1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallSite.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/Constant.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/IR/DataLayout.h"
63 #include "llvm/IR/DebugLoc.h"
64 #include "llvm/IR/DerivedTypes.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicsPowerPC.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/MC/MCContext.h"
76 #include "llvm/MC/MCExpr.h"
77 #include "llvm/MC/MCRegisterInfo.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
122 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
125 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
126 
127 STATISTIC(NumTailCalls, "Number of tail calls");
128 STATISTIC(NumSiblingCalls, "Number of sibling calls");
129 
130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
131 
132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
133 
134 // FIXME: Remove this once the bug has been fixed!
135 extern cl::opt<bool> ANDIGlueBug;
136 
137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
138                                      const PPCSubtarget &STI)
139     : TargetLowering(TM), Subtarget(STI) {
140   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
141   // arguments are at least 4/8 bytes aligned.
142   bool isPPC64 = Subtarget.isPPC64();
143   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
144 
145   // Set up the register classes.
146   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
147   if (!useSoftFloat()) {
148     if (hasSPE()) {
149       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
150       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
151     } else {
152       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
153       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
154     }
155   }
156 
157   // Match BITREVERSE to customized fast code sequence in the td file.
158   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
159   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
160 
161   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
162   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
163 
164   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
165   for (MVT VT : MVT::integer_valuetypes()) {
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
168   }
169 
170   if (Subtarget.isISA3_0()) {
171     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
172     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
174     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
175   } else {
176     // No extending loads from f16 or HW conversions back and forth.
177     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
178     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
179     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
180     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
181     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
182     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
183     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
184     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
185   }
186 
187   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
188 
189   // PowerPC has pre-inc load and store's.
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
200   if (!Subtarget.hasSPE()) {
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
202     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
204     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
205   }
206 
207   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
208   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
209   for (MVT VT : ScalarIntVTs) {
210     setOperationAction(ISD::ADDC, VT, Legal);
211     setOperationAction(ISD::ADDE, VT, Legal);
212     setOperationAction(ISD::SUBC, VT, Legal);
213     setOperationAction(ISD::SUBE, VT, Legal);
214   }
215 
216   if (Subtarget.useCRBits()) {
217     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
218 
219     if (isPPC64 || Subtarget.hasFPCVT()) {
220       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
221       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
222                          isPPC64 ? MVT::i64 : MVT::i32);
223       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
224       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
225                         isPPC64 ? MVT::i64 : MVT::i32);
226     } else {
227       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
228       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
229     }
230 
231     // PowerPC does not support direct load/store of condition registers.
232     setOperationAction(ISD::LOAD, MVT::i1, Custom);
233     setOperationAction(ISD::STORE, MVT::i1, Custom);
234 
235     // FIXME: Remove this once the ANDI glue bug is fixed:
236     if (ANDIGlueBug)
237       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
238 
239     for (MVT VT : MVT::integer_valuetypes()) {
240       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
241       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
242       setTruncStoreAction(VT, MVT::i1, Expand);
243     }
244 
245     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
246   }
247 
248   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
249   // PPC (the libcall is not available).
250   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
251   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
252 
253   // We do not currently implement these libm ops for PowerPC.
254   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
255   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
256   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
257   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
258   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
259   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
260 
261   // PowerPC has no SREM/UREM instructions unless we are on P9
262   // On P9 we may use a hardware instruction to compute the remainder.
263   // The instructions are not legalized directly because in the cases where the
264   // result of both the remainder and the division is required it is more
265   // efficient to compute the remainder from the result of the division rather
266   // than use the remainder instruction.
267   if (Subtarget.isISA3_0()) {
268     setOperationAction(ISD::SREM, MVT::i32, Custom);
269     setOperationAction(ISD::UREM, MVT::i32, Custom);
270     setOperationAction(ISD::SREM, MVT::i64, Custom);
271     setOperationAction(ISD::UREM, MVT::i64, Custom);
272   } else {
273     setOperationAction(ISD::SREM, MVT::i32, Expand);
274     setOperationAction(ISD::UREM, MVT::i32, Expand);
275     setOperationAction(ISD::SREM, MVT::i64, Expand);
276     setOperationAction(ISD::UREM, MVT::i64, Expand);
277   }
278 
279   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
280   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
282   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
284   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
288 
289   // We don't support sin/cos/sqrt/fmod/pow
290   setOperationAction(ISD::FSIN , MVT::f64, Expand);
291   setOperationAction(ISD::FCOS , MVT::f64, Expand);
292   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
293   setOperationAction(ISD::FREM , MVT::f64, Expand);
294   setOperationAction(ISD::FPOW , MVT::f64, Expand);
295   setOperationAction(ISD::FSIN , MVT::f32, Expand);
296   setOperationAction(ISD::FCOS , MVT::f32, Expand);
297   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
298   setOperationAction(ISD::FREM , MVT::f32, Expand);
299   setOperationAction(ISD::FPOW , MVT::f32, Expand);
300   if (Subtarget.hasSPE()) {
301     setOperationAction(ISD::FMA  , MVT::f64, Expand);
302     setOperationAction(ISD::FMA  , MVT::f32, Expand);
303   } else {
304     setOperationAction(ISD::FMA  , MVT::f64, Legal);
305     setOperationAction(ISD::FMA  , MVT::f32, Legal);
306   }
307 
308   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
309 
310   // If we're enabling GP optimizations, use hardware square root
311   if (!Subtarget.hasFSQRT() &&
312       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
313         Subtarget.hasFRE()))
314     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
315 
316   if (!Subtarget.hasFSQRT() &&
317       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
318         Subtarget.hasFRES()))
319     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
320 
321   if (Subtarget.hasFCPSGN()) {
322     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
323     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
324   } else {
325     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
326     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
327   }
328 
329   if (Subtarget.hasFPRND()) {
330     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
331     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
332     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
333     setOperationAction(ISD::FROUND, MVT::f64, Legal);
334 
335     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
336     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
337     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
338     setOperationAction(ISD::FROUND, MVT::f32, Legal);
339   }
340 
341   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
342   // to speed up scalar BSWAP64.
343   // CTPOP or CTTZ were introduced in P8/P9 respectively
344   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
345   if (Subtarget.hasP9Vector())
346     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
347   else
348     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
349   if (Subtarget.isISA3_0()) {
350     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
351     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
352   } else {
353     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
354     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
355   }
356 
357   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
358     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
359     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
360   } else {
361     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
362     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
363   }
364 
365   // PowerPC does not have ROTR
366   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
367   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
368 
369   if (!Subtarget.useCRBits()) {
370     // PowerPC does not have Select
371     setOperationAction(ISD::SELECT, MVT::i32, Expand);
372     setOperationAction(ISD::SELECT, MVT::i64, Expand);
373     setOperationAction(ISD::SELECT, MVT::f32, Expand);
374     setOperationAction(ISD::SELECT, MVT::f64, Expand);
375   }
376 
377   // PowerPC wants to turn select_cc of FP into fsel when possible.
378   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
379   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
380 
381   // PowerPC wants to optimize integer setcc a bit
382   if (!Subtarget.useCRBits())
383     setOperationAction(ISD::SETCC, MVT::i32, Custom);
384 
385   // PowerPC does not have BRCOND which requires SetCC
386   if (!Subtarget.useCRBits())
387     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
388 
389   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
390 
391   if (Subtarget.hasSPE()) {
392     // SPE has built-in conversions
393     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
394     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
395     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
396   } else {
397     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
398     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
399 
400     // PowerPC does not have [U|S]INT_TO_FP
401     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
402     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
403   }
404 
405   if (Subtarget.hasDirectMove() && isPPC64) {
406     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
407     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
408     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
409     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
410     if (TM.Options.UnsafeFPMath) {
411       setOperationAction(ISD::LRINT, MVT::f64, Legal);
412       setOperationAction(ISD::LRINT, MVT::f32, Legal);
413       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
414       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
415       setOperationAction(ISD::LROUND, MVT::f64, Legal);
416       setOperationAction(ISD::LROUND, MVT::f32, Legal);
417       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
418       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
419     }
420   } else {
421     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
422     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
423     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
424     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
425   }
426 
427   // We cannot sextinreg(i1).  Expand to shifts.
428   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
429 
430   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
431   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
432   // support continuation, user-level threading, and etc.. As a result, no
433   // other SjLj exception interfaces are implemented and please don't build
434   // your own exception handling based on them.
435   // LLVM/Clang supports zero-cost DWARF exception handling.
436   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
437   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
438 
439   // We want to legalize GlobalAddress and ConstantPool nodes into the
440   // appropriate instructions to materialize the address.
441   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
442   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
443   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
444   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
445   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
446   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
447   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
448   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
449   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
450   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
451 
452   // TRAP is legal.
453   setOperationAction(ISD::TRAP, MVT::Other, Legal);
454 
455   // TRAMPOLINE is custom lowered.
456   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
457   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
458 
459   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
460   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
461 
462   if (Subtarget.is64BitELFABI()) {
463     // VAARG always uses double-word chunks, so promote anything smaller.
464     setOperationAction(ISD::VAARG, MVT::i1, Promote);
465     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
466     setOperationAction(ISD::VAARG, MVT::i8, Promote);
467     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
468     setOperationAction(ISD::VAARG, MVT::i16, Promote);
469     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
470     setOperationAction(ISD::VAARG, MVT::i32, Promote);
471     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
472     setOperationAction(ISD::VAARG, MVT::Other, Expand);
473   } else if (Subtarget.is32BitELFABI()) {
474     // VAARG is custom lowered with the 32-bit SVR4 ABI.
475     setOperationAction(ISD::VAARG, MVT::Other, Custom);
476     setOperationAction(ISD::VAARG, MVT::i64, Custom);
477   } else
478     setOperationAction(ISD::VAARG, MVT::Other, Expand);
479 
480   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
481   if (Subtarget.is32BitELFABI())
482     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
483   else
484     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
485 
486   // Use the default implementation.
487   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
488   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
489   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
490   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
491   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
492   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
493   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
494   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
495   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
496 
497   // We want to custom lower some of our intrinsics.
498   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
499 
500   // To handle counter-based loop conditions.
501   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
502 
503   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
504   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
505   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
506   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
507 
508   // Comparisons that require checking two conditions.
509   if (Subtarget.hasSPE()) {
510     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
511     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
512     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
513     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
514   }
515   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
516   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
517   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
518   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
519   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
520   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
521   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
522   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
523   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
524   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
525   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
526   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
527 
528   if (Subtarget.has64BitSupport()) {
529     // They also have instructions for converting between i64 and fp.
530     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
531     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
532     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
533     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
534     // This is just the low 32 bits of a (signed) fp->i64 conversion.
535     // We cannot do this with Promote because i64 is not a legal type.
536     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
537 
538     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
539       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
540   } else {
541     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
542     if (Subtarget.hasSPE())
543       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
544     else
545       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
546   }
547 
548   // With the instructions enabled under FPCVT, we can do everything.
549   if (Subtarget.hasFPCVT()) {
550     if (Subtarget.has64BitSupport()) {
551       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
552       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
553       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
554       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
555     }
556 
557     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
558     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
559     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
561   }
562 
563   if (Subtarget.use64BitRegs()) {
564     // 64-bit PowerPC implementations can support i64 types directly
565     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
566     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
567     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
568     // 64-bit PowerPC wants to expand i128 shifts itself.
569     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
570     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
571     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
572   } else {
573     // 32-bit PowerPC wants to expand i64 shifts itself.
574     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
575     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
576     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
577   }
578 
579   if (Subtarget.hasVSX()) {
580     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
581     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
582     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
583     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
584   }
585 
586   if (Subtarget.hasAltivec()) {
587     // First set operation action for all vector types to expand. Then we
588     // will selectively turn on ones that can be effectively codegen'd.
589     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
590       // add/sub are legal for all supported vector VT's.
591       setOperationAction(ISD::ADD, VT, Legal);
592       setOperationAction(ISD::SUB, VT, Legal);
593 
594       // For v2i64, these are only valid with P8Vector. This is corrected after
595       // the loop.
596       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
597         setOperationAction(ISD::SMAX, VT, Legal);
598         setOperationAction(ISD::SMIN, VT, Legal);
599         setOperationAction(ISD::UMAX, VT, Legal);
600         setOperationAction(ISD::UMIN, VT, Legal);
601       }
602       else {
603         setOperationAction(ISD::SMAX, VT, Expand);
604         setOperationAction(ISD::SMIN, VT, Expand);
605         setOperationAction(ISD::UMAX, VT, Expand);
606         setOperationAction(ISD::UMIN, VT, Expand);
607       }
608 
609       if (Subtarget.hasVSX()) {
610         setOperationAction(ISD::FMAXNUM, VT, Legal);
611         setOperationAction(ISD::FMINNUM, VT, Legal);
612       }
613 
614       // Vector instructions introduced in P8
615       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
616         setOperationAction(ISD::CTPOP, VT, Legal);
617         setOperationAction(ISD::CTLZ, VT, Legal);
618       }
619       else {
620         setOperationAction(ISD::CTPOP, VT, Expand);
621         setOperationAction(ISD::CTLZ, VT, Expand);
622       }
623 
624       // Vector instructions introduced in P9
625       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
626         setOperationAction(ISD::CTTZ, VT, Legal);
627       else
628         setOperationAction(ISD::CTTZ, VT, Expand);
629 
630       // We promote all shuffles to v16i8.
631       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
632       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
633 
634       // We promote all non-typed operations to v4i32.
635       setOperationAction(ISD::AND   , VT, Promote);
636       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
637       setOperationAction(ISD::OR    , VT, Promote);
638       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
639       setOperationAction(ISD::XOR   , VT, Promote);
640       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
641       setOperationAction(ISD::LOAD  , VT, Promote);
642       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
643       setOperationAction(ISD::SELECT, VT, Promote);
644       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
645       setOperationAction(ISD::VSELECT, VT, Legal);
646       setOperationAction(ISD::SELECT_CC, VT, Promote);
647       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
648       setOperationAction(ISD::STORE, VT, Promote);
649       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
650 
651       // No other operations are legal.
652       setOperationAction(ISD::MUL , VT, Expand);
653       setOperationAction(ISD::SDIV, VT, Expand);
654       setOperationAction(ISD::SREM, VT, Expand);
655       setOperationAction(ISD::UDIV, VT, Expand);
656       setOperationAction(ISD::UREM, VT, Expand);
657       setOperationAction(ISD::FDIV, VT, Expand);
658       setOperationAction(ISD::FREM, VT, Expand);
659       setOperationAction(ISD::FNEG, VT, Expand);
660       setOperationAction(ISD::FSQRT, VT, Expand);
661       setOperationAction(ISD::FLOG, VT, Expand);
662       setOperationAction(ISD::FLOG10, VT, Expand);
663       setOperationAction(ISD::FLOG2, VT, Expand);
664       setOperationAction(ISD::FEXP, VT, Expand);
665       setOperationAction(ISD::FEXP2, VT, Expand);
666       setOperationAction(ISD::FSIN, VT, Expand);
667       setOperationAction(ISD::FCOS, VT, Expand);
668       setOperationAction(ISD::FABS, VT, Expand);
669       setOperationAction(ISD::FFLOOR, VT, Expand);
670       setOperationAction(ISD::FCEIL,  VT, Expand);
671       setOperationAction(ISD::FTRUNC, VT, Expand);
672       setOperationAction(ISD::FRINT,  VT, Expand);
673       setOperationAction(ISD::FNEARBYINT, VT, Expand);
674       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
675       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
676       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
677       setOperationAction(ISD::MULHU, VT, Expand);
678       setOperationAction(ISD::MULHS, VT, Expand);
679       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
680       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
681       setOperationAction(ISD::UDIVREM, VT, Expand);
682       setOperationAction(ISD::SDIVREM, VT, Expand);
683       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
684       setOperationAction(ISD::FPOW, VT, Expand);
685       setOperationAction(ISD::BSWAP, VT, Expand);
686       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
687       setOperationAction(ISD::ROTL, VT, Expand);
688       setOperationAction(ISD::ROTR, VT, Expand);
689 
690       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
691         setTruncStoreAction(VT, InnerVT, Expand);
692         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
693         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
694         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
695       }
696     }
697     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
698     if (!Subtarget.hasP8Vector()) {
699       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
700       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
701       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
702       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
703     }
704 
705     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
706       setOperationAction(ISD::ABS, VT, Custom);
707 
708     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
709     // with merges, splats, etc.
710     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
711 
712     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
713     // are cheap, so handle them before they get expanded to scalar.
714     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
715     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
716     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
717     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
718     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
719 
720     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
721     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
722     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
723     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
724     setOperationAction(ISD::SELECT, MVT::v4i32,
725                        Subtarget.useCRBits() ? Legal : Expand);
726     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
727     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
728     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
729     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
730     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
731     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
732     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
733     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
734     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
735 
736     // Without hasP8Altivec set, v2i64 SMAX isn't available.
737     // But ABS custom lowering requires SMAX support.
738     if (!Subtarget.hasP8Altivec())
739       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
740 
741     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
742     if (Subtarget.hasAltivec())
743       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
744         setOperationAction(ISD::ROTL, VT, Legal);
745     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
746     if (Subtarget.hasP8Altivec())
747       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
748 
749     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
750     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
751     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
752     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
753 
754     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
755     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
756 
757     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
758       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
759       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
760     }
761 
762     if (Subtarget.hasP8Altivec())
763       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
764     else
765       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
766 
767     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
768     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
769 
770     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
771     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
772 
773     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
774     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
775     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
776     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
777 
778     // Altivec does not contain unordered floating-point compare instructions
779     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
780     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
781     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
782     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
783 
784     if (Subtarget.hasVSX()) {
785       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
786       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
787       if (Subtarget.hasP8Vector()) {
788         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
789         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
790       }
791       if (Subtarget.hasDirectMove() && isPPC64) {
792         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
793         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
794         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
795         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
796         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
797         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
798         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
799         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
800       }
801       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
802 
803       // The nearbyint variants are not allowed to raise the inexact exception
804       // so we can only code-gen them with unsafe math.
805       if (TM.Options.UnsafeFPMath) {
806         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
807         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
808       }
809 
810       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
811       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
812       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
813       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
814       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
815       setOperationAction(ISD::FROUND, MVT::f64, Legal);
816 
817       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
818       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
819       setOperationAction(ISD::FROUND, MVT::f32, Legal);
820 
821       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
822       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
823 
824       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
825       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
826 
827       // Share the Altivec comparison restrictions.
828       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
829       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
830       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
831       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
832 
833       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
834       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
835 
836       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
837 
838       if (Subtarget.hasP8Vector())
839         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
840 
841       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
842 
843       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
844       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
845       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
846 
847       if (Subtarget.hasP8Altivec()) {
848         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
849         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
850         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
851 
852         // 128 bit shifts can be accomplished via 3 instructions for SHL and
853         // SRL, but not for SRA because of the instructions available:
854         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
855         // doing
856         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
857         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
858         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
859 
860         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
861       }
862       else {
863         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
864         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
865         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
866 
867         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
868 
869         // VSX v2i64 only supports non-arithmetic operations.
870         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
871         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
872       }
873 
874       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
875       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
876       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
877       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
878 
879       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
880 
881       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
882       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
883       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
884       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
885 
886       // Custom handling for partial vectors of integers converted to
887       // floating point. We already have optimal handling for v2i32 through
888       // the DAG combine, so those aren't necessary.
889       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
890       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
891       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
892       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
893       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
894       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
895       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
896       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
897 
898       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
899       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
900       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
901       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
902       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
903       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
904 
905       if (Subtarget.hasDirectMove())
906         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
907       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
908 
909       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
910     }
911 
912     if (Subtarget.hasP8Altivec()) {
913       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
914       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
915     }
916 
917     if (Subtarget.hasP9Vector()) {
918       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
919       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
920 
921       // 128 bit shifts can be accomplished via 3 instructions for SHL and
922       // SRL, but not for SRA because of the instructions available:
923       // VS{RL} and VS{RL}O.
924       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
925       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
926       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
927 
928       if (EnableQuadPrecision) {
929         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
930         setOperationAction(ISD::FADD, MVT::f128, Legal);
931         setOperationAction(ISD::FSUB, MVT::f128, Legal);
932         setOperationAction(ISD::FDIV, MVT::f128, Legal);
933         setOperationAction(ISD::FMUL, MVT::f128, Legal);
934         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
935         // No extending loads to f128 on PPC.
936         for (MVT FPT : MVT::fp_valuetypes())
937           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
938         setOperationAction(ISD::FMA, MVT::f128, Legal);
939         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
940         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
941         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
942         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
943         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
944         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
945 
946         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
947         setOperationAction(ISD::FRINT, MVT::f128, Legal);
948         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
949         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
950         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
951         setOperationAction(ISD::FROUND, MVT::f128, Legal);
952 
953         setOperationAction(ISD::SELECT, MVT::f128, Expand);
954         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
955         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
956         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
957         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
958         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
959         // No implementation for these ops for PowerPC.
960         setOperationAction(ISD::FSIN , MVT::f128, Expand);
961         setOperationAction(ISD::FCOS , MVT::f128, Expand);
962         setOperationAction(ISD::FPOW, MVT::f128, Expand);
963         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
964         setOperationAction(ISD::FREM, MVT::f128, Expand);
965       }
966       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
967       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
968       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
969       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
970       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
971     }
972 
973     if (Subtarget.hasP9Altivec()) {
974       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
975       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
976 
977       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
978       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
979       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
980       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
981       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
982       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
983       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
984     }
985   }
986 
987   if (Subtarget.hasQPX()) {
988     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
989     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
990     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
991     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
992 
993     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
994     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
995 
996     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
997     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
998 
999     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1000     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1001 
1002     if (!Subtarget.useCRBits())
1003       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1004     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1005 
1006     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1008     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1009     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1010     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1011     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1012     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1013 
1014     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1015     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1016 
1017     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1018     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1019 
1020     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1021     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1022     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1023     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1024     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1025     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1026     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1027     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1028     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1029     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1030 
1031     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1032     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1033 
1034     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1035     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1036 
1037     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1038 
1039     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1040     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1041     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1042     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1043 
1044     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1045     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1046 
1047     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1048     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1049 
1050     if (!Subtarget.useCRBits())
1051       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1052     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1053 
1054     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1055     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1056     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1057     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1058     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1059     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1060     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1061 
1062     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1063     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1064 
1065     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1066     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1067     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1068     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1069     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1070     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1071     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1072     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1073     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1074     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1075 
1076     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1077     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1078 
1079     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1080     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1081 
1082     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1083 
1084     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1085     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1086     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1087 
1088     if (!Subtarget.useCRBits())
1089       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1090     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1091 
1092     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1093     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1094 
1095     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1096     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1097     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1098     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1099     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1100     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1101     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1102 
1103     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1104     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1105 
1106     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1107 
1108     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1109     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1110     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1111     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1112 
1113     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1114     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1115     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1116     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1117 
1118     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1119     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1120 
1121     // These need to set FE_INEXACT, and so cannot be vectorized here.
1122     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1123     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1124 
1125     if (TM.Options.UnsafeFPMath) {
1126       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1127       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1128 
1129       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1130       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1131     } else {
1132       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1133       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1134 
1135       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1136       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1137     }
1138   }
1139 
1140   if (Subtarget.has64BitSupport())
1141     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1142 
1143   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1144 
1145   if (isPPC64)
1146     setMaxAtomicSizeInBitsSupported(64);
1147   else {
1148     setMaxAtomicSizeInBitsSupported(32);
1149     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1150     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1151   }
1152 
1153   setBooleanContents(ZeroOrOneBooleanContent);
1154 
1155   if (Subtarget.hasAltivec()) {
1156     // Altivec instructions set fields to all zeros or all ones.
1157     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1158   }
1159 
1160   if (!isPPC64) {
1161     // These libcalls are not available in 32-bit.
1162     setLibcallName(RTLIB::SHL_I128, nullptr);
1163     setLibcallName(RTLIB::SRL_I128, nullptr);
1164     setLibcallName(RTLIB::SRA_I128, nullptr);
1165   }
1166 
1167   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1168 
1169   // We have target-specific dag combine patterns for the following nodes:
1170   setTargetDAGCombine(ISD::ADD);
1171   setTargetDAGCombine(ISD::SHL);
1172   setTargetDAGCombine(ISD::SRA);
1173   setTargetDAGCombine(ISD::SRL);
1174   setTargetDAGCombine(ISD::MUL);
1175   setTargetDAGCombine(ISD::SINT_TO_FP);
1176   setTargetDAGCombine(ISD::BUILD_VECTOR);
1177   if (Subtarget.hasFPCVT())
1178     setTargetDAGCombine(ISD::UINT_TO_FP);
1179   setTargetDAGCombine(ISD::LOAD);
1180   setTargetDAGCombine(ISD::STORE);
1181   setTargetDAGCombine(ISD::BR_CC);
1182   if (Subtarget.useCRBits())
1183     setTargetDAGCombine(ISD::BRCOND);
1184   setTargetDAGCombine(ISD::BSWAP);
1185   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1186   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1187   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1188 
1189   setTargetDAGCombine(ISD::SIGN_EXTEND);
1190   setTargetDAGCombine(ISD::ZERO_EXTEND);
1191   setTargetDAGCombine(ISD::ANY_EXTEND);
1192 
1193   setTargetDAGCombine(ISD::TRUNCATE);
1194   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1195 
1196 
1197   if (Subtarget.useCRBits()) {
1198     setTargetDAGCombine(ISD::TRUNCATE);
1199     setTargetDAGCombine(ISD::SETCC);
1200     setTargetDAGCombine(ISD::SELECT_CC);
1201   }
1202 
1203   // Use reciprocal estimates.
1204   if (TM.Options.UnsafeFPMath) {
1205     setTargetDAGCombine(ISD::FDIV);
1206     setTargetDAGCombine(ISD::FSQRT);
1207   }
1208 
1209   if (Subtarget.hasP9Altivec()) {
1210     setTargetDAGCombine(ISD::ABS);
1211     setTargetDAGCombine(ISD::VSELECT);
1212   }
1213 
1214   // Darwin long double math library functions have $LDBL128 appended.
1215   if (Subtarget.isDarwin()) {
1216     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1217     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1218     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1219     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1220     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1221     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1222     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1223     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1224     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1225     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1226   }
1227 
1228   if (EnableQuadPrecision) {
1229     setLibcallName(RTLIB::LOG_F128, "logf128");
1230     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1231     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1232     setLibcallName(RTLIB::EXP_F128, "expf128");
1233     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1234     setLibcallName(RTLIB::SIN_F128, "sinf128");
1235     setLibcallName(RTLIB::COS_F128, "cosf128");
1236     setLibcallName(RTLIB::POW_F128, "powf128");
1237     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1238     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1239     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1240     setLibcallName(RTLIB::REM_F128, "fmodf128");
1241   }
1242 
1243   // With 32 condition bits, we don't need to sink (and duplicate) compares
1244   // aggressively in CodeGenPrep.
1245   if (Subtarget.useCRBits()) {
1246     setHasMultipleConditionRegisters();
1247     setJumpIsExpensive();
1248   }
1249 
1250   setMinFunctionAlignment(Align(4));
1251   if (Subtarget.isDarwin())
1252     setPrefFunctionAlignment(Align(16));
1253 
1254   switch (Subtarget.getCPUDirective()) {
1255   default: break;
1256   case PPC::DIR_970:
1257   case PPC::DIR_A2:
1258   case PPC::DIR_E500:
1259   case PPC::DIR_E500mc:
1260   case PPC::DIR_E5500:
1261   case PPC::DIR_PWR4:
1262   case PPC::DIR_PWR5:
1263   case PPC::DIR_PWR5X:
1264   case PPC::DIR_PWR6:
1265   case PPC::DIR_PWR6X:
1266   case PPC::DIR_PWR7:
1267   case PPC::DIR_PWR8:
1268   case PPC::DIR_PWR9:
1269   case PPC::DIR_PWR_FUTURE:
1270     setPrefLoopAlignment(Align(16));
1271     setPrefFunctionAlignment(Align(16));
1272     break;
1273   }
1274 
1275   if (Subtarget.enableMachineScheduler())
1276     setSchedulingPreference(Sched::Source);
1277   else
1278     setSchedulingPreference(Sched::Hybrid);
1279 
1280   computeRegisterProperties(STI.getRegisterInfo());
1281 
1282   // The Freescale cores do better with aggressive inlining of memcpy and
1283   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1284   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1285       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1286     MaxStoresPerMemset = 32;
1287     MaxStoresPerMemsetOptSize = 16;
1288     MaxStoresPerMemcpy = 32;
1289     MaxStoresPerMemcpyOptSize = 8;
1290     MaxStoresPerMemmove = 32;
1291     MaxStoresPerMemmoveOptSize = 8;
1292   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1293     // The A2 also benefits from (very) aggressive inlining of memcpy and
1294     // friends. The overhead of a the function call, even when warm, can be
1295     // over one hundred cycles.
1296     MaxStoresPerMemset = 128;
1297     MaxStoresPerMemcpy = 128;
1298     MaxStoresPerMemmove = 128;
1299     MaxLoadsPerMemcmp = 128;
1300   } else {
1301     MaxLoadsPerMemcmp = 8;
1302     MaxLoadsPerMemcmpOptSize = 4;
1303   }
1304 }
1305 
1306 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1307 /// the desired ByVal argument alignment.
1308 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1309                              unsigned MaxMaxAlign) {
1310   if (MaxAlign == MaxMaxAlign)
1311     return;
1312   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1313     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1314       MaxAlign = 32;
1315     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1316       MaxAlign = 16;
1317   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1318     unsigned EltAlign = 0;
1319     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1320     if (EltAlign > MaxAlign)
1321       MaxAlign = EltAlign;
1322   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1323     for (auto *EltTy : STy->elements()) {
1324       unsigned EltAlign = 0;
1325       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1326       if (EltAlign > MaxAlign)
1327         MaxAlign = EltAlign;
1328       if (MaxAlign == MaxMaxAlign)
1329         break;
1330     }
1331   }
1332 }
1333 
1334 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1335 /// function arguments in the caller parameter area.
1336 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1337                                                   const DataLayout &DL) const {
1338   // Darwin passes everything on 4 byte boundary.
1339   if (Subtarget.isDarwin())
1340     return 4;
1341 
1342   // 16byte and wider vectors are passed on 16byte boundary.
1343   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1344   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1345   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1346     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1347   return Align;
1348 }
1349 
1350 bool PPCTargetLowering::useSoftFloat() const {
1351   return Subtarget.useSoftFloat();
1352 }
1353 
1354 bool PPCTargetLowering::hasSPE() const {
1355   return Subtarget.hasSPE();
1356 }
1357 
1358 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1359   return VT.isScalarInteger();
1360 }
1361 
1362 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1363   switch ((PPCISD::NodeType)Opcode) {
1364   case PPCISD::FIRST_NUMBER:    break;
1365   case PPCISD::FSEL:            return "PPCISD::FSEL";
1366   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1367   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1368   case PPCISD::FCFID:           return "PPCISD::FCFID";
1369   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1370   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1371   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1372   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1373   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1374   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1375   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1376   case PPCISD::FP_TO_UINT_IN_VSR:
1377                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1378   case PPCISD::FP_TO_SINT_IN_VSR:
1379                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1380   case PPCISD::FRE:             return "PPCISD::FRE";
1381   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1382   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1383   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1384   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1385   case PPCISD::VPERM:           return "PPCISD::VPERM";
1386   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1387   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1388   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1389   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1390   case PPCISD::CMPB:            return "PPCISD::CMPB";
1391   case PPCISD::Hi:              return "PPCISD::Hi";
1392   case PPCISD::Lo:              return "PPCISD::Lo";
1393   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1394   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1395   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1396   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1397   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1398   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1399   case PPCISD::SRL:             return "PPCISD::SRL";
1400   case PPCISD::SRA:             return "PPCISD::SRA";
1401   case PPCISD::SHL:             return "PPCISD::SHL";
1402   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1403   case PPCISD::CALL:            return "PPCISD::CALL";
1404   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1405   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1406   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1407   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1408   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1409   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1410   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1411   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1412   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1413   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1414   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1415   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1416   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1417   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1418   case PPCISD::ANDI_rec_1_EQ_BIT:
1419     return "PPCISD::ANDI_rec_1_EQ_BIT";
1420   case PPCISD::ANDI_rec_1_GT_BIT:
1421     return "PPCISD::ANDI_rec_1_GT_BIT";
1422   case PPCISD::VCMP:            return "PPCISD::VCMP";
1423   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1424   case PPCISD::LBRX:            return "PPCISD::LBRX";
1425   case PPCISD::STBRX:           return "PPCISD::STBRX";
1426   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1427   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1428   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1429   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1430   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1431   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1432   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1433   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1434   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1435   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1436   case PPCISD::ST_VSR_SCAL_INT:
1437                                 return "PPCISD::ST_VSR_SCAL_INT";
1438   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1439   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1440   case PPCISD::BDZ:             return "PPCISD::BDZ";
1441   case PPCISD::MFFS:            return "PPCISD::MFFS";
1442   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1443   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1444   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1445   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1446   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1447   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1448   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1449   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1450   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1451   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1452   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1453   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1454   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1455   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1456   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1457   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1458   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1459   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1460   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1461   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1462   case PPCISD::SC:              return "PPCISD::SC";
1463   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1464   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1465   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1466   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1467   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1468   case PPCISD::VABSD:           return "PPCISD::VABSD";
1469   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1470   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1471   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1472   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1473   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1474   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1475   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1476   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1477   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1478   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1479   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1480   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1481   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1482   }
1483   return nullptr;
1484 }
1485 
1486 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1487                                           EVT VT) const {
1488   if (!VT.isVector())
1489     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1490 
1491   if (Subtarget.hasQPX())
1492     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1493 
1494   return VT.changeVectorElementTypeToInteger();
1495 }
1496 
1497 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1498   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1499   return true;
1500 }
1501 
1502 //===----------------------------------------------------------------------===//
1503 // Node matching predicates, for use by the tblgen matching code.
1504 //===----------------------------------------------------------------------===//
1505 
1506 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1507 static bool isFloatingPointZero(SDValue Op) {
1508   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1509     return CFP->getValueAPF().isZero();
1510   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1511     // Maybe this has already been legalized into the constant pool?
1512     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1513       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1514         return CFP->getValueAPF().isZero();
1515   }
1516   return false;
1517 }
1518 
1519 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1520 /// true if Op is undef or if it matches the specified value.
1521 static bool isConstantOrUndef(int Op, int Val) {
1522   return Op < 0 || Op == Val;
1523 }
1524 
1525 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1526 /// VPKUHUM instruction.
1527 /// The ShuffleKind distinguishes between big-endian operations with
1528 /// two different inputs (0), either-endian operations with two identical
1529 /// inputs (1), and little-endian operations with two different inputs (2).
1530 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1531 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1532                                SelectionDAG &DAG) {
1533   bool IsLE = DAG.getDataLayout().isLittleEndian();
1534   if (ShuffleKind == 0) {
1535     if (IsLE)
1536       return false;
1537     for (unsigned i = 0; i != 16; ++i)
1538       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1539         return false;
1540   } else if (ShuffleKind == 2) {
1541     if (!IsLE)
1542       return false;
1543     for (unsigned i = 0; i != 16; ++i)
1544       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1545         return false;
1546   } else if (ShuffleKind == 1) {
1547     unsigned j = IsLE ? 0 : 1;
1548     for (unsigned i = 0; i != 8; ++i)
1549       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1550           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1551         return false;
1552   }
1553   return true;
1554 }
1555 
1556 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1557 /// VPKUWUM instruction.
1558 /// The ShuffleKind distinguishes between big-endian operations with
1559 /// two different inputs (0), either-endian operations with two identical
1560 /// inputs (1), and little-endian operations with two different inputs (2).
1561 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1562 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1563                                SelectionDAG &DAG) {
1564   bool IsLE = DAG.getDataLayout().isLittleEndian();
1565   if (ShuffleKind == 0) {
1566     if (IsLE)
1567       return false;
1568     for (unsigned i = 0; i != 16; i += 2)
1569       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1570           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1571         return false;
1572   } else if (ShuffleKind == 2) {
1573     if (!IsLE)
1574       return false;
1575     for (unsigned i = 0; i != 16; i += 2)
1576       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1577           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1578         return false;
1579   } else if (ShuffleKind == 1) {
1580     unsigned j = IsLE ? 0 : 2;
1581     for (unsigned i = 0; i != 8; i += 2)
1582       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1583           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1584           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1585           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1586         return false;
1587   }
1588   return true;
1589 }
1590 
1591 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1592 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1593 /// current subtarget.
1594 ///
1595 /// The ShuffleKind distinguishes between big-endian operations with
1596 /// two different inputs (0), either-endian operations with two identical
1597 /// inputs (1), and little-endian operations with two different inputs (2).
1598 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1599 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1600                                SelectionDAG &DAG) {
1601   const PPCSubtarget& Subtarget =
1602       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1603   if (!Subtarget.hasP8Vector())
1604     return false;
1605 
1606   bool IsLE = DAG.getDataLayout().isLittleEndian();
1607   if (ShuffleKind == 0) {
1608     if (IsLE)
1609       return false;
1610     for (unsigned i = 0; i != 16; i += 4)
1611       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1612           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1613           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1614           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1615         return false;
1616   } else if (ShuffleKind == 2) {
1617     if (!IsLE)
1618       return false;
1619     for (unsigned i = 0; i != 16; i += 4)
1620       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1621           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1622           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1623           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1624         return false;
1625   } else if (ShuffleKind == 1) {
1626     unsigned j = IsLE ? 0 : 4;
1627     for (unsigned i = 0; i != 8; i += 4)
1628       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1629           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1630           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1631           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1632           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1633           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1634           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1635           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1636         return false;
1637   }
1638   return true;
1639 }
1640 
1641 /// isVMerge - Common function, used to match vmrg* shuffles.
1642 ///
1643 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1644                      unsigned LHSStart, unsigned RHSStart) {
1645   if (N->getValueType(0) != MVT::v16i8)
1646     return false;
1647   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1648          "Unsupported merge size!");
1649 
1650   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1651     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1652       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1653                              LHSStart+j+i*UnitSize) ||
1654           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1655                              RHSStart+j+i*UnitSize))
1656         return false;
1657     }
1658   return true;
1659 }
1660 
1661 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1662 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1663 /// The ShuffleKind distinguishes between big-endian merges with two
1664 /// different inputs (0), either-endian merges with two identical inputs (1),
1665 /// and little-endian merges with two different inputs (2).  For the latter,
1666 /// the input operands are swapped (see PPCInstrAltivec.td).
1667 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1668                              unsigned ShuffleKind, SelectionDAG &DAG) {
1669   if (DAG.getDataLayout().isLittleEndian()) {
1670     if (ShuffleKind == 1) // unary
1671       return isVMerge(N, UnitSize, 0, 0);
1672     else if (ShuffleKind == 2) // swapped
1673       return isVMerge(N, UnitSize, 0, 16);
1674     else
1675       return false;
1676   } else {
1677     if (ShuffleKind == 1) // unary
1678       return isVMerge(N, UnitSize, 8, 8);
1679     else if (ShuffleKind == 0) // normal
1680       return isVMerge(N, UnitSize, 8, 24);
1681     else
1682       return false;
1683   }
1684 }
1685 
1686 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1687 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1688 /// The ShuffleKind distinguishes between big-endian merges with two
1689 /// different inputs (0), either-endian merges with two identical inputs (1),
1690 /// and little-endian merges with two different inputs (2).  For the latter,
1691 /// the input operands are swapped (see PPCInstrAltivec.td).
1692 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1693                              unsigned ShuffleKind, SelectionDAG &DAG) {
1694   if (DAG.getDataLayout().isLittleEndian()) {
1695     if (ShuffleKind == 1) // unary
1696       return isVMerge(N, UnitSize, 8, 8);
1697     else if (ShuffleKind == 2) // swapped
1698       return isVMerge(N, UnitSize, 8, 24);
1699     else
1700       return false;
1701   } else {
1702     if (ShuffleKind == 1) // unary
1703       return isVMerge(N, UnitSize, 0, 0);
1704     else if (ShuffleKind == 0) // normal
1705       return isVMerge(N, UnitSize, 0, 16);
1706     else
1707       return false;
1708   }
1709 }
1710 
1711 /**
1712  * Common function used to match vmrgew and vmrgow shuffles
1713  *
1714  * The indexOffset determines whether to look for even or odd words in
1715  * the shuffle mask. This is based on the of the endianness of the target
1716  * machine.
1717  *   - Little Endian:
1718  *     - Use offset of 0 to check for odd elements
1719  *     - Use offset of 4 to check for even elements
1720  *   - Big Endian:
1721  *     - Use offset of 0 to check for even elements
1722  *     - Use offset of 4 to check for odd elements
1723  * A detailed description of the vector element ordering for little endian and
1724  * big endian can be found at
1725  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1726  * Targeting your applications - what little endian and big endian IBM XL C/C++
1727  * compiler differences mean to you
1728  *
1729  * The mask to the shuffle vector instruction specifies the indices of the
1730  * elements from the two input vectors to place in the result. The elements are
1731  * numbered in array-access order, starting with the first vector. These vectors
1732  * are always of type v16i8, thus each vector will contain 16 elements of size
1733  * 8. More info on the shuffle vector can be found in the
1734  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1735  * Language Reference.
1736  *
1737  * The RHSStartValue indicates whether the same input vectors are used (unary)
1738  * or two different input vectors are used, based on the following:
1739  *   - If the instruction uses the same vector for both inputs, the range of the
1740  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1741  *     be 0.
1742  *   - If the instruction has two different vectors then the range of the
1743  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1744  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1745  *     to 31 specify elements in the second vector).
1746  *
1747  * \param[in] N The shuffle vector SD Node to analyze
1748  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1749  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1750  * vector to the shuffle_vector instruction
1751  * \return true iff this shuffle vector represents an even or odd word merge
1752  */
1753 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1754                      unsigned RHSStartValue) {
1755   if (N->getValueType(0) != MVT::v16i8)
1756     return false;
1757 
1758   for (unsigned i = 0; i < 2; ++i)
1759     for (unsigned j = 0; j < 4; ++j)
1760       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1761                              i*RHSStartValue+j+IndexOffset) ||
1762           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1763                              i*RHSStartValue+j+IndexOffset+8))
1764         return false;
1765   return true;
1766 }
1767 
1768 /**
1769  * Determine if the specified shuffle mask is suitable for the vmrgew or
1770  * vmrgow instructions.
1771  *
1772  * \param[in] N The shuffle vector SD Node to analyze
1773  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1774  * \param[in] ShuffleKind Identify the type of merge:
1775  *   - 0 = big-endian merge with two different inputs;
1776  *   - 1 = either-endian merge with two identical inputs;
1777  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1778  *     little-endian merges).
1779  * \param[in] DAG The current SelectionDAG
1780  * \return true iff this shuffle mask
1781  */
1782 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1783                               unsigned ShuffleKind, SelectionDAG &DAG) {
1784   if (DAG.getDataLayout().isLittleEndian()) {
1785     unsigned indexOffset = CheckEven ? 4 : 0;
1786     if (ShuffleKind == 1) // Unary
1787       return isVMerge(N, indexOffset, 0);
1788     else if (ShuffleKind == 2) // swapped
1789       return isVMerge(N, indexOffset, 16);
1790     else
1791       return false;
1792   }
1793   else {
1794     unsigned indexOffset = CheckEven ? 0 : 4;
1795     if (ShuffleKind == 1) // Unary
1796       return isVMerge(N, indexOffset, 0);
1797     else if (ShuffleKind == 0) // Normal
1798       return isVMerge(N, indexOffset, 16);
1799     else
1800       return false;
1801   }
1802   return false;
1803 }
1804 
1805 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1806 /// amount, otherwise return -1.
1807 /// The ShuffleKind distinguishes between big-endian operations with two
1808 /// different inputs (0), either-endian operations with two identical inputs
1809 /// (1), and little-endian operations with two different inputs (2).  For the
1810 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1811 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1812                              SelectionDAG &DAG) {
1813   if (N->getValueType(0) != MVT::v16i8)
1814     return -1;
1815 
1816   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1817 
1818   // Find the first non-undef value in the shuffle mask.
1819   unsigned i;
1820   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1821     /*search*/;
1822 
1823   if (i == 16) return -1;  // all undef.
1824 
1825   // Otherwise, check to see if the rest of the elements are consecutively
1826   // numbered from this value.
1827   unsigned ShiftAmt = SVOp->getMaskElt(i);
1828   if (ShiftAmt < i) return -1;
1829 
1830   ShiftAmt -= i;
1831   bool isLE = DAG.getDataLayout().isLittleEndian();
1832 
1833   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1834     // Check the rest of the elements to see if they are consecutive.
1835     for (++i; i != 16; ++i)
1836       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1837         return -1;
1838   } else if (ShuffleKind == 1) {
1839     // Check the rest of the elements to see if they are consecutive.
1840     for (++i; i != 16; ++i)
1841       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1842         return -1;
1843   } else
1844     return -1;
1845 
1846   if (isLE)
1847     ShiftAmt = 16 - ShiftAmt;
1848 
1849   return ShiftAmt;
1850 }
1851 
1852 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1853 /// specifies a splat of a single element that is suitable for input to
1854 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1855 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1856   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1857          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1858 
1859   // The consecutive indices need to specify an element, not part of two
1860   // different elements.  So abandon ship early if this isn't the case.
1861   if (N->getMaskElt(0) % EltSize != 0)
1862     return false;
1863 
1864   // This is a splat operation if each element of the permute is the same, and
1865   // if the value doesn't reference the second vector.
1866   unsigned ElementBase = N->getMaskElt(0);
1867 
1868   // FIXME: Handle UNDEF elements too!
1869   if (ElementBase >= 16)
1870     return false;
1871 
1872   // Check that the indices are consecutive, in the case of a multi-byte element
1873   // splatted with a v16i8 mask.
1874   for (unsigned i = 1; i != EltSize; ++i)
1875     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1876       return false;
1877 
1878   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1879     if (N->getMaskElt(i) < 0) continue;
1880     for (unsigned j = 0; j != EltSize; ++j)
1881       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1882         return false;
1883   }
1884   return true;
1885 }
1886 
1887 /// Check that the mask is shuffling N byte elements. Within each N byte
1888 /// element of the mask, the indices could be either in increasing or
1889 /// decreasing order as long as they are consecutive.
1890 /// \param[in] N the shuffle vector SD Node to analyze
1891 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1892 /// Word/DoubleWord/QuadWord).
1893 /// \param[in] StepLen the delta indices number among the N byte element, if
1894 /// the mask is in increasing/decreasing order then it is 1/-1.
1895 /// \return true iff the mask is shuffling N byte elements.
1896 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1897                                    int StepLen) {
1898   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1899          "Unexpected element width.");
1900   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1901 
1902   unsigned NumOfElem = 16 / Width;
1903   unsigned MaskVal[16]; //  Width is never greater than 16
1904   for (unsigned i = 0; i < NumOfElem; ++i) {
1905     MaskVal[0] = N->getMaskElt(i * Width);
1906     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1907       return false;
1908     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1909       return false;
1910     }
1911 
1912     for (unsigned int j = 1; j < Width; ++j) {
1913       MaskVal[j] = N->getMaskElt(i * Width + j);
1914       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1915         return false;
1916       }
1917     }
1918   }
1919 
1920   return true;
1921 }
1922 
1923 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1924                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1925   if (!isNByteElemShuffleMask(N, 4, 1))
1926     return false;
1927 
1928   // Now we look at mask elements 0,4,8,12
1929   unsigned M0 = N->getMaskElt(0) / 4;
1930   unsigned M1 = N->getMaskElt(4) / 4;
1931   unsigned M2 = N->getMaskElt(8) / 4;
1932   unsigned M3 = N->getMaskElt(12) / 4;
1933   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1934   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1935 
1936   // Below, let H and L be arbitrary elements of the shuffle mask
1937   // where H is in the range [4,7] and L is in the range [0,3].
1938   // H, 1, 2, 3 or L, 5, 6, 7
1939   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1940       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1941     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1942     InsertAtByte = IsLE ? 12 : 0;
1943     Swap = M0 < 4;
1944     return true;
1945   }
1946   // 0, H, 2, 3 or 4, L, 6, 7
1947   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1948       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1949     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1950     InsertAtByte = IsLE ? 8 : 4;
1951     Swap = M1 < 4;
1952     return true;
1953   }
1954   // 0, 1, H, 3 or 4, 5, L, 7
1955   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1956       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1957     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1958     InsertAtByte = IsLE ? 4 : 8;
1959     Swap = M2 < 4;
1960     return true;
1961   }
1962   // 0, 1, 2, H or 4, 5, 6, L
1963   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1964       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1965     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1966     InsertAtByte = IsLE ? 0 : 12;
1967     Swap = M3 < 4;
1968     return true;
1969   }
1970 
1971   // If both vector operands for the shuffle are the same vector, the mask will
1972   // contain only elements from the first one and the second one will be undef.
1973   if (N->getOperand(1).isUndef()) {
1974     ShiftElts = 0;
1975     Swap = true;
1976     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1977     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1978       InsertAtByte = IsLE ? 12 : 0;
1979       return true;
1980     }
1981     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1982       InsertAtByte = IsLE ? 8 : 4;
1983       return true;
1984     }
1985     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1986       InsertAtByte = IsLE ? 4 : 8;
1987       return true;
1988     }
1989     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1990       InsertAtByte = IsLE ? 0 : 12;
1991       return true;
1992     }
1993   }
1994 
1995   return false;
1996 }
1997 
1998 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1999                                bool &Swap, bool IsLE) {
2000   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2001   // Ensure each byte index of the word is consecutive.
2002   if (!isNByteElemShuffleMask(N, 4, 1))
2003     return false;
2004 
2005   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2006   unsigned M0 = N->getMaskElt(0) / 4;
2007   unsigned M1 = N->getMaskElt(4) / 4;
2008   unsigned M2 = N->getMaskElt(8) / 4;
2009   unsigned M3 = N->getMaskElt(12) / 4;
2010 
2011   // If both vector operands for the shuffle are the same vector, the mask will
2012   // contain only elements from the first one and the second one will be undef.
2013   if (N->getOperand(1).isUndef()) {
2014     assert(M0 < 4 && "Indexing into an undef vector?");
2015     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2016       return false;
2017 
2018     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2019     Swap = false;
2020     return true;
2021   }
2022 
2023   // Ensure each word index of the ShuffleVector Mask is consecutive.
2024   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2025     return false;
2026 
2027   if (IsLE) {
2028     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2029       // Input vectors don't need to be swapped if the leading element
2030       // of the result is one of the 3 left elements of the second vector
2031       // (or if there is no shift to be done at all).
2032       Swap = false;
2033       ShiftElts = (8 - M0) % 8;
2034     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2035       // Input vectors need to be swapped if the leading element
2036       // of the result is one of the 3 left elements of the first vector
2037       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2038       Swap = true;
2039       ShiftElts = (4 - M0) % 4;
2040     }
2041 
2042     return true;
2043   } else {                                          // BE
2044     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2045       // Input vectors don't need to be swapped if the leading element
2046       // of the result is one of the 4 elements of the first vector.
2047       Swap = false;
2048       ShiftElts = M0;
2049     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2050       // Input vectors need to be swapped if the leading element
2051       // of the result is one of the 4 elements of the right vector.
2052       Swap = true;
2053       ShiftElts = M0 - 4;
2054     }
2055 
2056     return true;
2057   }
2058 }
2059 
2060 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2061   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2062 
2063   if (!isNByteElemShuffleMask(N, Width, -1))
2064     return false;
2065 
2066   for (int i = 0; i < 16; i += Width)
2067     if (N->getMaskElt(i) != i + Width - 1)
2068       return false;
2069 
2070   return true;
2071 }
2072 
2073 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2074   return isXXBRShuffleMaskHelper(N, 2);
2075 }
2076 
2077 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2078   return isXXBRShuffleMaskHelper(N, 4);
2079 }
2080 
2081 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2082   return isXXBRShuffleMaskHelper(N, 8);
2083 }
2084 
2085 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2086   return isXXBRShuffleMaskHelper(N, 16);
2087 }
2088 
2089 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2090 /// if the inputs to the instruction should be swapped and set \p DM to the
2091 /// value for the immediate.
2092 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2093 /// AND element 0 of the result comes from the first input (LE) or second input
2094 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2095 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2096 /// mask.
2097 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2098                                bool &Swap, bool IsLE) {
2099   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2100 
2101   // Ensure each byte index of the double word is consecutive.
2102   if (!isNByteElemShuffleMask(N, 8, 1))
2103     return false;
2104 
2105   unsigned M0 = N->getMaskElt(0) / 8;
2106   unsigned M1 = N->getMaskElt(8) / 8;
2107   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2108 
2109   // If both vector operands for the shuffle are the same vector, the mask will
2110   // contain only elements from the first one and the second one will be undef.
2111   if (N->getOperand(1).isUndef()) {
2112     if ((M0 | M1) < 2) {
2113       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2114       Swap = false;
2115       return true;
2116     } else
2117       return false;
2118   }
2119 
2120   if (IsLE) {
2121     if (M0 > 1 && M1 < 2) {
2122       Swap = false;
2123     } else if (M0 < 2 && M1 > 1) {
2124       M0 = (M0 + 2) % 4;
2125       M1 = (M1 + 2) % 4;
2126       Swap = true;
2127     } else
2128       return false;
2129 
2130     // Note: if control flow comes here that means Swap is already set above
2131     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2132     return true;
2133   } else { // BE
2134     if (M0 < 2 && M1 > 1) {
2135       Swap = false;
2136     } else if (M0 > 1 && M1 < 2) {
2137       M0 = (M0 + 2) % 4;
2138       M1 = (M1 + 2) % 4;
2139       Swap = true;
2140     } else
2141       return false;
2142 
2143     // Note: if control flow comes here that means Swap is already set above
2144     DM = (M0 << 1) + (M1 & 1);
2145     return true;
2146   }
2147 }
2148 
2149 
2150 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2151 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2152 /// elements are counted from the left of the vector register).
2153 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2154                                          SelectionDAG &DAG) {
2155   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2156   assert(isSplatShuffleMask(SVOp, EltSize));
2157   if (DAG.getDataLayout().isLittleEndian())
2158     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2159   else
2160     return SVOp->getMaskElt(0) / EltSize;
2161 }
2162 
2163 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2164 /// by using a vspltis[bhw] instruction of the specified element size, return
2165 /// the constant being splatted.  The ByteSize field indicates the number of
2166 /// bytes of each element [124] -> [bhw].
2167 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2168   SDValue OpVal(nullptr, 0);
2169 
2170   // If ByteSize of the splat is bigger than the element size of the
2171   // build_vector, then we have a case where we are checking for a splat where
2172   // multiple elements of the buildvector are folded together into a single
2173   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2174   unsigned EltSize = 16/N->getNumOperands();
2175   if (EltSize < ByteSize) {
2176     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2177     SDValue UniquedVals[4];
2178     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2179 
2180     // See if all of the elements in the buildvector agree across.
2181     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2182       if (N->getOperand(i).isUndef()) continue;
2183       // If the element isn't a constant, bail fully out.
2184       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2185 
2186       if (!UniquedVals[i&(Multiple-1)].getNode())
2187         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2188       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2189         return SDValue();  // no match.
2190     }
2191 
2192     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2193     // either constant or undef values that are identical for each chunk.  See
2194     // if these chunks can form into a larger vspltis*.
2195 
2196     // Check to see if all of the leading entries are either 0 or -1.  If
2197     // neither, then this won't fit into the immediate field.
2198     bool LeadingZero = true;
2199     bool LeadingOnes = true;
2200     for (unsigned i = 0; i != Multiple-1; ++i) {
2201       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2202 
2203       LeadingZero &= isNullConstant(UniquedVals[i]);
2204       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2205     }
2206     // Finally, check the least significant entry.
2207     if (LeadingZero) {
2208       if (!UniquedVals[Multiple-1].getNode())
2209         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2210       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2211       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2212         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2213     }
2214     if (LeadingOnes) {
2215       if (!UniquedVals[Multiple-1].getNode())
2216         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2217       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2218       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2219         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2220     }
2221 
2222     return SDValue();
2223   }
2224 
2225   // Check to see if this buildvec has a single non-undef value in its elements.
2226   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2227     if (N->getOperand(i).isUndef()) continue;
2228     if (!OpVal.getNode())
2229       OpVal = N->getOperand(i);
2230     else if (OpVal != N->getOperand(i))
2231       return SDValue();
2232   }
2233 
2234   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2235 
2236   unsigned ValSizeInBytes = EltSize;
2237   uint64_t Value = 0;
2238   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2239     Value = CN->getZExtValue();
2240   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2241     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2242     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2243   }
2244 
2245   // If the splat value is larger than the element value, then we can never do
2246   // this splat.  The only case that we could fit the replicated bits into our
2247   // immediate field for would be zero, and we prefer to use vxor for it.
2248   if (ValSizeInBytes < ByteSize) return SDValue();
2249 
2250   // If the element value is larger than the splat value, check if it consists
2251   // of a repeated bit pattern of size ByteSize.
2252   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2253     return SDValue();
2254 
2255   // Properly sign extend the value.
2256   int MaskVal = SignExtend32(Value, ByteSize * 8);
2257 
2258   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2259   if (MaskVal == 0) return SDValue();
2260 
2261   // Finally, if this value fits in a 5 bit sext field, return it
2262   if (SignExtend32<5>(MaskVal) == MaskVal)
2263     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2264   return SDValue();
2265 }
2266 
2267 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2268 /// amount, otherwise return -1.
2269 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2270   EVT VT = N->getValueType(0);
2271   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2272     return -1;
2273 
2274   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2275 
2276   // Find the first non-undef value in the shuffle mask.
2277   unsigned i;
2278   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2279     /*search*/;
2280 
2281   if (i == 4) return -1;  // all undef.
2282 
2283   // Otherwise, check to see if the rest of the elements are consecutively
2284   // numbered from this value.
2285   unsigned ShiftAmt = SVOp->getMaskElt(i);
2286   if (ShiftAmt < i) return -1;
2287   ShiftAmt -= i;
2288 
2289   // Check the rest of the elements to see if they are consecutive.
2290   for (++i; i != 4; ++i)
2291     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2292       return -1;
2293 
2294   return ShiftAmt;
2295 }
2296 
2297 //===----------------------------------------------------------------------===//
2298 //  Addressing Mode Selection
2299 //===----------------------------------------------------------------------===//
2300 
2301 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2302 /// or 64-bit immediate, and if the value can be accurately represented as a
2303 /// sign extension from a 16-bit value.  If so, this returns true and the
2304 /// immediate.
2305 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2306   if (!isa<ConstantSDNode>(N))
2307     return false;
2308 
2309   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2310   if (N->getValueType(0) == MVT::i32)
2311     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2312   else
2313     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2314 }
2315 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2316   return isIntS16Immediate(Op.getNode(), Imm);
2317 }
2318 
2319 
2320 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2321 /// be represented as an indexed [r+r] operation.
2322 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2323                                                SDValue &Index,
2324                                                SelectionDAG &DAG) const {
2325   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2326       UI != E; ++UI) {
2327     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2328       if (Memop->getMemoryVT() == MVT::f64) {
2329           Base = N.getOperand(0);
2330           Index = N.getOperand(1);
2331           return true;
2332       }
2333     }
2334   }
2335   return false;
2336 }
2337 
2338 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2339 /// can be represented as an indexed [r+r] operation.  Returns false if it
2340 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2341 /// non-zero and N can be represented by a base register plus a signed 16-bit
2342 /// displacement, make a more precise judgement by checking (displacement % \p
2343 /// EncodingAlignment).
2344 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2345                                             SDValue &Index, SelectionDAG &DAG,
2346                                             unsigned EncodingAlignment) const {
2347   int16_t imm = 0;
2348   if (N.getOpcode() == ISD::ADD) {
2349     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2350     // SPE load/store can only handle 8-bit offsets.
2351     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2352         return true;
2353     if (isIntS16Immediate(N.getOperand(1), imm) &&
2354         (!EncodingAlignment || !(imm % EncodingAlignment)))
2355       return false; // r+i
2356     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2357       return false;    // r+i
2358 
2359     Base = N.getOperand(0);
2360     Index = N.getOperand(1);
2361     return true;
2362   } else if (N.getOpcode() == ISD::OR) {
2363     if (isIntS16Immediate(N.getOperand(1), imm) &&
2364         (!EncodingAlignment || !(imm % EncodingAlignment)))
2365       return false; // r+i can fold it if we can.
2366 
2367     // If this is an or of disjoint bitfields, we can codegen this as an add
2368     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2369     // disjoint.
2370     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2371 
2372     if (LHSKnown.Zero.getBoolValue()) {
2373       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2374       // If all of the bits are known zero on the LHS or RHS, the add won't
2375       // carry.
2376       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2377         Base = N.getOperand(0);
2378         Index = N.getOperand(1);
2379         return true;
2380       }
2381     }
2382   }
2383 
2384   return false;
2385 }
2386 
2387 // If we happen to be doing an i64 load or store into a stack slot that has
2388 // less than a 4-byte alignment, then the frame-index elimination may need to
2389 // use an indexed load or store instruction (because the offset may not be a
2390 // multiple of 4). The extra register needed to hold the offset comes from the
2391 // register scavenger, and it is possible that the scavenger will need to use
2392 // an emergency spill slot. As a result, we need to make sure that a spill slot
2393 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2394 // stack slot.
2395 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2396   // FIXME: This does not handle the LWA case.
2397   if (VT != MVT::i64)
2398     return;
2399 
2400   // NOTE: We'll exclude negative FIs here, which come from argument
2401   // lowering, because there are no known test cases triggering this problem
2402   // using packed structures (or similar). We can remove this exclusion if
2403   // we find such a test case. The reason why this is so test-case driven is
2404   // because this entire 'fixup' is only to prevent crashes (from the
2405   // register scavenger) on not-really-valid inputs. For example, if we have:
2406   //   %a = alloca i1
2407   //   %b = bitcast i1* %a to i64*
2408   //   store i64* a, i64 b
2409   // then the store should really be marked as 'align 1', but is not. If it
2410   // were marked as 'align 1' then the indexed form would have been
2411   // instruction-selected initially, and the problem this 'fixup' is preventing
2412   // won't happen regardless.
2413   if (FrameIdx < 0)
2414     return;
2415 
2416   MachineFunction &MF = DAG.getMachineFunction();
2417   MachineFrameInfo &MFI = MF.getFrameInfo();
2418 
2419   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2420   if (Align >= 4)
2421     return;
2422 
2423   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2424   FuncInfo->setHasNonRISpills();
2425 }
2426 
2427 /// Returns true if the address N can be represented by a base register plus
2428 /// a signed 16-bit displacement [r+imm], and if it is not better
2429 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2430 /// displacements that are multiples of that value.
2431 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2432                                             SDValue &Base,
2433                                             SelectionDAG &DAG,
2434                                             unsigned EncodingAlignment) const {
2435   // FIXME dl should come from parent load or store, not from address
2436   SDLoc dl(N);
2437   // If this can be more profitably realized as r+r, fail.
2438   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2439     return false;
2440 
2441   if (N.getOpcode() == ISD::ADD) {
2442     int16_t imm = 0;
2443     if (isIntS16Immediate(N.getOperand(1), imm) &&
2444         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2445       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2446       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2447         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2448         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2449       } else {
2450         Base = N.getOperand(0);
2451       }
2452       return true; // [r+i]
2453     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2454       // Match LOAD (ADD (X, Lo(G))).
2455       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2456              && "Cannot handle constant offsets yet!");
2457       Disp = N.getOperand(1).getOperand(0);  // The global address.
2458       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2459              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2460              Disp.getOpcode() == ISD::TargetConstantPool ||
2461              Disp.getOpcode() == ISD::TargetJumpTable);
2462       Base = N.getOperand(0);
2463       return true;  // [&g+r]
2464     }
2465   } else if (N.getOpcode() == ISD::OR) {
2466     int16_t imm = 0;
2467     if (isIntS16Immediate(N.getOperand(1), imm) &&
2468         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2469       // If this is an or of disjoint bitfields, we can codegen this as an add
2470       // (for better address arithmetic) if the LHS and RHS of the OR are
2471       // provably disjoint.
2472       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2473 
2474       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2475         // If all of the bits are known zero on the LHS or RHS, the add won't
2476         // carry.
2477         if (FrameIndexSDNode *FI =
2478               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2479           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2480           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2481         } else {
2482           Base = N.getOperand(0);
2483         }
2484         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2485         return true;
2486       }
2487     }
2488   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2489     // Loading from a constant address.
2490 
2491     // If this address fits entirely in a 16-bit sext immediate field, codegen
2492     // this as "d, 0"
2493     int16_t Imm;
2494     if (isIntS16Immediate(CN, Imm) &&
2495         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2496       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2497       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2498                              CN->getValueType(0));
2499       return true;
2500     }
2501 
2502     // Handle 32-bit sext immediates with LIS + addr mode.
2503     if ((CN->getValueType(0) == MVT::i32 ||
2504          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2505         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2506       int Addr = (int)CN->getZExtValue();
2507 
2508       // Otherwise, break this down into an LIS + disp.
2509       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2510 
2511       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2512                                    MVT::i32);
2513       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2514       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2515       return true;
2516     }
2517   }
2518 
2519   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2520   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2521     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2522     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2523   } else
2524     Base = N;
2525   return true;      // [r+0]
2526 }
2527 
2528 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2529 /// represented as an indexed [r+r] operation.
2530 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2531                                                 SDValue &Index,
2532                                                 SelectionDAG &DAG) const {
2533   // Check to see if we can easily represent this as an [r+r] address.  This
2534   // will fail if it thinks that the address is more profitably represented as
2535   // reg+imm, e.g. where imm = 0.
2536   if (SelectAddressRegReg(N, Base, Index, DAG))
2537     return true;
2538 
2539   // If the address is the result of an add, we will utilize the fact that the
2540   // address calculation includes an implicit add.  However, we can reduce
2541   // register pressure if we do not materialize a constant just for use as the
2542   // index register.  We only get rid of the add if it is not an add of a
2543   // value and a 16-bit signed constant and both have a single use.
2544   int16_t imm = 0;
2545   if (N.getOpcode() == ISD::ADD &&
2546       (!isIntS16Immediate(N.getOperand(1), imm) ||
2547        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2548     Base = N.getOperand(0);
2549     Index = N.getOperand(1);
2550     return true;
2551   }
2552 
2553   // Otherwise, do it the hard way, using R0 as the base register.
2554   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2555                          N.getValueType());
2556   Index = N;
2557   return true;
2558 }
2559 
2560 /// Returns true if we should use a direct load into vector instruction
2561 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2562 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2563 
2564   // If there are any other uses other than scalar to vector, then we should
2565   // keep it as a scalar load -> direct move pattern to prevent multiple
2566   // loads.
2567   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2568   if (!LD)
2569     return false;
2570 
2571   EVT MemVT = LD->getMemoryVT();
2572   if (!MemVT.isSimple())
2573     return false;
2574   switch(MemVT.getSimpleVT().SimpleTy) {
2575   case MVT::i64:
2576     break;
2577   case MVT::i32:
2578     if (!ST.hasP8Vector())
2579       return false;
2580     break;
2581   case MVT::i16:
2582   case MVT::i8:
2583     if (!ST.hasP9Vector())
2584       return false;
2585     break;
2586   default:
2587     return false;
2588   }
2589 
2590   SDValue LoadedVal(N, 0);
2591   if (!LoadedVal.hasOneUse())
2592     return false;
2593 
2594   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2595        UI != UE; ++UI)
2596     if (UI.getUse().get().getResNo() == 0 &&
2597         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2598       return false;
2599 
2600   return true;
2601 }
2602 
2603 /// getPreIndexedAddressParts - returns true by value, base pointer and
2604 /// offset pointer and addressing mode by reference if the node's address
2605 /// can be legally represented as pre-indexed load / store address.
2606 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2607                                                   SDValue &Offset,
2608                                                   ISD::MemIndexedMode &AM,
2609                                                   SelectionDAG &DAG) const {
2610   if (DisablePPCPreinc) return false;
2611 
2612   bool isLoad = true;
2613   SDValue Ptr;
2614   EVT VT;
2615   unsigned Alignment;
2616   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2617     Ptr = LD->getBasePtr();
2618     VT = LD->getMemoryVT();
2619     Alignment = LD->getAlignment();
2620   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2621     Ptr = ST->getBasePtr();
2622     VT  = ST->getMemoryVT();
2623     Alignment = ST->getAlignment();
2624     isLoad = false;
2625   } else
2626     return false;
2627 
2628   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2629   // instructions because we can fold these into a more efficient instruction
2630   // instead, (such as LXSD).
2631   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2632     return false;
2633   }
2634 
2635   // PowerPC doesn't have preinc load/store instructions for vectors (except
2636   // for QPX, which does have preinc r+r forms).
2637   if (VT.isVector()) {
2638     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2639       return false;
2640     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2641       AM = ISD::PRE_INC;
2642       return true;
2643     }
2644   }
2645 
2646   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2647     // Common code will reject creating a pre-inc form if the base pointer
2648     // is a frame index, or if N is a store and the base pointer is either
2649     // the same as or a predecessor of the value being stored.  Check for
2650     // those situations here, and try with swapped Base/Offset instead.
2651     bool Swap = false;
2652 
2653     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2654       Swap = true;
2655     else if (!isLoad) {
2656       SDValue Val = cast<StoreSDNode>(N)->getValue();
2657       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2658         Swap = true;
2659     }
2660 
2661     if (Swap)
2662       std::swap(Base, Offset);
2663 
2664     AM = ISD::PRE_INC;
2665     return true;
2666   }
2667 
2668   // LDU/STU can only handle immediates that are a multiple of 4.
2669   if (VT != MVT::i64) {
2670     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2671       return false;
2672   } else {
2673     // LDU/STU need an address with at least 4-byte alignment.
2674     if (Alignment < 4)
2675       return false;
2676 
2677     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2678       return false;
2679   }
2680 
2681   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2682     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2683     // sext i32 to i64 when addr mode is r+i.
2684     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2685         LD->getExtensionType() == ISD::SEXTLOAD &&
2686         isa<ConstantSDNode>(Offset))
2687       return false;
2688   }
2689 
2690   AM = ISD::PRE_INC;
2691   return true;
2692 }
2693 
2694 //===----------------------------------------------------------------------===//
2695 //  LowerOperation implementation
2696 //===----------------------------------------------------------------------===//
2697 
2698 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2699 /// and LoOpFlags to the target MO flags.
2700 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2701                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2702                                const GlobalValue *GV = nullptr) {
2703   HiOpFlags = PPCII::MO_HA;
2704   LoOpFlags = PPCII::MO_LO;
2705 
2706   // Don't use the pic base if not in PIC relocation model.
2707   if (IsPIC) {
2708     HiOpFlags |= PPCII::MO_PIC_FLAG;
2709     LoOpFlags |= PPCII::MO_PIC_FLAG;
2710   }
2711 
2712   // If this is a reference to a global value that requires a non-lazy-ptr, make
2713   // sure that instruction lowering adds it.
2714   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2715     HiOpFlags |= PPCII::MO_NLP_FLAG;
2716     LoOpFlags |= PPCII::MO_NLP_FLAG;
2717 
2718     if (GV->hasHiddenVisibility()) {
2719       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2720       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2721     }
2722   }
2723 }
2724 
2725 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2726                              SelectionDAG &DAG) {
2727   SDLoc DL(HiPart);
2728   EVT PtrVT = HiPart.getValueType();
2729   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2730 
2731   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2732   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2733 
2734   // With PIC, the first instruction is actually "GR+hi(&G)".
2735   if (isPIC)
2736     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2737                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2738 
2739   // Generate non-pic code that has direct accesses to the constant pool.
2740   // The address of the global is just (hi(&g)+lo(&g)).
2741   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2742 }
2743 
2744 static void setUsesTOCBasePtr(MachineFunction &MF) {
2745   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2746   FuncInfo->setUsesTOCBasePtr();
2747 }
2748 
2749 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2750   setUsesTOCBasePtr(DAG.getMachineFunction());
2751 }
2752 
2753 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2754                                        SDValue GA) const {
2755   const bool Is64Bit = Subtarget.isPPC64();
2756   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2757   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2758                         : Subtarget.isAIXABI()
2759                               ? DAG.getRegister(PPC::R2, VT)
2760                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2761   SDValue Ops[] = { GA, Reg };
2762   return DAG.getMemIntrinsicNode(
2763       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2764       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2765       MachineMemOperand::MOLoad);
2766 }
2767 
2768 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2769                                              SelectionDAG &DAG) const {
2770   EVT PtrVT = Op.getValueType();
2771   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2772   const Constant *C = CP->getConstVal();
2773 
2774   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2775   // The actual address of the GlobalValue is stored in the TOC.
2776   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2777     setUsesTOCBasePtr(DAG);
2778     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2779     return getTOCEntry(DAG, SDLoc(CP), GA);
2780   }
2781 
2782   unsigned MOHiFlag, MOLoFlag;
2783   bool IsPIC = isPositionIndependent();
2784   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2785 
2786   if (IsPIC && Subtarget.isSVR4ABI()) {
2787     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2788                                            PPCII::MO_PIC_FLAG);
2789     return getTOCEntry(DAG, SDLoc(CP), GA);
2790   }
2791 
2792   SDValue CPIHi =
2793     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2794   SDValue CPILo =
2795     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2796   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2797 }
2798 
2799 // For 64-bit PowerPC, prefer the more compact relative encodings.
2800 // This trades 32 bits per jump table entry for one or two instructions
2801 // on the jump site.
2802 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2803   if (isJumpTableRelative())
2804     return MachineJumpTableInfo::EK_LabelDifference32;
2805 
2806   return TargetLowering::getJumpTableEncoding();
2807 }
2808 
2809 bool PPCTargetLowering::isJumpTableRelative() const {
2810   if (UseAbsoluteJumpTables)
2811     return false;
2812   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2813     return true;
2814   return TargetLowering::isJumpTableRelative();
2815 }
2816 
2817 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2818                                                     SelectionDAG &DAG) const {
2819   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2820     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2821 
2822   switch (getTargetMachine().getCodeModel()) {
2823   case CodeModel::Small:
2824   case CodeModel::Medium:
2825     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2826   default:
2827     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2828                        getPointerTy(DAG.getDataLayout()));
2829   }
2830 }
2831 
2832 const MCExpr *
2833 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2834                                                 unsigned JTI,
2835                                                 MCContext &Ctx) const {
2836   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2837     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2838 
2839   switch (getTargetMachine().getCodeModel()) {
2840   case CodeModel::Small:
2841   case CodeModel::Medium:
2842     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2843   default:
2844     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2845   }
2846 }
2847 
2848 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2849   EVT PtrVT = Op.getValueType();
2850   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2851 
2852   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2853   // The actual address of the GlobalValue is stored in the TOC.
2854   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2855     setUsesTOCBasePtr(DAG);
2856     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2857     return getTOCEntry(DAG, SDLoc(JT), GA);
2858   }
2859 
2860   unsigned MOHiFlag, MOLoFlag;
2861   bool IsPIC = isPositionIndependent();
2862   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2863 
2864   if (IsPIC && Subtarget.isSVR4ABI()) {
2865     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2866                                         PPCII::MO_PIC_FLAG);
2867     return getTOCEntry(DAG, SDLoc(GA), GA);
2868   }
2869 
2870   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2871   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2872   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2873 }
2874 
2875 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2876                                              SelectionDAG &DAG) const {
2877   EVT PtrVT = Op.getValueType();
2878   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2879   const BlockAddress *BA = BASDN->getBlockAddress();
2880 
2881   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2882   // The actual BlockAddress is stored in the TOC.
2883   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2884     setUsesTOCBasePtr(DAG);
2885     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2886     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2887   }
2888 
2889   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2890   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2891     return getTOCEntry(
2892         DAG, SDLoc(BASDN),
2893         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2894 
2895   unsigned MOHiFlag, MOLoFlag;
2896   bool IsPIC = isPositionIndependent();
2897   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2898   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2899   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2900   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2901 }
2902 
2903 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2904                                               SelectionDAG &DAG) const {
2905   // FIXME: TLS addresses currently use medium model code sequences,
2906   // which is the most useful form.  Eventually support for small and
2907   // large models could be added if users need it, at the cost of
2908   // additional complexity.
2909   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2910   if (DAG.getTarget().useEmulatedTLS())
2911     return LowerToTLSEmulatedModel(GA, DAG);
2912 
2913   SDLoc dl(GA);
2914   const GlobalValue *GV = GA->getGlobal();
2915   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2916   bool is64bit = Subtarget.isPPC64();
2917   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2918   PICLevel::Level picLevel = M->getPICLevel();
2919 
2920   const TargetMachine &TM = getTargetMachine();
2921   TLSModel::Model Model = TM.getTLSModel(GV);
2922 
2923   if (Model == TLSModel::LocalExec) {
2924     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2925                                                PPCII::MO_TPREL_HA);
2926     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2927                                                PPCII::MO_TPREL_LO);
2928     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2929                              : DAG.getRegister(PPC::R2, MVT::i32);
2930 
2931     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2932     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2933   }
2934 
2935   if (Model == TLSModel::InitialExec) {
2936     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2937     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2938                                                 PPCII::MO_TLS);
2939     SDValue GOTPtr;
2940     if (is64bit) {
2941       setUsesTOCBasePtr(DAG);
2942       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2943       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2944                            PtrVT, GOTReg, TGA);
2945     } else {
2946       if (!TM.isPositionIndependent())
2947         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2948       else if (picLevel == PICLevel::SmallPIC)
2949         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2950       else
2951         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2952     }
2953     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2954                                    PtrVT, TGA, GOTPtr);
2955     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2956   }
2957 
2958   if (Model == TLSModel::GeneralDynamic) {
2959     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2960     SDValue GOTPtr;
2961     if (is64bit) {
2962       setUsesTOCBasePtr(DAG);
2963       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2964       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2965                                    GOTReg, TGA);
2966     } else {
2967       if (picLevel == PICLevel::SmallPIC)
2968         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2969       else
2970         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2971     }
2972     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2973                        GOTPtr, TGA, TGA);
2974   }
2975 
2976   if (Model == TLSModel::LocalDynamic) {
2977     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2978     SDValue GOTPtr;
2979     if (is64bit) {
2980       setUsesTOCBasePtr(DAG);
2981       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2982       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2983                            GOTReg, TGA);
2984     } else {
2985       if (picLevel == PICLevel::SmallPIC)
2986         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2987       else
2988         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2989     }
2990     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2991                                   PtrVT, GOTPtr, TGA, TGA);
2992     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2993                                       PtrVT, TLSAddr, TGA);
2994     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2995   }
2996 
2997   llvm_unreachable("Unknown TLS model!");
2998 }
2999 
3000 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3001                                               SelectionDAG &DAG) const {
3002   EVT PtrVT = Op.getValueType();
3003   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3004   SDLoc DL(GSDN);
3005   const GlobalValue *GV = GSDN->getGlobal();
3006 
3007   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3008   // The actual address of the GlobalValue is stored in the TOC.
3009   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3010     setUsesTOCBasePtr(DAG);
3011     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3012     return getTOCEntry(DAG, DL, GA);
3013   }
3014 
3015   unsigned MOHiFlag, MOLoFlag;
3016   bool IsPIC = isPositionIndependent();
3017   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3018 
3019   if (IsPIC && Subtarget.isSVR4ABI()) {
3020     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3021                                             GSDN->getOffset(),
3022                                             PPCII::MO_PIC_FLAG);
3023     return getTOCEntry(DAG, DL, GA);
3024   }
3025 
3026   SDValue GAHi =
3027     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3028   SDValue GALo =
3029     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3030 
3031   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3032 
3033   // If the global reference is actually to a non-lazy-pointer, we have to do an
3034   // extra load to get the address of the global.
3035   if (MOHiFlag & PPCII::MO_NLP_FLAG)
3036     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3037   return Ptr;
3038 }
3039 
3040 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3041   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3042   SDLoc dl(Op);
3043 
3044   if (Op.getValueType() == MVT::v2i64) {
3045     // When the operands themselves are v2i64 values, we need to do something
3046     // special because VSX has no underlying comparison operations for these.
3047     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3048       // Equality can be handled by casting to the legal type for Altivec
3049       // comparisons, everything else needs to be expanded.
3050       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3051         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3052                  DAG.getSetCC(dl, MVT::v4i32,
3053                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3054                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3055                    CC));
3056       }
3057 
3058       return SDValue();
3059     }
3060 
3061     // We handle most of these in the usual way.
3062     return Op;
3063   }
3064 
3065   // If we're comparing for equality to zero, expose the fact that this is
3066   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3067   // fold the new nodes.
3068   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3069     return V;
3070 
3071   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3072     // Leave comparisons against 0 and -1 alone for now, since they're usually
3073     // optimized.  FIXME: revisit this when we can custom lower all setcc
3074     // optimizations.
3075     if (C->isAllOnesValue() || C->isNullValue())
3076       return SDValue();
3077   }
3078 
3079   // If we have an integer seteq/setne, turn it into a compare against zero
3080   // by xor'ing the rhs with the lhs, which is faster than setting a
3081   // condition register, reading it back out, and masking the correct bit.  The
3082   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3083   // the result to other bit-twiddling opportunities.
3084   EVT LHSVT = Op.getOperand(0).getValueType();
3085   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3086     EVT VT = Op.getValueType();
3087     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3088                                 Op.getOperand(1));
3089     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3090   }
3091   return SDValue();
3092 }
3093 
3094 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3095   SDNode *Node = Op.getNode();
3096   EVT VT = Node->getValueType(0);
3097   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3098   SDValue InChain = Node->getOperand(0);
3099   SDValue VAListPtr = Node->getOperand(1);
3100   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3101   SDLoc dl(Node);
3102 
3103   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3104 
3105   // gpr_index
3106   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3107                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3108   InChain = GprIndex.getValue(1);
3109 
3110   if (VT == MVT::i64) {
3111     // Check if GprIndex is even
3112     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3113                                  DAG.getConstant(1, dl, MVT::i32));
3114     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3115                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3116     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3117                                           DAG.getConstant(1, dl, MVT::i32));
3118     // Align GprIndex to be even if it isn't
3119     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3120                            GprIndex);
3121   }
3122 
3123   // fpr index is 1 byte after gpr
3124   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3125                                DAG.getConstant(1, dl, MVT::i32));
3126 
3127   // fpr
3128   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3129                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3130   InChain = FprIndex.getValue(1);
3131 
3132   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3133                                        DAG.getConstant(8, dl, MVT::i32));
3134 
3135   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3136                                         DAG.getConstant(4, dl, MVT::i32));
3137 
3138   // areas
3139   SDValue OverflowArea =
3140       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3141   InChain = OverflowArea.getValue(1);
3142 
3143   SDValue RegSaveArea =
3144       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3145   InChain = RegSaveArea.getValue(1);
3146 
3147   // select overflow_area if index > 8
3148   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3149                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3150 
3151   // adjustment constant gpr_index * 4/8
3152   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3153                                     VT.isInteger() ? GprIndex : FprIndex,
3154                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3155                                                     MVT::i32));
3156 
3157   // OurReg = RegSaveArea + RegConstant
3158   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3159                                RegConstant);
3160 
3161   // Floating types are 32 bytes into RegSaveArea
3162   if (VT.isFloatingPoint())
3163     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3164                          DAG.getConstant(32, dl, MVT::i32));
3165 
3166   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3167   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3168                                    VT.isInteger() ? GprIndex : FprIndex,
3169                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3170                                                    MVT::i32));
3171 
3172   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3173                               VT.isInteger() ? VAListPtr : FprPtr,
3174                               MachinePointerInfo(SV), MVT::i8);
3175 
3176   // determine if we should load from reg_save_area or overflow_area
3177   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3178 
3179   // increase overflow_area by 4/8 if gpr/fpr > 8
3180   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3181                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3182                                           dl, MVT::i32));
3183 
3184   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3185                              OverflowAreaPlusN);
3186 
3187   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3188                               MachinePointerInfo(), MVT::i32);
3189 
3190   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3191 }
3192 
3193 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3194   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3195 
3196   // We have to copy the entire va_list struct:
3197   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3198   return DAG.getMemcpy(Op.getOperand(0), Op,
3199                        Op.getOperand(1), Op.getOperand(2),
3200                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3201                        false, MachinePointerInfo(), MachinePointerInfo());
3202 }
3203 
3204 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3205                                                   SelectionDAG &DAG) const {
3206   if (Subtarget.isAIXABI())
3207     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3208 
3209   return Op.getOperand(0);
3210 }
3211 
3212 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3213                                                 SelectionDAG &DAG) const {
3214   if (Subtarget.isAIXABI())
3215     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3216 
3217   SDValue Chain = Op.getOperand(0);
3218   SDValue Trmp = Op.getOperand(1); // trampoline
3219   SDValue FPtr = Op.getOperand(2); // nested function
3220   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3221   SDLoc dl(Op);
3222 
3223   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3224   bool isPPC64 = (PtrVT == MVT::i64);
3225   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3226 
3227   TargetLowering::ArgListTy Args;
3228   TargetLowering::ArgListEntry Entry;
3229 
3230   Entry.Ty = IntPtrTy;
3231   Entry.Node = Trmp; Args.push_back(Entry);
3232 
3233   // TrampSize == (isPPC64 ? 48 : 40);
3234   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3235                                isPPC64 ? MVT::i64 : MVT::i32);
3236   Args.push_back(Entry);
3237 
3238   Entry.Node = FPtr; Args.push_back(Entry);
3239   Entry.Node = Nest; Args.push_back(Entry);
3240 
3241   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3242   TargetLowering::CallLoweringInfo CLI(DAG);
3243   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3244       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3245       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3246 
3247   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3248   return CallResult.second;
3249 }
3250 
3251 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3252   MachineFunction &MF = DAG.getMachineFunction();
3253   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3254   EVT PtrVT = getPointerTy(MF.getDataLayout());
3255 
3256   SDLoc dl(Op);
3257 
3258   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3259     // vastart just stores the address of the VarArgsFrameIndex slot into the
3260     // memory location argument.
3261     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3262     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3263     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3264                         MachinePointerInfo(SV));
3265   }
3266 
3267   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3268   // We suppose the given va_list is already allocated.
3269   //
3270   // typedef struct {
3271   //  char gpr;     /* index into the array of 8 GPRs
3272   //                 * stored in the register save area
3273   //                 * gpr=0 corresponds to r3,
3274   //                 * gpr=1 to r4, etc.
3275   //                 */
3276   //  char fpr;     /* index into the array of 8 FPRs
3277   //                 * stored in the register save area
3278   //                 * fpr=0 corresponds to f1,
3279   //                 * fpr=1 to f2, etc.
3280   //                 */
3281   //  char *overflow_arg_area;
3282   //                /* location on stack that holds
3283   //                 * the next overflow argument
3284   //                 */
3285   //  char *reg_save_area;
3286   //               /* where r3:r10 and f1:f8 (if saved)
3287   //                * are stored
3288   //                */
3289   // } va_list[1];
3290 
3291   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3292   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3293   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3294                                             PtrVT);
3295   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3296                                  PtrVT);
3297 
3298   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3299   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3300 
3301   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3302   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3303 
3304   uint64_t FPROffset = 1;
3305   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3306 
3307   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3308 
3309   // Store first byte : number of int regs
3310   SDValue firstStore =
3311       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3312                         MachinePointerInfo(SV), MVT::i8);
3313   uint64_t nextOffset = FPROffset;
3314   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3315                                   ConstFPROffset);
3316 
3317   // Store second byte : number of float regs
3318   SDValue secondStore =
3319       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3320                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3321   nextOffset += StackOffset;
3322   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3323 
3324   // Store second word : arguments given on stack
3325   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3326                                     MachinePointerInfo(SV, nextOffset));
3327   nextOffset += FrameOffset;
3328   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3329 
3330   // Store third word : arguments given in registers
3331   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3332                       MachinePointerInfo(SV, nextOffset));
3333 }
3334 
3335 /// FPR - The set of FP registers that should be allocated for arguments
3336 /// on Darwin and AIX.
3337 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3338                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3339                                 PPC::F11, PPC::F12, PPC::F13};
3340 
3341 /// QFPR - The set of QPX registers that should be allocated for arguments.
3342 static const MCPhysReg QFPR[] = {
3343     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3344     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3345 
3346 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3347 /// the stack.
3348 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3349                                        unsigned PtrByteSize) {
3350   unsigned ArgSize = ArgVT.getStoreSize();
3351   if (Flags.isByVal())
3352     ArgSize = Flags.getByValSize();
3353 
3354   // Round up to multiples of the pointer size, except for array members,
3355   // which are always packed.
3356   if (!Flags.isInConsecutiveRegs())
3357     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3358 
3359   return ArgSize;
3360 }
3361 
3362 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3363 /// on the stack.
3364 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3365                                             ISD::ArgFlagsTy Flags,
3366                                             unsigned PtrByteSize) {
3367   unsigned Align = PtrByteSize;
3368 
3369   // Altivec parameters are padded to a 16 byte boundary.
3370   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3371       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3372       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3373       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3374     Align = 16;
3375   // QPX vector types stored in double-precision are padded to a 32 byte
3376   // boundary.
3377   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3378     Align = 32;
3379 
3380   // ByVal parameters are aligned as requested.
3381   if (Flags.isByVal()) {
3382     unsigned BVAlign = Flags.getByValAlign();
3383     if (BVAlign > PtrByteSize) {
3384       if (BVAlign % PtrByteSize != 0)
3385           llvm_unreachable(
3386             "ByVal alignment is not a multiple of the pointer size");
3387 
3388       Align = BVAlign;
3389     }
3390   }
3391 
3392   // Array members are always packed to their original alignment.
3393   if (Flags.isInConsecutiveRegs()) {
3394     // If the array member was split into multiple registers, the first
3395     // needs to be aligned to the size of the full type.  (Except for
3396     // ppcf128, which is only aligned as its f64 components.)
3397     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3398       Align = OrigVT.getStoreSize();
3399     else
3400       Align = ArgVT.getStoreSize();
3401   }
3402 
3403   return Align;
3404 }
3405 
3406 /// CalculateStackSlotUsed - Return whether this argument will use its
3407 /// stack slot (instead of being passed in registers).  ArgOffset,
3408 /// AvailableFPRs, and AvailableVRs must hold the current argument
3409 /// position, and will be updated to account for this argument.
3410 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3411                                    ISD::ArgFlagsTy Flags,
3412                                    unsigned PtrByteSize,
3413                                    unsigned LinkageSize,
3414                                    unsigned ParamAreaSize,
3415                                    unsigned &ArgOffset,
3416                                    unsigned &AvailableFPRs,
3417                                    unsigned &AvailableVRs, bool HasQPX) {
3418   bool UseMemory = false;
3419 
3420   // Respect alignment of argument on the stack.
3421   unsigned Align =
3422     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3423   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3424   // If there's no space left in the argument save area, we must
3425   // use memory (this check also catches zero-sized arguments).
3426   if (ArgOffset >= LinkageSize + ParamAreaSize)
3427     UseMemory = true;
3428 
3429   // Allocate argument on the stack.
3430   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3431   if (Flags.isInConsecutiveRegsLast())
3432     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3433   // If we overran the argument save area, we must use memory
3434   // (this check catches arguments passed partially in memory)
3435   if (ArgOffset > LinkageSize + ParamAreaSize)
3436     UseMemory = true;
3437 
3438   // However, if the argument is actually passed in an FPR or a VR,
3439   // we don't use memory after all.
3440   if (!Flags.isByVal()) {
3441     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3442         // QPX registers overlap with the scalar FP registers.
3443         (HasQPX && (ArgVT == MVT::v4f32 ||
3444                     ArgVT == MVT::v4f64 ||
3445                     ArgVT == MVT::v4i1)))
3446       if (AvailableFPRs > 0) {
3447         --AvailableFPRs;
3448         return false;
3449       }
3450     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3451         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3452         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3453         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3454       if (AvailableVRs > 0) {
3455         --AvailableVRs;
3456         return false;
3457       }
3458   }
3459 
3460   return UseMemory;
3461 }
3462 
3463 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3464 /// ensure minimum alignment required for target.
3465 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3466                                      unsigned NumBytes) {
3467   unsigned TargetAlign = Lowering->getStackAlignment();
3468   unsigned AlignMask = TargetAlign - 1;
3469   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3470   return NumBytes;
3471 }
3472 
3473 SDValue PPCTargetLowering::LowerFormalArguments(
3474     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3475     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3476     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3477   if (Subtarget.isAIXABI())
3478     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3479                                     InVals);
3480   if (Subtarget.is64BitELFABI())
3481     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3482                                        InVals);
3483   if (Subtarget.is32BitELFABI())
3484     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3485                                        InVals);
3486 
3487   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3488                                      InVals);
3489 }
3490 
3491 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3492     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3493     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3494     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3495 
3496   // 32-bit SVR4 ABI Stack Frame Layout:
3497   //              +-----------------------------------+
3498   //        +-->  |            Back chain             |
3499   //        |     +-----------------------------------+
3500   //        |     | Floating-point register save area |
3501   //        |     +-----------------------------------+
3502   //        |     |    General register save area     |
3503   //        |     +-----------------------------------+
3504   //        |     |          CR save word             |
3505   //        |     +-----------------------------------+
3506   //        |     |         VRSAVE save word          |
3507   //        |     +-----------------------------------+
3508   //        |     |         Alignment padding         |
3509   //        |     +-----------------------------------+
3510   //        |     |     Vector register save area     |
3511   //        |     +-----------------------------------+
3512   //        |     |       Local variable space        |
3513   //        |     +-----------------------------------+
3514   //        |     |        Parameter list area        |
3515   //        |     +-----------------------------------+
3516   //        |     |           LR save word            |
3517   //        |     +-----------------------------------+
3518   // SP-->  +---  |            Back chain             |
3519   //              +-----------------------------------+
3520   //
3521   // Specifications:
3522   //   System V Application Binary Interface PowerPC Processor Supplement
3523   //   AltiVec Technology Programming Interface Manual
3524 
3525   MachineFunction &MF = DAG.getMachineFunction();
3526   MachineFrameInfo &MFI = MF.getFrameInfo();
3527   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3528 
3529   EVT PtrVT = getPointerTy(MF.getDataLayout());
3530   // Potential tail calls could cause overwriting of argument stack slots.
3531   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3532                        (CallConv == CallingConv::Fast));
3533   unsigned PtrByteSize = 4;
3534 
3535   // Assign locations to all of the incoming arguments.
3536   SmallVector<CCValAssign, 16> ArgLocs;
3537   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3538                  *DAG.getContext());
3539 
3540   // Reserve space for the linkage area on the stack.
3541   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3542   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3543   if (useSoftFloat())
3544     CCInfo.PreAnalyzeFormalArguments(Ins);
3545 
3546   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3547   CCInfo.clearWasPPCF128();
3548 
3549   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3550     CCValAssign &VA = ArgLocs[i];
3551 
3552     // Arguments stored in registers.
3553     if (VA.isRegLoc()) {
3554       const TargetRegisterClass *RC;
3555       EVT ValVT = VA.getValVT();
3556 
3557       switch (ValVT.getSimpleVT().SimpleTy) {
3558         default:
3559           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3560         case MVT::i1:
3561         case MVT::i32:
3562           RC = &PPC::GPRCRegClass;
3563           break;
3564         case MVT::f32:
3565           if (Subtarget.hasP8Vector())
3566             RC = &PPC::VSSRCRegClass;
3567           else if (Subtarget.hasSPE())
3568             RC = &PPC::GPRCRegClass;
3569           else
3570             RC = &PPC::F4RCRegClass;
3571           break;
3572         case MVT::f64:
3573           if (Subtarget.hasVSX())
3574             RC = &PPC::VSFRCRegClass;
3575           else if (Subtarget.hasSPE())
3576             // SPE passes doubles in GPR pairs.
3577             RC = &PPC::GPRCRegClass;
3578           else
3579             RC = &PPC::F8RCRegClass;
3580           break;
3581         case MVT::v16i8:
3582         case MVT::v8i16:
3583         case MVT::v4i32:
3584           RC = &PPC::VRRCRegClass;
3585           break;
3586         case MVT::v4f32:
3587           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3588           break;
3589         case MVT::v2f64:
3590         case MVT::v2i64:
3591           RC = &PPC::VRRCRegClass;
3592           break;
3593         case MVT::v4f64:
3594           RC = &PPC::QFRCRegClass;
3595           break;
3596         case MVT::v4i1:
3597           RC = &PPC::QBRCRegClass;
3598           break;
3599       }
3600 
3601       SDValue ArgValue;
3602       // Transform the arguments stored in physical registers into
3603       // virtual ones.
3604       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3605         assert(i + 1 < e && "No second half of double precision argument");
3606         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3607         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3608         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3609         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3610         if (!Subtarget.isLittleEndian())
3611           std::swap (ArgValueLo, ArgValueHi);
3612         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3613                                ArgValueHi);
3614       } else {
3615         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3616         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3617                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3618         if (ValVT == MVT::i1)
3619           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3620       }
3621 
3622       InVals.push_back(ArgValue);
3623     } else {
3624       // Argument stored in memory.
3625       assert(VA.isMemLoc());
3626 
3627       // Get the extended size of the argument type in stack
3628       unsigned ArgSize = VA.getLocVT().getStoreSize();
3629       // Get the actual size of the argument type
3630       unsigned ObjSize = VA.getValVT().getStoreSize();
3631       unsigned ArgOffset = VA.getLocMemOffset();
3632       // Stack objects in PPC32 are right justified.
3633       ArgOffset += ArgSize - ObjSize;
3634       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3635 
3636       // Create load nodes to retrieve arguments from the stack.
3637       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3638       InVals.push_back(
3639           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3640     }
3641   }
3642 
3643   // Assign locations to all of the incoming aggregate by value arguments.
3644   // Aggregates passed by value are stored in the local variable space of the
3645   // caller's stack frame, right above the parameter list area.
3646   SmallVector<CCValAssign, 16> ByValArgLocs;
3647   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3648                       ByValArgLocs, *DAG.getContext());
3649 
3650   // Reserve stack space for the allocations in CCInfo.
3651   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3652 
3653   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3654 
3655   // Area that is at least reserved in the caller of this function.
3656   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3657   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3658 
3659   // Set the size that is at least reserved in caller of this function.  Tail
3660   // call optimized function's reserved stack space needs to be aligned so that
3661   // taking the difference between two stack areas will result in an aligned
3662   // stack.
3663   MinReservedArea =
3664       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3665   FuncInfo->setMinReservedArea(MinReservedArea);
3666 
3667   SmallVector<SDValue, 8> MemOps;
3668 
3669   // If the function takes variable number of arguments, make a frame index for
3670   // the start of the first vararg value... for expansion of llvm.va_start.
3671   if (isVarArg) {
3672     static const MCPhysReg GPArgRegs[] = {
3673       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3674       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3675     };
3676     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3677 
3678     static const MCPhysReg FPArgRegs[] = {
3679       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3680       PPC::F8
3681     };
3682     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3683 
3684     if (useSoftFloat() || hasSPE())
3685        NumFPArgRegs = 0;
3686 
3687     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3688     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3689 
3690     // Make room for NumGPArgRegs and NumFPArgRegs.
3691     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3692                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3693 
3694     FuncInfo->setVarArgsStackOffset(
3695       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3696                             CCInfo.getNextStackOffset(), true));
3697 
3698     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3699     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3700 
3701     // The fixed integer arguments of a variadic function are stored to the
3702     // VarArgsFrameIndex on the stack so that they may be loaded by
3703     // dereferencing the result of va_next.
3704     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3705       // Get an existing live-in vreg, or add a new one.
3706       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3707       if (!VReg)
3708         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3709 
3710       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3711       SDValue Store =
3712           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3713       MemOps.push_back(Store);
3714       // Increment the address by four for the next argument to store
3715       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3716       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3717     }
3718 
3719     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3720     // is set.
3721     // The double arguments are stored to the VarArgsFrameIndex
3722     // on the stack.
3723     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3724       // Get an existing live-in vreg, or add a new one.
3725       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3726       if (!VReg)
3727         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3728 
3729       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3730       SDValue Store =
3731           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3732       MemOps.push_back(Store);
3733       // Increment the address by eight for the next argument to store
3734       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3735                                          PtrVT);
3736       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3737     }
3738   }
3739 
3740   if (!MemOps.empty())
3741     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3742 
3743   return Chain;
3744 }
3745 
3746 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3747 // value to MVT::i64 and then truncate to the correct register size.
3748 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3749                                              EVT ObjectVT, SelectionDAG &DAG,
3750                                              SDValue ArgVal,
3751                                              const SDLoc &dl) const {
3752   if (Flags.isSExt())
3753     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3754                          DAG.getValueType(ObjectVT));
3755   else if (Flags.isZExt())
3756     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3757                          DAG.getValueType(ObjectVT));
3758 
3759   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3760 }
3761 
3762 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3763     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3764     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3765     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3766   // TODO: add description of PPC stack frame format, or at least some docs.
3767   //
3768   bool isELFv2ABI = Subtarget.isELFv2ABI();
3769   bool isLittleEndian = Subtarget.isLittleEndian();
3770   MachineFunction &MF = DAG.getMachineFunction();
3771   MachineFrameInfo &MFI = MF.getFrameInfo();
3772   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3773 
3774   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3775          "fastcc not supported on varargs functions");
3776 
3777   EVT PtrVT = getPointerTy(MF.getDataLayout());
3778   // Potential tail calls could cause overwriting of argument stack slots.
3779   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3780                        (CallConv == CallingConv::Fast));
3781   unsigned PtrByteSize = 8;
3782   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3783 
3784   static const MCPhysReg GPR[] = {
3785     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3786     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3787   };
3788   static const MCPhysReg VR[] = {
3789     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3790     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3791   };
3792 
3793   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3794   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3795   const unsigned Num_VR_Regs  = array_lengthof(VR);
3796   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3797 
3798   // Do a first pass over the arguments to determine whether the ABI
3799   // guarantees that our caller has allocated the parameter save area
3800   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3801   // in the ELFv2 ABI, it is true if this is a vararg function or if
3802   // any parameter is located in a stack slot.
3803 
3804   bool HasParameterArea = !isELFv2ABI || isVarArg;
3805   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3806   unsigned NumBytes = LinkageSize;
3807   unsigned AvailableFPRs = Num_FPR_Regs;
3808   unsigned AvailableVRs = Num_VR_Regs;
3809   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3810     if (Ins[i].Flags.isNest())
3811       continue;
3812 
3813     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3814                                PtrByteSize, LinkageSize, ParamAreaSize,
3815                                NumBytes, AvailableFPRs, AvailableVRs,
3816                                Subtarget.hasQPX()))
3817       HasParameterArea = true;
3818   }
3819 
3820   // Add DAG nodes to load the arguments or copy them out of registers.  On
3821   // entry to a function on PPC, the arguments start after the linkage area,
3822   // although the first ones are often in registers.
3823 
3824   unsigned ArgOffset = LinkageSize;
3825   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3826   unsigned &QFPR_idx = FPR_idx;
3827   SmallVector<SDValue, 8> MemOps;
3828   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3829   unsigned CurArgIdx = 0;
3830   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3831     SDValue ArgVal;
3832     bool needsLoad = false;
3833     EVT ObjectVT = Ins[ArgNo].VT;
3834     EVT OrigVT = Ins[ArgNo].ArgVT;
3835     unsigned ObjSize = ObjectVT.getStoreSize();
3836     unsigned ArgSize = ObjSize;
3837     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3838     if (Ins[ArgNo].isOrigArg()) {
3839       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3840       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3841     }
3842     // We re-align the argument offset for each argument, except when using the
3843     // fast calling convention, when we need to make sure we do that only when
3844     // we'll actually use a stack slot.
3845     unsigned CurArgOffset, Align;
3846     auto ComputeArgOffset = [&]() {
3847       /* Respect alignment of argument on the stack.  */
3848       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3849       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3850       CurArgOffset = ArgOffset;
3851     };
3852 
3853     if (CallConv != CallingConv::Fast) {
3854       ComputeArgOffset();
3855 
3856       /* Compute GPR index associated with argument offset.  */
3857       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3858       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3859     }
3860 
3861     // FIXME the codegen can be much improved in some cases.
3862     // We do not have to keep everything in memory.
3863     if (Flags.isByVal()) {
3864       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3865 
3866       if (CallConv == CallingConv::Fast)
3867         ComputeArgOffset();
3868 
3869       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3870       ObjSize = Flags.getByValSize();
3871       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3872       // Empty aggregate parameters do not take up registers.  Examples:
3873       //   struct { } a;
3874       //   union  { } b;
3875       //   int c[0];
3876       // etc.  However, we have to provide a place-holder in InVals, so
3877       // pretend we have an 8-byte item at the current address for that
3878       // purpose.
3879       if (!ObjSize) {
3880         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3881         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3882         InVals.push_back(FIN);
3883         continue;
3884       }
3885 
3886       // Create a stack object covering all stack doublewords occupied
3887       // by the argument.  If the argument is (fully or partially) on
3888       // the stack, or if the argument is fully in registers but the
3889       // caller has allocated the parameter save anyway, we can refer
3890       // directly to the caller's stack frame.  Otherwise, create a
3891       // local copy in our own frame.
3892       int FI;
3893       if (HasParameterArea ||
3894           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3895         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3896       else
3897         FI = MFI.CreateStackObject(ArgSize, Align, false);
3898       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3899 
3900       // Handle aggregates smaller than 8 bytes.
3901       if (ObjSize < PtrByteSize) {
3902         // The value of the object is its address, which differs from the
3903         // address of the enclosing doubleword on big-endian systems.
3904         SDValue Arg = FIN;
3905         if (!isLittleEndian) {
3906           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3907           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3908         }
3909         InVals.push_back(Arg);
3910 
3911         if (GPR_idx != Num_GPR_Regs) {
3912           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3913           FuncInfo->addLiveInAttr(VReg, Flags);
3914           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3915           SDValue Store;
3916 
3917           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3918             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3919                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3920             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3921                                       MachinePointerInfo(&*FuncArg), ObjType);
3922           } else {
3923             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3924             // store the whole register as-is to the parameter save area
3925             // slot.
3926             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3927                                  MachinePointerInfo(&*FuncArg));
3928           }
3929 
3930           MemOps.push_back(Store);
3931         }
3932         // Whether we copied from a register or not, advance the offset
3933         // into the parameter save area by a full doubleword.
3934         ArgOffset += PtrByteSize;
3935         continue;
3936       }
3937 
3938       // The value of the object is its address, which is the address of
3939       // its first stack doubleword.
3940       InVals.push_back(FIN);
3941 
3942       // Store whatever pieces of the object are in registers to memory.
3943       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3944         if (GPR_idx == Num_GPR_Regs)
3945           break;
3946 
3947         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3948         FuncInfo->addLiveInAttr(VReg, Flags);
3949         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3950         SDValue Addr = FIN;
3951         if (j) {
3952           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3953           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3954         }
3955         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3956                                      MachinePointerInfo(&*FuncArg, j));
3957         MemOps.push_back(Store);
3958         ++GPR_idx;
3959       }
3960       ArgOffset += ArgSize;
3961       continue;
3962     }
3963 
3964     switch (ObjectVT.getSimpleVT().SimpleTy) {
3965     default: llvm_unreachable("Unhandled argument type!");
3966     case MVT::i1:
3967     case MVT::i32:
3968     case MVT::i64:
3969       if (Flags.isNest()) {
3970         // The 'nest' parameter, if any, is passed in R11.
3971         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3972         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3973 
3974         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3975           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3976 
3977         break;
3978       }
3979 
3980       // These can be scalar arguments or elements of an integer array type
3981       // passed directly.  Clang may use those instead of "byval" aggregate
3982       // types to avoid forcing arguments to memory unnecessarily.
3983       if (GPR_idx != Num_GPR_Regs) {
3984         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3985         FuncInfo->addLiveInAttr(VReg, Flags);
3986         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3987 
3988         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3989           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3990           // value to MVT::i64 and then truncate to the correct register size.
3991           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3992       } else {
3993         if (CallConv == CallingConv::Fast)
3994           ComputeArgOffset();
3995 
3996         needsLoad = true;
3997         ArgSize = PtrByteSize;
3998       }
3999       if (CallConv != CallingConv::Fast || needsLoad)
4000         ArgOffset += 8;
4001       break;
4002 
4003     case MVT::f32:
4004     case MVT::f64:
4005       // These can be scalar arguments or elements of a float array type
4006       // passed directly.  The latter are used to implement ELFv2 homogenous
4007       // float aggregates.
4008       if (FPR_idx != Num_FPR_Regs) {
4009         unsigned VReg;
4010 
4011         if (ObjectVT == MVT::f32)
4012           VReg = MF.addLiveIn(FPR[FPR_idx],
4013                               Subtarget.hasP8Vector()
4014                                   ? &PPC::VSSRCRegClass
4015                                   : &PPC::F4RCRegClass);
4016         else
4017           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4018                                                 ? &PPC::VSFRCRegClass
4019                                                 : &PPC::F8RCRegClass);
4020 
4021         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4022         ++FPR_idx;
4023       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4024         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4025         // once we support fp <-> gpr moves.
4026 
4027         // This can only ever happen in the presence of f32 array types,
4028         // since otherwise we never run out of FPRs before running out
4029         // of GPRs.
4030         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4031         FuncInfo->addLiveInAttr(VReg, Flags);
4032         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4033 
4034         if (ObjectVT == MVT::f32) {
4035           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4036             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4037                                  DAG.getConstant(32, dl, MVT::i32));
4038           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4039         }
4040 
4041         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4042       } else {
4043         if (CallConv == CallingConv::Fast)
4044           ComputeArgOffset();
4045 
4046         needsLoad = true;
4047       }
4048 
4049       // When passing an array of floats, the array occupies consecutive
4050       // space in the argument area; only round up to the next doubleword
4051       // at the end of the array.  Otherwise, each float takes 8 bytes.
4052       if (CallConv != CallingConv::Fast || needsLoad) {
4053         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4054         ArgOffset += ArgSize;
4055         if (Flags.isInConsecutiveRegsLast())
4056           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4057       }
4058       break;
4059     case MVT::v4f32:
4060     case MVT::v4i32:
4061     case MVT::v8i16:
4062     case MVT::v16i8:
4063     case MVT::v2f64:
4064     case MVT::v2i64:
4065     case MVT::v1i128:
4066     case MVT::f128:
4067       if (!Subtarget.hasQPX()) {
4068         // These can be scalar arguments or elements of a vector array type
4069         // passed directly.  The latter are used to implement ELFv2 homogenous
4070         // vector aggregates.
4071         if (VR_idx != Num_VR_Regs) {
4072           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4073           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4074           ++VR_idx;
4075         } else {
4076           if (CallConv == CallingConv::Fast)
4077             ComputeArgOffset();
4078           needsLoad = true;
4079         }
4080         if (CallConv != CallingConv::Fast || needsLoad)
4081           ArgOffset += 16;
4082         break;
4083       } // not QPX
4084 
4085       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4086              "Invalid QPX parameter type");
4087       LLVM_FALLTHROUGH;
4088 
4089     case MVT::v4f64:
4090     case MVT::v4i1:
4091       // QPX vectors are treated like their scalar floating-point subregisters
4092       // (except that they're larger).
4093       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4094       if (QFPR_idx != Num_QFPR_Regs) {
4095         const TargetRegisterClass *RC;
4096         switch (ObjectVT.getSimpleVT().SimpleTy) {
4097         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4098         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4099         default:         RC = &PPC::QBRCRegClass; break;
4100         }
4101 
4102         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4103         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4104         ++QFPR_idx;
4105       } else {
4106         if (CallConv == CallingConv::Fast)
4107           ComputeArgOffset();
4108         needsLoad = true;
4109       }
4110       if (CallConv != CallingConv::Fast || needsLoad)
4111         ArgOffset += Sz;
4112       break;
4113     }
4114 
4115     // We need to load the argument to a virtual register if we determined
4116     // above that we ran out of physical registers of the appropriate type.
4117     if (needsLoad) {
4118       if (ObjSize < ArgSize && !isLittleEndian)
4119         CurArgOffset += ArgSize - ObjSize;
4120       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4121       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4122       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4123     }
4124 
4125     InVals.push_back(ArgVal);
4126   }
4127 
4128   // Area that is at least reserved in the caller of this function.
4129   unsigned MinReservedArea;
4130   if (HasParameterArea)
4131     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4132   else
4133     MinReservedArea = LinkageSize;
4134 
4135   // Set the size that is at least reserved in caller of this function.  Tail
4136   // call optimized functions' reserved stack space needs to be aligned so that
4137   // taking the difference between two stack areas will result in an aligned
4138   // stack.
4139   MinReservedArea =
4140       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4141   FuncInfo->setMinReservedArea(MinReservedArea);
4142 
4143   // If the function takes variable number of arguments, make a frame index for
4144   // the start of the first vararg value... for expansion of llvm.va_start.
4145   if (isVarArg) {
4146     int Depth = ArgOffset;
4147 
4148     FuncInfo->setVarArgsFrameIndex(
4149       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4150     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4151 
4152     // If this function is vararg, store any remaining integer argument regs
4153     // to their spots on the stack so that they may be loaded by dereferencing
4154     // the result of va_next.
4155     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4156          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4157       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4158       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4159       SDValue Store =
4160           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4161       MemOps.push_back(Store);
4162       // Increment the address by four for the next argument to store
4163       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4164       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4165     }
4166   }
4167 
4168   if (!MemOps.empty())
4169     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4170 
4171   return Chain;
4172 }
4173 
4174 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4175     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4176     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4177     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4178   // TODO: add description of PPC stack frame format, or at least some docs.
4179   //
4180   MachineFunction &MF = DAG.getMachineFunction();
4181   MachineFrameInfo &MFI = MF.getFrameInfo();
4182   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4183 
4184   EVT PtrVT = getPointerTy(MF.getDataLayout());
4185   bool isPPC64 = PtrVT == MVT::i64;
4186   // Potential tail calls could cause overwriting of argument stack slots.
4187   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4188                        (CallConv == CallingConv::Fast));
4189   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4190   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4191   unsigned ArgOffset = LinkageSize;
4192   // Area that is at least reserved in caller of this function.
4193   unsigned MinReservedArea = ArgOffset;
4194 
4195   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4196     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4197     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4198   };
4199   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4200     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4201     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4202   };
4203   static const MCPhysReg VR[] = {
4204     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4205     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4206   };
4207 
4208   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4209   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4210   const unsigned Num_VR_Regs  = array_lengthof( VR);
4211 
4212   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4213 
4214   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4215 
4216   // In 32-bit non-varargs functions, the stack space for vectors is after the
4217   // stack space for non-vectors.  We do not use this space unless we have
4218   // too many vectors to fit in registers, something that only occurs in
4219   // constructed examples:), but we have to walk the arglist to figure
4220   // that out...for the pathological case, compute VecArgOffset as the
4221   // start of the vector parameter area.  Computing VecArgOffset is the
4222   // entire point of the following loop.
4223   unsigned VecArgOffset = ArgOffset;
4224   if (!isVarArg && !isPPC64) {
4225     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4226          ++ArgNo) {
4227       EVT ObjectVT = Ins[ArgNo].VT;
4228       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4229 
4230       if (Flags.isByVal()) {
4231         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4232         unsigned ObjSize = Flags.getByValSize();
4233         unsigned ArgSize =
4234                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4235         VecArgOffset += ArgSize;
4236         continue;
4237       }
4238 
4239       switch(ObjectVT.getSimpleVT().SimpleTy) {
4240       default: llvm_unreachable("Unhandled argument type!");
4241       case MVT::i1:
4242       case MVT::i32:
4243       case MVT::f32:
4244         VecArgOffset += 4;
4245         break;
4246       case MVT::i64:  // PPC64
4247       case MVT::f64:
4248         // FIXME: We are guaranteed to be !isPPC64 at this point.
4249         // Does MVT::i64 apply?
4250         VecArgOffset += 8;
4251         break;
4252       case MVT::v4f32:
4253       case MVT::v4i32:
4254       case MVT::v8i16:
4255       case MVT::v16i8:
4256         // Nothing to do, we're only looking at Nonvector args here.
4257         break;
4258       }
4259     }
4260   }
4261   // We've found where the vector parameter area in memory is.  Skip the
4262   // first 12 parameters; these don't use that memory.
4263   VecArgOffset = ((VecArgOffset+15)/16)*16;
4264   VecArgOffset += 12*16;
4265 
4266   // Add DAG nodes to load the arguments or copy them out of registers.  On
4267   // entry to a function on PPC, the arguments start after the linkage area,
4268   // although the first ones are often in registers.
4269 
4270   SmallVector<SDValue, 8> MemOps;
4271   unsigned nAltivecParamsAtEnd = 0;
4272   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4273   unsigned CurArgIdx = 0;
4274   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4275     SDValue ArgVal;
4276     bool needsLoad = false;
4277     EVT ObjectVT = Ins[ArgNo].VT;
4278     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4279     unsigned ArgSize = ObjSize;
4280     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4281     if (Ins[ArgNo].isOrigArg()) {
4282       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4283       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4284     }
4285     unsigned CurArgOffset = ArgOffset;
4286 
4287     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4288     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4289         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4290       if (isVarArg || isPPC64) {
4291         MinReservedArea = ((MinReservedArea+15)/16)*16;
4292         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4293                                                   Flags,
4294                                                   PtrByteSize);
4295       } else  nAltivecParamsAtEnd++;
4296     } else
4297       // Calculate min reserved area.
4298       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4299                                                 Flags,
4300                                                 PtrByteSize);
4301 
4302     // FIXME the codegen can be much improved in some cases.
4303     // We do not have to keep everything in memory.
4304     if (Flags.isByVal()) {
4305       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4306 
4307       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4308       ObjSize = Flags.getByValSize();
4309       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4310       // Objects of size 1 and 2 are right justified, everything else is
4311       // left justified.  This means the memory address is adjusted forwards.
4312       if (ObjSize==1 || ObjSize==2) {
4313         CurArgOffset = CurArgOffset + (4 - ObjSize);
4314       }
4315       // The value of the object is its address.
4316       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4317       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4318       InVals.push_back(FIN);
4319       if (ObjSize==1 || ObjSize==2) {
4320         if (GPR_idx != Num_GPR_Regs) {
4321           unsigned VReg;
4322           if (isPPC64)
4323             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4324           else
4325             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4326           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4327           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4328           SDValue Store =
4329               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4330                                 MachinePointerInfo(&*FuncArg), ObjType);
4331           MemOps.push_back(Store);
4332           ++GPR_idx;
4333         }
4334 
4335         ArgOffset += PtrByteSize;
4336 
4337         continue;
4338       }
4339       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4340         // Store whatever pieces of the object are in registers
4341         // to memory.  ArgOffset will be the address of the beginning
4342         // of the object.
4343         if (GPR_idx != Num_GPR_Regs) {
4344           unsigned VReg;
4345           if (isPPC64)
4346             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4347           else
4348             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4349           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4350           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4351           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4352           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4353                                        MachinePointerInfo(&*FuncArg, j));
4354           MemOps.push_back(Store);
4355           ++GPR_idx;
4356           ArgOffset += PtrByteSize;
4357         } else {
4358           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4359           break;
4360         }
4361       }
4362       continue;
4363     }
4364 
4365     switch (ObjectVT.getSimpleVT().SimpleTy) {
4366     default: llvm_unreachable("Unhandled argument type!");
4367     case MVT::i1:
4368     case MVT::i32:
4369       if (!isPPC64) {
4370         if (GPR_idx != Num_GPR_Regs) {
4371           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4372           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4373 
4374           if (ObjectVT == MVT::i1)
4375             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4376 
4377           ++GPR_idx;
4378         } else {
4379           needsLoad = true;
4380           ArgSize = PtrByteSize;
4381         }
4382         // All int arguments reserve stack space in the Darwin ABI.
4383         ArgOffset += PtrByteSize;
4384         break;
4385       }
4386       LLVM_FALLTHROUGH;
4387     case MVT::i64:  // PPC64
4388       if (GPR_idx != Num_GPR_Regs) {
4389         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4390         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4391 
4392         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4393           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4394           // value to MVT::i64 and then truncate to the correct register size.
4395           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4396 
4397         ++GPR_idx;
4398       } else {
4399         needsLoad = true;
4400         ArgSize = PtrByteSize;
4401       }
4402       // All int arguments reserve stack space in the Darwin ABI.
4403       ArgOffset += 8;
4404       break;
4405 
4406     case MVT::f32:
4407     case MVT::f64:
4408       // Every 4 bytes of argument space consumes one of the GPRs available for
4409       // argument passing.
4410       if (GPR_idx != Num_GPR_Regs) {
4411         ++GPR_idx;
4412         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4413           ++GPR_idx;
4414       }
4415       if (FPR_idx != Num_FPR_Regs) {
4416         unsigned VReg;
4417 
4418         if (ObjectVT == MVT::f32)
4419           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4420         else
4421           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4422 
4423         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4424         ++FPR_idx;
4425       } else {
4426         needsLoad = true;
4427       }
4428 
4429       // All FP arguments reserve stack space in the Darwin ABI.
4430       ArgOffset += isPPC64 ? 8 : ObjSize;
4431       break;
4432     case MVT::v4f32:
4433     case MVT::v4i32:
4434     case MVT::v8i16:
4435     case MVT::v16i8:
4436       // Note that vector arguments in registers don't reserve stack space,
4437       // except in varargs functions.
4438       if (VR_idx != Num_VR_Regs) {
4439         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4440         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4441         if (isVarArg) {
4442           while ((ArgOffset % 16) != 0) {
4443             ArgOffset += PtrByteSize;
4444             if (GPR_idx != Num_GPR_Regs)
4445               GPR_idx++;
4446           }
4447           ArgOffset += 16;
4448           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4449         }
4450         ++VR_idx;
4451       } else {
4452         if (!isVarArg && !isPPC64) {
4453           // Vectors go after all the nonvectors.
4454           CurArgOffset = VecArgOffset;
4455           VecArgOffset += 16;
4456         } else {
4457           // Vectors are aligned.
4458           ArgOffset = ((ArgOffset+15)/16)*16;
4459           CurArgOffset = ArgOffset;
4460           ArgOffset += 16;
4461         }
4462         needsLoad = true;
4463       }
4464       break;
4465     }
4466 
4467     // We need to load the argument to a virtual register if we determined above
4468     // that we ran out of physical registers of the appropriate type.
4469     if (needsLoad) {
4470       int FI = MFI.CreateFixedObject(ObjSize,
4471                                      CurArgOffset + (ArgSize - ObjSize),
4472                                      isImmutable);
4473       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4474       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4475     }
4476 
4477     InVals.push_back(ArgVal);
4478   }
4479 
4480   // Allow for Altivec parameters at the end, if needed.
4481   if (nAltivecParamsAtEnd) {
4482     MinReservedArea = ((MinReservedArea+15)/16)*16;
4483     MinReservedArea += 16*nAltivecParamsAtEnd;
4484   }
4485 
4486   // Area that is at least reserved in the caller of this function.
4487   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4488 
4489   // Set the size that is at least reserved in caller of this function.  Tail
4490   // call optimized functions' reserved stack space needs to be aligned so that
4491   // taking the difference between two stack areas will result in an aligned
4492   // stack.
4493   MinReservedArea =
4494       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4495   FuncInfo->setMinReservedArea(MinReservedArea);
4496 
4497   // If the function takes variable number of arguments, make a frame index for
4498   // the start of the first vararg value... for expansion of llvm.va_start.
4499   if (isVarArg) {
4500     int Depth = ArgOffset;
4501 
4502     FuncInfo->setVarArgsFrameIndex(
4503       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4504                             Depth, true));
4505     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4506 
4507     // If this function is vararg, store any remaining integer argument regs
4508     // to their spots on the stack so that they may be loaded by dereferencing
4509     // the result of va_next.
4510     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4511       unsigned VReg;
4512 
4513       if (isPPC64)
4514         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4515       else
4516         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4517 
4518       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4519       SDValue Store =
4520           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4521       MemOps.push_back(Store);
4522       // Increment the address by four for the next argument to store
4523       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4524       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4525     }
4526   }
4527 
4528   if (!MemOps.empty())
4529     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4530 
4531   return Chain;
4532 }
4533 
4534 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4535 /// adjusted to accommodate the arguments for the tailcall.
4536 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4537                                    unsigned ParamSize) {
4538 
4539   if (!isTailCall) return 0;
4540 
4541   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4542   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4543   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4544   // Remember only if the new adjustment is bigger.
4545   if (SPDiff < FI->getTailCallSPDelta())
4546     FI->setTailCallSPDelta(SPDiff);
4547 
4548   return SPDiff;
4549 }
4550 
4551 static bool isFunctionGlobalAddress(SDValue Callee);
4552 
4553 static bool
4554 callsShareTOCBase(const Function *Caller, SDValue Callee,
4555                     const TargetMachine &TM) {
4556    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4557    // don't have enough information to determine if the caller and calle share
4558    // the same  TOC base, so we have to pessimistically assume they don't for
4559    // correctness.
4560    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4561    if (!G)
4562      return false;
4563 
4564    const GlobalValue *GV = G->getGlobal();
4565   // The medium and large code models are expected to provide a sufficiently
4566   // large TOC to provide all data addressing needs of a module with a
4567   // single TOC. Since each module will be addressed with a single TOC then we
4568   // only need to check that caller and callee don't cross dso boundaries.
4569   if (CodeModel::Medium == TM.getCodeModel() ||
4570       CodeModel::Large == TM.getCodeModel())
4571     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4572 
4573   // Otherwise we need to ensure callee and caller are in the same section,
4574   // since the linker may allocate multiple TOCs, and we don't know which
4575   // sections will belong to the same TOC base.
4576 
4577   if (!GV->isStrongDefinitionForLinker())
4578     return false;
4579 
4580   // Any explicitly-specified sections and section prefixes must also match.
4581   // Also, if we're using -ffunction-sections, then each function is always in
4582   // a different section (the same is true for COMDAT functions).
4583   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4584       GV->getSection() != Caller->getSection())
4585     return false;
4586   if (const auto *F = dyn_cast<Function>(GV)) {
4587     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4588       return false;
4589   }
4590 
4591   // If the callee might be interposed, then we can't assume the ultimate call
4592   // target will be in the same section. Even in cases where we can assume that
4593   // interposition won't happen, in any case where the linker might insert a
4594   // stub to allow for interposition, we must generate code as though
4595   // interposition might occur. To understand why this matters, consider a
4596   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4597   // in the same section, but a is in a different module (i.e. has a different
4598   // TOC base pointer). If the linker allows for interposition between b and c,
4599   // then it will generate a stub for the call edge between b and c which will
4600   // save the TOC pointer into the designated stack slot allocated by b. If we
4601   // return true here, and therefore allow a tail call between b and c, that
4602   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4603   // pointer into the stack slot allocated by a (where the a -> b stub saved
4604   // a's TOC base pointer). If we're not considering a tail call, but rather,
4605   // whether a nop is needed after the call instruction in b, because the linker
4606   // will insert a stub, it might complain about a missing nop if we omit it
4607   // (although many don't complain in this case).
4608   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4609     return false;
4610 
4611   return true;
4612 }
4613 
4614 static bool
4615 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4616                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4617   assert(Subtarget.is64BitELFABI());
4618 
4619   const unsigned PtrByteSize = 8;
4620   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4621 
4622   static const MCPhysReg GPR[] = {
4623     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4624     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4625   };
4626   static const MCPhysReg VR[] = {
4627     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4628     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4629   };
4630 
4631   const unsigned NumGPRs = array_lengthof(GPR);
4632   const unsigned NumFPRs = 13;
4633   const unsigned NumVRs = array_lengthof(VR);
4634   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4635 
4636   unsigned NumBytes = LinkageSize;
4637   unsigned AvailableFPRs = NumFPRs;
4638   unsigned AvailableVRs = NumVRs;
4639 
4640   for (const ISD::OutputArg& Param : Outs) {
4641     if (Param.Flags.isNest()) continue;
4642 
4643     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4644                                PtrByteSize, LinkageSize, ParamAreaSize,
4645                                NumBytes, AvailableFPRs, AvailableVRs,
4646                                Subtarget.hasQPX()))
4647       return true;
4648   }
4649   return false;
4650 }
4651 
4652 static bool
4653 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4654   if (CS.arg_size() != CallerFn->arg_size())
4655     return false;
4656 
4657   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4658   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4659   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4660 
4661   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4662     const Value* CalleeArg = *CalleeArgIter;
4663     const Value* CallerArg = &(*CallerArgIter);
4664     if (CalleeArg == CallerArg)
4665       continue;
4666 
4667     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4668     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4669     //      }
4670     // 1st argument of callee is undef and has the same type as caller.
4671     if (CalleeArg->getType() == CallerArg->getType() &&
4672         isa<UndefValue>(CalleeArg))
4673       continue;
4674 
4675     return false;
4676   }
4677 
4678   return true;
4679 }
4680 
4681 // Returns true if TCO is possible between the callers and callees
4682 // calling conventions.
4683 static bool
4684 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4685                                     CallingConv::ID CalleeCC) {
4686   // Tail calls are possible with fastcc and ccc.
4687   auto isTailCallableCC  = [] (CallingConv::ID CC){
4688       return  CC == CallingConv::C || CC == CallingConv::Fast;
4689   };
4690   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4691     return false;
4692 
4693   // We can safely tail call both fastcc and ccc callees from a c calling
4694   // convention caller. If the caller is fastcc, we may have less stack space
4695   // than a non-fastcc caller with the same signature so disable tail-calls in
4696   // that case.
4697   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4698 }
4699 
4700 bool
4701 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4702                                     SDValue Callee,
4703                                     CallingConv::ID CalleeCC,
4704                                     ImmutableCallSite CS,
4705                                     bool isVarArg,
4706                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4707                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4708                                     SelectionDAG& DAG) const {
4709   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4710 
4711   if (DisableSCO && !TailCallOpt) return false;
4712 
4713   // Variadic argument functions are not supported.
4714   if (isVarArg) return false;
4715 
4716   auto &Caller = DAG.getMachineFunction().getFunction();
4717   // Check that the calling conventions are compatible for tco.
4718   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4719     return false;
4720 
4721   // Caller contains any byval parameter is not supported.
4722   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4723     return false;
4724 
4725   // Callee contains any byval parameter is not supported, too.
4726   // Note: This is a quick work around, because in some cases, e.g.
4727   // caller's stack size > callee's stack size, we are still able to apply
4728   // sibling call optimization. For example, gcc is able to do SCO for caller1
4729   // in the following example, but not for caller2.
4730   //   struct test {
4731   //     long int a;
4732   //     char ary[56];
4733   //   } gTest;
4734   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4735   //     b->a = v.a;
4736   //     return 0;
4737   //   }
4738   //   void caller1(struct test a, struct test c, struct test *b) {
4739   //     callee(gTest, b); }
4740   //   void caller2(struct test *b) { callee(gTest, b); }
4741   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4742     return false;
4743 
4744   // If callee and caller use different calling conventions, we cannot pass
4745   // parameters on stack since offsets for the parameter area may be different.
4746   if (Caller.getCallingConv() != CalleeCC &&
4747       needStackSlotPassParameters(Subtarget, Outs))
4748     return false;
4749 
4750   // No TCO/SCO on indirect call because Caller have to restore its TOC
4751   if (!isFunctionGlobalAddress(Callee) &&
4752       !isa<ExternalSymbolSDNode>(Callee))
4753     return false;
4754 
4755   // If the caller and callee potentially have different TOC bases then we
4756   // cannot tail call since we need to restore the TOC pointer after the call.
4757   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4758   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4759     return false;
4760 
4761   // TCO allows altering callee ABI, so we don't have to check further.
4762   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4763     return true;
4764 
4765   if (DisableSCO) return false;
4766 
4767   // If callee use the same argument list that caller is using, then we can
4768   // apply SCO on this case. If it is not, then we need to check if callee needs
4769   // stack for passing arguments.
4770   if (!hasSameArgumentList(&Caller, CS) &&
4771       needStackSlotPassParameters(Subtarget, Outs)) {
4772     return false;
4773   }
4774 
4775   return true;
4776 }
4777 
4778 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4779 /// for tail call optimization. Targets which want to do tail call
4780 /// optimization should implement this function.
4781 bool
4782 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4783                                                      CallingConv::ID CalleeCC,
4784                                                      bool isVarArg,
4785                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4786                                                      SelectionDAG& DAG) const {
4787   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4788     return false;
4789 
4790   // Variable argument functions are not supported.
4791   if (isVarArg)
4792     return false;
4793 
4794   MachineFunction &MF = DAG.getMachineFunction();
4795   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4796   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4797     // Functions containing by val parameters are not supported.
4798     for (unsigned i = 0; i != Ins.size(); i++) {
4799        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4800        if (Flags.isByVal()) return false;
4801     }
4802 
4803     // Non-PIC/GOT tail calls are supported.
4804     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4805       return true;
4806 
4807     // At the moment we can only do local tail calls (in same module, hidden
4808     // or protected) if we are generating PIC.
4809     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4810       return G->getGlobal()->hasHiddenVisibility()
4811           || G->getGlobal()->hasProtectedVisibility();
4812   }
4813 
4814   return false;
4815 }
4816 
4817 /// isCallCompatibleAddress - Return the immediate to use if the specified
4818 /// 32-bit value is representable in the immediate field of a BxA instruction.
4819 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4820   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4821   if (!C) return nullptr;
4822 
4823   int Addr = C->getZExtValue();
4824   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4825       SignExtend32<26>(Addr) != Addr)
4826     return nullptr;  // Top 6 bits have to be sext of immediate.
4827 
4828   return DAG
4829       .getConstant(
4830           (int)C->getZExtValue() >> 2, SDLoc(Op),
4831           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4832       .getNode();
4833 }
4834 
4835 namespace {
4836 
4837 struct TailCallArgumentInfo {
4838   SDValue Arg;
4839   SDValue FrameIdxOp;
4840   int FrameIdx = 0;
4841 
4842   TailCallArgumentInfo() = default;
4843 };
4844 
4845 } // end anonymous namespace
4846 
4847 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4848 static void StoreTailCallArgumentsToStackSlot(
4849     SelectionDAG &DAG, SDValue Chain,
4850     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4851     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4852   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4853     SDValue Arg = TailCallArgs[i].Arg;
4854     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4855     int FI = TailCallArgs[i].FrameIdx;
4856     // Store relative to framepointer.
4857     MemOpChains.push_back(DAG.getStore(
4858         Chain, dl, Arg, FIN,
4859         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4860   }
4861 }
4862 
4863 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4864 /// the appropriate stack slot for the tail call optimized function call.
4865 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4866                                              SDValue OldRetAddr, SDValue OldFP,
4867                                              int SPDiff, const SDLoc &dl) {
4868   if (SPDiff) {
4869     // Calculate the new stack slot for the return address.
4870     MachineFunction &MF = DAG.getMachineFunction();
4871     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4872     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4873     bool isPPC64 = Subtarget.isPPC64();
4874     int SlotSize = isPPC64 ? 8 : 4;
4875     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4876     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4877                                                          NewRetAddrLoc, true);
4878     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4879     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4880     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4881                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4882 
4883     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4884     // slot as the FP is never overwritten.
4885     if (Subtarget.isDarwinABI()) {
4886       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4887       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4888                                                          true);
4889       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4890       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4891                            MachinePointerInfo::getFixedStack(
4892                                DAG.getMachineFunction(), NewFPIdx));
4893     }
4894   }
4895   return Chain;
4896 }
4897 
4898 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4899 /// the position of the argument.
4900 static void
4901 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4902                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4903                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4904   int Offset = ArgOffset + SPDiff;
4905   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4906   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4907   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4908   SDValue FIN = DAG.getFrameIndex(FI, VT);
4909   TailCallArgumentInfo Info;
4910   Info.Arg = Arg;
4911   Info.FrameIdxOp = FIN;
4912   Info.FrameIdx = FI;
4913   TailCallArguments.push_back(Info);
4914 }
4915 
4916 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4917 /// stack slot. Returns the chain as result and the loaded frame pointers in
4918 /// LROpOut/FPOpout. Used when tail calling.
4919 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4920     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4921     SDValue &FPOpOut, const SDLoc &dl) const {
4922   if (SPDiff) {
4923     // Load the LR and FP stack slot for later adjusting.
4924     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4925     LROpOut = getReturnAddrFrameIndex(DAG);
4926     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4927     Chain = SDValue(LROpOut.getNode(), 1);
4928 
4929     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4930     // slot as the FP is never overwritten.
4931     if (Subtarget.isDarwinABI()) {
4932       FPOpOut = getFramePointerFrameIndex(DAG);
4933       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4934       Chain = SDValue(FPOpOut.getNode(), 1);
4935     }
4936   }
4937   return Chain;
4938 }
4939 
4940 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4941 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4942 /// specified by the specific parameter attribute. The copy will be passed as
4943 /// a byval function parameter.
4944 /// Sometimes what we are copying is the end of a larger object, the part that
4945 /// does not fit in registers.
4946 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4947                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4948                                          SelectionDAG &DAG, const SDLoc &dl) {
4949   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4950   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4951                        false, false, false, MachinePointerInfo(),
4952                        MachinePointerInfo());
4953 }
4954 
4955 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4956 /// tail calls.
4957 static void LowerMemOpCallTo(
4958     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4959     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4960     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4961     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4962   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4963   if (!isTailCall) {
4964     if (isVector) {
4965       SDValue StackPtr;
4966       if (isPPC64)
4967         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4968       else
4969         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4970       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4971                            DAG.getConstant(ArgOffset, dl, PtrVT));
4972     }
4973     MemOpChains.push_back(
4974         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4975     // Calculate and remember argument location.
4976   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4977                                   TailCallArguments);
4978 }
4979 
4980 static void
4981 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4982                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4983                 SDValue FPOp,
4984                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4985   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4986   // might overwrite each other in case of tail call optimization.
4987   SmallVector<SDValue, 8> MemOpChains2;
4988   // Do not flag preceding copytoreg stuff together with the following stuff.
4989   InFlag = SDValue();
4990   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4991                                     MemOpChains2, dl);
4992   if (!MemOpChains2.empty())
4993     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4994 
4995   // Store the return address to the appropriate stack slot.
4996   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4997 
4998   // Emit callseq_end just before tailcall node.
4999   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5000                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5001   InFlag = Chain.getValue(1);
5002 }
5003 
5004 // Is this global address that of a function that can be called by name? (as
5005 // opposed to something that must hold a descriptor for an indirect call).
5006 static bool isFunctionGlobalAddress(SDValue Callee) {
5007   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5008     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5009         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5010       return false;
5011 
5012     return G->getGlobal()->getValueType()->isFunctionTy();
5013   }
5014 
5015   return false;
5016 }
5017 
5018 SDValue PPCTargetLowering::LowerCallResult(
5019     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5020     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5021     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5022   SmallVector<CCValAssign, 16> RVLocs;
5023   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5024                     *DAG.getContext());
5025 
5026   CCRetInfo.AnalyzeCallResult(
5027       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5028                ? RetCC_PPC_Cold
5029                : RetCC_PPC);
5030 
5031   // Copy all of the result registers out of their specified physreg.
5032   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5033     CCValAssign &VA = RVLocs[i];
5034     assert(VA.isRegLoc() && "Can only return in registers!");
5035 
5036     SDValue Val;
5037 
5038     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5039       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5040                                       InFlag);
5041       Chain = Lo.getValue(1);
5042       InFlag = Lo.getValue(2);
5043       VA = RVLocs[++i]; // skip ahead to next loc
5044       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5045                                       InFlag);
5046       Chain = Hi.getValue(1);
5047       InFlag = Hi.getValue(2);
5048       if (!Subtarget.isLittleEndian())
5049         std::swap (Lo, Hi);
5050       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5051     } else {
5052       Val = DAG.getCopyFromReg(Chain, dl,
5053                                VA.getLocReg(), VA.getLocVT(), InFlag);
5054       Chain = Val.getValue(1);
5055       InFlag = Val.getValue(2);
5056     }
5057 
5058     switch (VA.getLocInfo()) {
5059     default: llvm_unreachable("Unknown loc info!");
5060     case CCValAssign::Full: break;
5061     case CCValAssign::AExt:
5062       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5063       break;
5064     case CCValAssign::ZExt:
5065       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5066                         DAG.getValueType(VA.getValVT()));
5067       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5068       break;
5069     case CCValAssign::SExt:
5070       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5071                         DAG.getValueType(VA.getValVT()));
5072       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5073       break;
5074     }
5075 
5076     InVals.push_back(Val);
5077   }
5078 
5079   return Chain;
5080 }
5081 
5082 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5083                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5084   // PatchPoint calls are not indirect.
5085   if (isPatchPoint)
5086     return false;
5087 
5088   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5089     return false;
5090 
5091   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5092   // becuase the immediate function pointer points to a descriptor instead of
5093   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5094   // pointer immediate points to the global entry point, while the BLA would
5095   // need to jump to the local entry point (see rL211174).
5096   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5097       isBLACompatibleAddress(Callee, DAG))
5098     return false;
5099 
5100   return true;
5101 }
5102 
5103 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint,
5104                               bool isTailCall, const Function &Caller,
5105                               const SDValue &Callee,
5106                               const PPCSubtarget &Subtarget,
5107                               const TargetMachine &TM) {
5108   if (isTailCall)
5109     return PPCISD::TC_RETURN;
5110 
5111   // This is a call through a function pointer.
5112   if (isIndirectCall) {
5113     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5114     // indirect calls. The save of the caller's TOC pointer to the stack will be
5115     // inserted into the DAG as part of call lowering. The restore of the TOC
5116     // pointer is modeled by using a pseudo instruction for the call opcode that
5117     // represents the 2 instruction sequence of an indirect branch and link,
5118     // immediately followed by a load of the TOC pointer from the the stack save
5119     // slot into gpr2.
5120     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5121       return PPCISD::BCTRL_LOAD_TOC;
5122 
5123     // An indirect call that does not need a TOC restore.
5124     return PPCISD::BCTRL;
5125   }
5126 
5127   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5128   // immediately following the call instruction if the caller and callee may
5129   // have different TOC bases. At link time if the linker determines the calls
5130   // may not share a TOC base, the call is redirected to a trampoline inserted
5131   // by the linker. The trampoline will (among other things) save the callers
5132   // TOC pointer at an ABI designated offset in the linkage area and the linker
5133   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5134   // into gpr2.
5135   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5136     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5137                                                   : PPCISD::CALL_NOP;
5138 
5139   return PPCISD::CALL;
5140 }
5141 
5142 static bool isValidAIXExternalSymSDNode(StringRef SymName) {
5143   return StringSwitch<bool>(SymName)
5144       .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf",
5145              "__moddi3", "__udivdi3", "__umoddi3", true)
5146       .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true)
5147       .Default(false);
5148 }
5149 
5150 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5151                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5152   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5153     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5154       return SDValue(Dest, 0);
5155 
5156   // Returns true if the callee is local, and false otherwise.
5157   auto isLocalCallee = [&]() {
5158     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5159     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5160     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5161 
5162     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5163            !dyn_cast_or_null<GlobalIFunc>(GV);
5164   };
5165 
5166   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5167   // a static relocation model causes some versions of GNU LD (2.17.50, at
5168   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5169   // built with secure-PLT.
5170   bool UsePlt =
5171       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5172       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5173 
5174   // On AIX, direct function calls reference the symbol for the function's
5175   // entry point, which is named by prepending a "." before the function's
5176   // C-linkage name.
5177   const auto getAIXFuncEntryPointSymbolSDNode =
5178       [&](StringRef FuncName, bool IsDeclaration,
5179           const XCOFF::StorageClass &SC) {
5180         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5181 
5182         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5183             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5184 
5185         if (IsDeclaration && !S->hasContainingCsect()) {
5186           // On AIX, an undefined symbol needs to be associated with a
5187           // MCSectionXCOFF to get the correct storage mapping class.
5188           // In this case, XCOFF::XMC_PR.
5189           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5190               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5191               SectionKind::getMetadata());
5192           S->setContainingCsect(Sec);
5193         }
5194 
5195         MVT PtrVT =
5196             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5197         return DAG.getMCSymbol(S, PtrVT);
5198       };
5199 
5200   if (isFunctionGlobalAddress(Callee)) {
5201     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5202     const GlobalValue *GV = G->getGlobal();
5203 
5204     if (!Subtarget.isAIXABI())
5205       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5206                                         UsePlt ? PPCII::MO_PLT : 0);
5207 
5208     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5209     const GlobalObject *GO = cast<GlobalObject>(GV);
5210     const XCOFF::StorageClass SC =
5211         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5212     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5213                                             SC);
5214   }
5215 
5216   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5217     const char *SymName = S->getSymbol();
5218     if (!Subtarget.isAIXABI())
5219       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5220                                          UsePlt ? PPCII::MO_PLT : 0);
5221 
5222     // If there exists a user-declared function whose name is the same as the
5223     // ExternalSymbol's, then we pick up the user-declared version.
5224     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5225     if (const Function *F =
5226             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5227       const XCOFF::StorageClass SC =
5228           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5229       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5230                                               SC);
5231     }
5232 
5233     // TODO: Remove this when the support for ExternalSymbolSDNode is complete.
5234     if (isValidAIXExternalSymSDNode(SymName)) {
5235       return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5236     }
5237 
5238     report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName));
5239   }
5240 
5241   // No transformation needed.
5242   assert(Callee.getNode() && "What no callee?");
5243   return Callee;
5244 }
5245 
5246 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5247   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5248          "Expected a CALLSEQ_STARTSDNode.");
5249 
5250   // The last operand is the chain, except when the node has glue. If the node
5251   // has glue, then the last operand is the glue, and the chain is the second
5252   // last operand.
5253   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5254   if (LastValue.getValueType() != MVT::Glue)
5255     return LastValue;
5256 
5257   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5258 }
5259 
5260 // Creates the node that moves a functions address into the count register
5261 // to prepare for an indirect call instruction.
5262 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5263                                 SDValue &Glue, SDValue &Chain,
5264                                 const SDLoc &dl) {
5265   SDValue MTCTROps[] = {Chain, Callee, Glue};
5266   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5267   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5268                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5269   // The glue is the second value produced.
5270   Glue = Chain.getValue(1);
5271 }
5272 
5273 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5274                                           SDValue &Glue, SDValue &Chain,
5275                                           SDValue CallSeqStart,
5276                                           ImmutableCallSite CS, const SDLoc &dl,
5277                                           bool hasNest,
5278                                           const PPCSubtarget &Subtarget) {
5279   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5280   // entry point, but to the function descriptor (the function entry point
5281   // address is part of the function descriptor though).
5282   // The function descriptor is a three doubleword structure with the
5283   // following fields: function entry point, TOC base address and
5284   // environment pointer.
5285   // Thus for a call through a function pointer, the following actions need
5286   // to be performed:
5287   //   1. Save the TOC of the caller in the TOC save area of its stack
5288   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5289   //   2. Load the address of the function entry point from the function
5290   //      descriptor.
5291   //   3. Load the TOC of the callee from the function descriptor into r2.
5292   //   4. Load the environment pointer from the function descriptor into
5293   //      r11.
5294   //   5. Branch to the function entry point address.
5295   //   6. On return of the callee, the TOC of the caller needs to be
5296   //      restored (this is done in FinishCall()).
5297   //
5298   // The loads are scheduled at the beginning of the call sequence, and the
5299   // register copies are flagged together to ensure that no other
5300   // operations can be scheduled in between. E.g. without flagging the
5301   // copies together, a TOC access in the caller could be scheduled between
5302   // the assignment of the callee TOC and the branch to the callee, which leads
5303   // to incorrect code.
5304 
5305   // Start by loading the function address from the descriptor.
5306   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5307   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5308                       ? (MachineMemOperand::MODereferenceable |
5309                          MachineMemOperand::MOInvariant)
5310                       : MachineMemOperand::MONone;
5311 
5312   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5313 
5314   // Registers used in building the DAG.
5315   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5316   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5317 
5318   // Offsets of descriptor members.
5319   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5320   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5321 
5322   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5323   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5324 
5325   // One load for the functions entry point address.
5326   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5327                                     Alignment, MMOFlags);
5328 
5329   // One for loading the TOC anchor for the module that contains the called
5330   // function.
5331   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5332   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5333   SDValue TOCPtr =
5334       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5335                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5336 
5337   // One for loading the environment pointer.
5338   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5339   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5340   SDValue LoadEnvPtr =
5341       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5342                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5343 
5344 
5345   // Then copy the newly loaded TOC anchor to the TOC pointer.
5346   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5347   Chain = TOCVal.getValue(0);
5348   Glue = TOCVal.getValue(1);
5349 
5350   // If the function call has an explicit 'nest' parameter, it takes the
5351   // place of the environment pointer.
5352   assert((!hasNest || !Subtarget.isAIXABI()) &&
5353          "Nest parameter is not supported on AIX.");
5354   if (!hasNest) {
5355     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5356     Chain = EnvVal.getValue(0);
5357     Glue = EnvVal.getValue(1);
5358   }
5359 
5360   // The rest of the indirect call sequence is the same as the non-descriptor
5361   // DAG.
5362   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5363 }
5364 
5365 static void
5366 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv,
5367                   const SDLoc &dl, bool isTailCall, bool isVarArg,
5368                   bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5369                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5370                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5371                   const PPCSubtarget &Subtarget, bool isIndirect) {
5372   const bool IsPPC64 = Subtarget.isPPC64();
5373   // MVT for a general purpose register.
5374   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5375 
5376   // First operand is always the chain.
5377   Ops.push_back(Chain);
5378 
5379   // If it's a direct call pass the callee as the second operand.
5380   if (!isIndirect)
5381     Ops.push_back(Callee);
5382   else {
5383     assert(!isPatchPoint && "Patch point call are not indirect.");
5384 
5385     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5386     // on the stack (this would have been done in `LowerCall_64SVR4` or
5387     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5388     // represents both the indirect branch and a load that restores the TOC
5389     // pointer from the linkage area. The operand for the TOC restore is an add
5390     // of the TOC save offset to the stack pointer. This must be the second
5391     // operand: after the chain input but before any other variadic arguments.
5392     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5393       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5394 
5395       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5396       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5397       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5398       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5399       Ops.push_back(AddTOC);
5400     }
5401 
5402     // Add the register used for the environment pointer.
5403     if (Subtarget.usesFunctionDescriptors() && !hasNest)
5404       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5405                                     RegVT));
5406 
5407 
5408     // Add CTR register as callee so a bctr can be emitted later.
5409     if (isTailCall)
5410       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5411   }
5412 
5413   // If this is a tail call add stack pointer delta.
5414   if (isTailCall)
5415     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5416 
5417   // Add argument registers to the end of the list so that they are known live
5418   // into the call.
5419   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5420     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5421                                   RegsToPass[i].second.getValueType()));
5422 
5423   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5424   // no way to mark dependencies as implicit here.
5425   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5426   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint)
5427     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5428 
5429   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5430   if (isVarArg && Subtarget.is32BitELFABI())
5431     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5432 
5433   // Add a register mask operand representing the call-preserved registers.
5434   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5435   const uint32_t *Mask =
5436       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5437   assert(Mask && "Missing call preserved mask for calling convention");
5438   Ops.push_back(DAG.getRegisterMask(Mask));
5439 
5440   // If the glue is valid, it is the last operand.
5441   if (Glue.getNode())
5442     Ops.push_back(Glue);
5443 }
5444 
5445 SDValue PPCTargetLowering::FinishCall(
5446     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5447     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5448     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5449     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5450     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5451     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5452 
5453   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5454     setUsesTOCBasePtr(DAG);
5455 
5456   const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint);
5457   unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall,
5458                                    DAG.getMachineFunction().getFunction(),
5459                                    Callee, Subtarget, DAG.getTarget());
5460 
5461   if (!isIndirect)
5462     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5463   else if (Subtarget.usesFunctionDescriptors())
5464     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5465                                   dl, hasNest, Subtarget);
5466   else
5467     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5468 
5469   // Build the operand list for the call instruction.
5470   SmallVector<SDValue, 8> Ops;
5471   buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5472                     hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff,
5473                     Subtarget, isIndirect);
5474 
5475   // Emit tail call.
5476   if (isTailCall) {
5477     assert(((Callee.getOpcode() == ISD::Register &&
5478              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5479             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5480             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5481             isa<ConstantSDNode>(Callee)) &&
5482            "Expecting a global address, external symbol, absolute value or "
5483            "register");
5484     assert(CallOpc == PPCISD::TC_RETURN &&
5485            "Unexpected call opcode for a tail call.");
5486     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5487     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5488   }
5489 
5490   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5491   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5492   Glue = Chain.getValue(1);
5493 
5494   // When performing tail call optimization the callee pops its arguments off
5495   // the stack. Account for this here so these bytes can be pushed back on in
5496   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5497   int BytesCalleePops = (CallConv == CallingConv::Fast &&
5498                          getTargetMachine().Options.GuaranteedTailCallOpt)
5499                             ? NumBytes
5500                             : 0;
5501 
5502   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5503                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5504                              Glue, dl);
5505   Glue = Chain.getValue(1);
5506 
5507   return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals);
5508 }
5509 
5510 SDValue
5511 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5512                              SmallVectorImpl<SDValue> &InVals) const {
5513   SelectionDAG &DAG                     = CLI.DAG;
5514   SDLoc &dl                             = CLI.DL;
5515   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5516   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5517   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5518   SDValue Chain                         = CLI.Chain;
5519   SDValue Callee                        = CLI.Callee;
5520   bool &isTailCall                      = CLI.IsTailCall;
5521   CallingConv::ID CallConv              = CLI.CallConv;
5522   bool isVarArg                         = CLI.IsVarArg;
5523   bool isPatchPoint                     = CLI.IsPatchPoint;
5524   ImmutableCallSite CS                  = CLI.CS;
5525 
5526   if (isTailCall) {
5527     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5528       isTailCall = false;
5529     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5530       isTailCall =
5531         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5532                                                  isVarArg, Outs, Ins, DAG);
5533     else
5534       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5535                                                      Ins, DAG);
5536     if (isTailCall) {
5537       ++NumTailCalls;
5538       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5539         ++NumSiblingCalls;
5540 
5541       assert(isa<GlobalAddressSDNode>(Callee) &&
5542              "Callee should be an llvm::Function object.");
5543       LLVM_DEBUG(
5544           const GlobalValue *GV =
5545               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5546           const unsigned Width =
5547               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5548           dbgs() << "TCO caller: "
5549                  << left_justify(DAG.getMachineFunction().getName(), Width)
5550                  << ", callee linkage: " << GV->getVisibility() << ", "
5551                  << GV->getLinkage() << "\n");
5552     }
5553   }
5554 
5555   if (!isTailCall && CS && CS.isMustTailCall())
5556     report_fatal_error("failed to perform tail call elimination on a call "
5557                        "site marked musttail");
5558 
5559   // When long calls (i.e. indirect calls) are always used, calls are always
5560   // made via function pointer. If we have a function name, first translate it
5561   // into a pointer.
5562   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5563       !isTailCall)
5564     Callee = LowerGlobalAddress(Callee, DAG);
5565 
5566   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5567     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5568                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5569                             dl, DAG, InVals, CS);
5570 
5571   if (Subtarget.isSVR4ABI())
5572     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5573                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5574                             dl, DAG, InVals, CS);
5575 
5576   if (Subtarget.isAIXABI())
5577     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5578                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5579                          dl, DAG, InVals, CS);
5580 
5581   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5582                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5583                           dl, DAG, InVals, CS);
5584 }
5585 
5586 SDValue PPCTargetLowering::LowerCall_32SVR4(
5587     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5588     bool isTailCall, bool isPatchPoint,
5589     const SmallVectorImpl<ISD::OutputArg> &Outs,
5590     const SmallVectorImpl<SDValue> &OutVals,
5591     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5592     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5593     ImmutableCallSite CS) const {
5594   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5595   // of the 32-bit SVR4 ABI stack frame layout.
5596 
5597   assert((CallConv == CallingConv::C ||
5598           CallConv == CallingConv::Cold ||
5599           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5600 
5601   unsigned PtrByteSize = 4;
5602 
5603   MachineFunction &MF = DAG.getMachineFunction();
5604 
5605   // Mark this function as potentially containing a function that contains a
5606   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5607   // and restoring the callers stack pointer in this functions epilog. This is
5608   // done because by tail calling the called function might overwrite the value
5609   // in this function's (MF) stack pointer stack slot 0(SP).
5610   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5611       CallConv == CallingConv::Fast)
5612     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5613 
5614   // Count how many bytes are to be pushed on the stack, including the linkage
5615   // area, parameter list area and the part of the local variable space which
5616   // contains copies of aggregates which are passed by value.
5617 
5618   // Assign locations to all of the outgoing arguments.
5619   SmallVector<CCValAssign, 16> ArgLocs;
5620   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5621 
5622   // Reserve space for the linkage area on the stack.
5623   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5624                        PtrByteSize);
5625   if (useSoftFloat())
5626     CCInfo.PreAnalyzeCallOperands(Outs);
5627 
5628   if (isVarArg) {
5629     // Handle fixed and variable vector arguments differently.
5630     // Fixed vector arguments go into registers as long as registers are
5631     // available. Variable vector arguments always go into memory.
5632     unsigned NumArgs = Outs.size();
5633 
5634     for (unsigned i = 0; i != NumArgs; ++i) {
5635       MVT ArgVT = Outs[i].VT;
5636       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5637       bool Result;
5638 
5639       if (Outs[i].IsFixed) {
5640         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5641                                CCInfo);
5642       } else {
5643         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5644                                       ArgFlags, CCInfo);
5645       }
5646 
5647       if (Result) {
5648 #ifndef NDEBUG
5649         errs() << "Call operand #" << i << " has unhandled type "
5650              << EVT(ArgVT).getEVTString() << "\n";
5651 #endif
5652         llvm_unreachable(nullptr);
5653       }
5654     }
5655   } else {
5656     // All arguments are treated the same.
5657     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5658   }
5659   CCInfo.clearWasPPCF128();
5660 
5661   // Assign locations to all of the outgoing aggregate by value arguments.
5662   SmallVector<CCValAssign, 16> ByValArgLocs;
5663   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5664 
5665   // Reserve stack space for the allocations in CCInfo.
5666   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5667 
5668   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5669 
5670   // Size of the linkage area, parameter list area and the part of the local
5671   // space variable where copies of aggregates which are passed by value are
5672   // stored.
5673   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5674 
5675   // Calculate by how many bytes the stack has to be adjusted in case of tail
5676   // call optimization.
5677   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5678 
5679   // Adjust the stack pointer for the new arguments...
5680   // These operations are automatically eliminated by the prolog/epilog pass
5681   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5682   SDValue CallSeqStart = Chain;
5683 
5684   // Load the return address and frame pointer so it can be moved somewhere else
5685   // later.
5686   SDValue LROp, FPOp;
5687   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5688 
5689   // Set up a copy of the stack pointer for use loading and storing any
5690   // arguments that may not fit in the registers available for argument
5691   // passing.
5692   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5693 
5694   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5695   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5696   SmallVector<SDValue, 8> MemOpChains;
5697 
5698   bool seenFloatArg = false;
5699   // Walk the register/memloc assignments, inserting copies/loads.
5700   // i - Tracks the index into the list of registers allocated for the call
5701   // RealArgIdx - Tracks the index into the list of actual function arguments
5702   // j - Tracks the index into the list of byval arguments
5703   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5704        i != e;
5705        ++i, ++RealArgIdx) {
5706     CCValAssign &VA = ArgLocs[i];
5707     SDValue Arg = OutVals[RealArgIdx];
5708     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5709 
5710     if (Flags.isByVal()) {
5711       // Argument is an aggregate which is passed by value, thus we need to
5712       // create a copy of it in the local variable space of the current stack
5713       // frame (which is the stack frame of the caller) and pass the address of
5714       // this copy to the callee.
5715       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5716       CCValAssign &ByValVA = ByValArgLocs[j++];
5717       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5718 
5719       // Memory reserved in the local variable space of the callers stack frame.
5720       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5721 
5722       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5723       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5724                            StackPtr, PtrOff);
5725 
5726       // Create a copy of the argument in the local area of the current
5727       // stack frame.
5728       SDValue MemcpyCall =
5729         CreateCopyOfByValArgument(Arg, PtrOff,
5730                                   CallSeqStart.getNode()->getOperand(0),
5731                                   Flags, DAG, dl);
5732 
5733       // This must go outside the CALLSEQ_START..END.
5734       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5735                                                      SDLoc(MemcpyCall));
5736       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5737                              NewCallSeqStart.getNode());
5738       Chain = CallSeqStart = NewCallSeqStart;
5739 
5740       // Pass the address of the aggregate copy on the stack either in a
5741       // physical register or in the parameter list area of the current stack
5742       // frame to the callee.
5743       Arg = PtrOff;
5744     }
5745 
5746     // When useCRBits() is true, there can be i1 arguments.
5747     // It is because getRegisterType(MVT::i1) => MVT::i1,
5748     // and for other integer types getRegisterType() => MVT::i32.
5749     // Extend i1 and ensure callee will get i32.
5750     if (Arg.getValueType() == MVT::i1)
5751       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5752                         dl, MVT::i32, Arg);
5753 
5754     if (VA.isRegLoc()) {
5755       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5756       // Put argument in a physical register.
5757       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5758         bool IsLE = Subtarget.isLittleEndian();
5759         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5760                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5761         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5762         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5763                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5764         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5765                              SVal.getValue(0)));
5766       } else
5767         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5768     } else {
5769       // Put argument in the parameter list area of the current stack frame.
5770       assert(VA.isMemLoc());
5771       unsigned LocMemOffset = VA.getLocMemOffset();
5772 
5773       if (!isTailCall) {
5774         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5775         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5776                              StackPtr, PtrOff);
5777 
5778         MemOpChains.push_back(
5779             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5780       } else {
5781         // Calculate and remember argument location.
5782         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5783                                  TailCallArguments);
5784       }
5785     }
5786   }
5787 
5788   if (!MemOpChains.empty())
5789     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5790 
5791   // Build a sequence of copy-to-reg nodes chained together with token chain
5792   // and flag operands which copy the outgoing args into the appropriate regs.
5793   SDValue InFlag;
5794   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5795     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5796                              RegsToPass[i].second, InFlag);
5797     InFlag = Chain.getValue(1);
5798   }
5799 
5800   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5801   // registers.
5802   if (isVarArg) {
5803     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5804     SDValue Ops[] = { Chain, InFlag };
5805 
5806     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5807                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5808 
5809     InFlag = Chain.getValue(1);
5810   }
5811 
5812   if (isTailCall)
5813     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5814                     TailCallArguments);
5815 
5816   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5817                     /* unused except on PPC64 ELFv1 */ false, DAG,
5818                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5819                     NumBytes, Ins, InVals, CS);
5820 }
5821 
5822 // Copy an argument into memory, being careful to do this outside the
5823 // call sequence for the call to which the argument belongs.
5824 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5825     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5826     SelectionDAG &DAG, const SDLoc &dl) const {
5827   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5828                         CallSeqStart.getNode()->getOperand(0),
5829                         Flags, DAG, dl);
5830   // The MEMCPY must go outside the CALLSEQ_START..END.
5831   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5832   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5833                                                  SDLoc(MemcpyCall));
5834   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5835                          NewCallSeqStart.getNode());
5836   return NewCallSeqStart;
5837 }
5838 
5839 SDValue PPCTargetLowering::LowerCall_64SVR4(
5840     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5841     bool isTailCall, bool isPatchPoint,
5842     const SmallVectorImpl<ISD::OutputArg> &Outs,
5843     const SmallVectorImpl<SDValue> &OutVals,
5844     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5845     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5846     ImmutableCallSite CS) const {
5847   bool isELFv2ABI = Subtarget.isELFv2ABI();
5848   bool isLittleEndian = Subtarget.isLittleEndian();
5849   unsigned NumOps = Outs.size();
5850   bool hasNest = false;
5851   bool IsSibCall = false;
5852 
5853   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5854   unsigned PtrByteSize = 8;
5855 
5856   MachineFunction &MF = DAG.getMachineFunction();
5857 
5858   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5859     IsSibCall = true;
5860 
5861   // Mark this function as potentially containing a function that contains a
5862   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5863   // and restoring the callers stack pointer in this functions epilog. This is
5864   // done because by tail calling the called function might overwrite the value
5865   // in this function's (MF) stack pointer stack slot 0(SP).
5866   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5867       CallConv == CallingConv::Fast)
5868     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5869 
5870   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5871          "fastcc not supported on varargs functions");
5872 
5873   // Count how many bytes are to be pushed on the stack, including the linkage
5874   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5875   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5876   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5877   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5878   unsigned NumBytes = LinkageSize;
5879   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5880   unsigned &QFPR_idx = FPR_idx;
5881 
5882   static const MCPhysReg GPR[] = {
5883     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5884     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5885   };
5886   static const MCPhysReg VR[] = {
5887     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5888     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5889   };
5890 
5891   const unsigned NumGPRs = array_lengthof(GPR);
5892   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5893   const unsigned NumVRs  = array_lengthof(VR);
5894   const unsigned NumQFPRs = NumFPRs;
5895 
5896   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5897   // can be passed to the callee in registers.
5898   // For the fast calling convention, there is another check below.
5899   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5900   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5901   if (!HasParameterArea) {
5902     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5903     unsigned AvailableFPRs = NumFPRs;
5904     unsigned AvailableVRs = NumVRs;
5905     unsigned NumBytesTmp = NumBytes;
5906     for (unsigned i = 0; i != NumOps; ++i) {
5907       if (Outs[i].Flags.isNest()) continue;
5908       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5909                                 PtrByteSize, LinkageSize, ParamAreaSize,
5910                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5911                                 Subtarget.hasQPX()))
5912         HasParameterArea = true;
5913     }
5914   }
5915 
5916   // When using the fast calling convention, we don't provide backing for
5917   // arguments that will be in registers.
5918   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5919 
5920   // Avoid allocating parameter area for fastcc functions if all the arguments
5921   // can be passed in the registers.
5922   if (CallConv == CallingConv::Fast)
5923     HasParameterArea = false;
5924 
5925   // Add up all the space actually used.
5926   for (unsigned i = 0; i != NumOps; ++i) {
5927     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5928     EVT ArgVT = Outs[i].VT;
5929     EVT OrigVT = Outs[i].ArgVT;
5930 
5931     if (Flags.isNest())
5932       continue;
5933 
5934     if (CallConv == CallingConv::Fast) {
5935       if (Flags.isByVal()) {
5936         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5937         if (NumGPRsUsed > NumGPRs)
5938           HasParameterArea = true;
5939       } else {
5940         switch (ArgVT.getSimpleVT().SimpleTy) {
5941         default: llvm_unreachable("Unexpected ValueType for argument!");
5942         case MVT::i1:
5943         case MVT::i32:
5944         case MVT::i64:
5945           if (++NumGPRsUsed <= NumGPRs)
5946             continue;
5947           break;
5948         case MVT::v4i32:
5949         case MVT::v8i16:
5950         case MVT::v16i8:
5951         case MVT::v2f64:
5952         case MVT::v2i64:
5953         case MVT::v1i128:
5954         case MVT::f128:
5955           if (++NumVRsUsed <= NumVRs)
5956             continue;
5957           break;
5958         case MVT::v4f32:
5959           // When using QPX, this is handled like a FP register, otherwise, it
5960           // is an Altivec register.
5961           if (Subtarget.hasQPX()) {
5962             if (++NumFPRsUsed <= NumFPRs)
5963               continue;
5964           } else {
5965             if (++NumVRsUsed <= NumVRs)
5966               continue;
5967           }
5968           break;
5969         case MVT::f32:
5970         case MVT::f64:
5971         case MVT::v4f64: // QPX
5972         case MVT::v4i1:  // QPX
5973           if (++NumFPRsUsed <= NumFPRs)
5974             continue;
5975           break;
5976         }
5977         HasParameterArea = true;
5978       }
5979     }
5980 
5981     /* Respect alignment of argument on the stack.  */
5982     unsigned Align =
5983       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5984     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5985 
5986     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5987     if (Flags.isInConsecutiveRegsLast())
5988       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5989   }
5990 
5991   unsigned NumBytesActuallyUsed = NumBytes;
5992 
5993   // In the old ELFv1 ABI,
5994   // the prolog code of the callee may store up to 8 GPR argument registers to
5995   // the stack, allowing va_start to index over them in memory if its varargs.
5996   // Because we cannot tell if this is needed on the caller side, we have to
5997   // conservatively assume that it is needed.  As such, make sure we have at
5998   // least enough stack space for the caller to store the 8 GPRs.
5999   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6000   // really requires memory operands, e.g. a vararg function.
6001   if (HasParameterArea)
6002     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6003   else
6004     NumBytes = LinkageSize;
6005 
6006   // Tail call needs the stack to be aligned.
6007   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6008       CallConv == CallingConv::Fast)
6009     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6010 
6011   int SPDiff = 0;
6012 
6013   // Calculate by how many bytes the stack has to be adjusted in case of tail
6014   // call optimization.
6015   if (!IsSibCall)
6016     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6017 
6018   // To protect arguments on the stack from being clobbered in a tail call,
6019   // force all the loads to happen before doing any other lowering.
6020   if (isTailCall)
6021     Chain = DAG.getStackArgumentTokenFactor(Chain);
6022 
6023   // Adjust the stack pointer for the new arguments...
6024   // These operations are automatically eliminated by the prolog/epilog pass
6025   if (!IsSibCall)
6026     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6027   SDValue CallSeqStart = Chain;
6028 
6029   // Load the return address and frame pointer so it can be move somewhere else
6030   // later.
6031   SDValue LROp, FPOp;
6032   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6033 
6034   // Set up a copy of the stack pointer for use loading and storing any
6035   // arguments that may not fit in the registers available for argument
6036   // passing.
6037   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6038 
6039   // Figure out which arguments are going to go in registers, and which in
6040   // memory.  Also, if this is a vararg function, floating point operations
6041   // must be stored to our stack, and loaded into integer regs as well, if
6042   // any integer regs are available for argument passing.
6043   unsigned ArgOffset = LinkageSize;
6044 
6045   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6046   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6047 
6048   SmallVector<SDValue, 8> MemOpChains;
6049   for (unsigned i = 0; i != NumOps; ++i) {
6050     SDValue Arg = OutVals[i];
6051     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6052     EVT ArgVT = Outs[i].VT;
6053     EVT OrigVT = Outs[i].ArgVT;
6054 
6055     // PtrOff will be used to store the current argument to the stack if a
6056     // register cannot be found for it.
6057     SDValue PtrOff;
6058 
6059     // We re-align the argument offset for each argument, except when using the
6060     // fast calling convention, when we need to make sure we do that only when
6061     // we'll actually use a stack slot.
6062     auto ComputePtrOff = [&]() {
6063       /* Respect alignment of argument on the stack.  */
6064       unsigned Align =
6065         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6066       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
6067 
6068       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6069 
6070       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6071     };
6072 
6073     if (CallConv != CallingConv::Fast) {
6074       ComputePtrOff();
6075 
6076       /* Compute GPR index associated with argument offset.  */
6077       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6078       GPR_idx = std::min(GPR_idx, NumGPRs);
6079     }
6080 
6081     // Promote integers to 64-bit values.
6082     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6083       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6084       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6085       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6086     }
6087 
6088     // FIXME memcpy is used way more than necessary.  Correctness first.
6089     // Note: "by value" is code for passing a structure by value, not
6090     // basic types.
6091     if (Flags.isByVal()) {
6092       // Note: Size includes alignment padding, so
6093       //   struct x { short a; char b; }
6094       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6095       // These are the proper values we need for right-justifying the
6096       // aggregate in a parameter register.
6097       unsigned Size = Flags.getByValSize();
6098 
6099       // An empty aggregate parameter takes up no storage and no
6100       // registers.
6101       if (Size == 0)
6102         continue;
6103 
6104       if (CallConv == CallingConv::Fast)
6105         ComputePtrOff();
6106 
6107       // All aggregates smaller than 8 bytes must be passed right-justified.
6108       if (Size==1 || Size==2 || Size==4) {
6109         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6110         if (GPR_idx != NumGPRs) {
6111           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6112                                         MachinePointerInfo(), VT);
6113           MemOpChains.push_back(Load.getValue(1));
6114           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6115 
6116           ArgOffset += PtrByteSize;
6117           continue;
6118         }
6119       }
6120 
6121       if (GPR_idx == NumGPRs && Size < 8) {
6122         SDValue AddPtr = PtrOff;
6123         if (!isLittleEndian) {
6124           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6125                                           PtrOff.getValueType());
6126           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6127         }
6128         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6129                                                           CallSeqStart,
6130                                                           Flags, DAG, dl);
6131         ArgOffset += PtrByteSize;
6132         continue;
6133       }
6134       // Copy entire object into memory.  There are cases where gcc-generated
6135       // code assumes it is there, even if it could be put entirely into
6136       // registers.  (This is not what the doc says.)
6137 
6138       // FIXME: The above statement is likely due to a misunderstanding of the
6139       // documents.  All arguments must be copied into the parameter area BY
6140       // THE CALLEE in the event that the callee takes the address of any
6141       // formal argument.  That has not yet been implemented.  However, it is
6142       // reasonable to use the stack area as a staging area for the register
6143       // load.
6144 
6145       // Skip this for small aggregates, as we will use the same slot for a
6146       // right-justified copy, below.
6147       if (Size >= 8)
6148         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6149                                                           CallSeqStart,
6150                                                           Flags, DAG, dl);
6151 
6152       // When a register is available, pass a small aggregate right-justified.
6153       if (Size < 8 && GPR_idx != NumGPRs) {
6154         // The easiest way to get this right-justified in a register
6155         // is to copy the structure into the rightmost portion of a
6156         // local variable slot, then load the whole slot into the
6157         // register.
6158         // FIXME: The memcpy seems to produce pretty awful code for
6159         // small aggregates, particularly for packed ones.
6160         // FIXME: It would be preferable to use the slot in the
6161         // parameter save area instead of a new local variable.
6162         SDValue AddPtr = PtrOff;
6163         if (!isLittleEndian) {
6164           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6165           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6166         }
6167         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6168                                                           CallSeqStart,
6169                                                           Flags, DAG, dl);
6170 
6171         // Load the slot into the register.
6172         SDValue Load =
6173             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6174         MemOpChains.push_back(Load.getValue(1));
6175         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6176 
6177         // Done with this argument.
6178         ArgOffset += PtrByteSize;
6179         continue;
6180       }
6181 
6182       // For aggregates larger than PtrByteSize, copy the pieces of the
6183       // object that fit into registers from the parameter save area.
6184       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6185         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6186         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6187         if (GPR_idx != NumGPRs) {
6188           SDValue Load =
6189               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6190           MemOpChains.push_back(Load.getValue(1));
6191           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6192           ArgOffset += PtrByteSize;
6193         } else {
6194           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6195           break;
6196         }
6197       }
6198       continue;
6199     }
6200 
6201     switch (Arg.getSimpleValueType().SimpleTy) {
6202     default: llvm_unreachable("Unexpected ValueType for argument!");
6203     case MVT::i1:
6204     case MVT::i32:
6205     case MVT::i64:
6206       if (Flags.isNest()) {
6207         // The 'nest' parameter, if any, is passed in R11.
6208         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6209         hasNest = true;
6210         break;
6211       }
6212 
6213       // These can be scalar arguments or elements of an integer array type
6214       // passed directly.  Clang may use those instead of "byval" aggregate
6215       // types to avoid forcing arguments to memory unnecessarily.
6216       if (GPR_idx != NumGPRs) {
6217         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6218       } else {
6219         if (CallConv == CallingConv::Fast)
6220           ComputePtrOff();
6221 
6222         assert(HasParameterArea &&
6223                "Parameter area must exist to pass an argument in memory.");
6224         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6225                          true, isTailCall, false, MemOpChains,
6226                          TailCallArguments, dl);
6227         if (CallConv == CallingConv::Fast)
6228           ArgOffset += PtrByteSize;
6229       }
6230       if (CallConv != CallingConv::Fast)
6231         ArgOffset += PtrByteSize;
6232       break;
6233     case MVT::f32:
6234     case MVT::f64: {
6235       // These can be scalar arguments or elements of a float array type
6236       // passed directly.  The latter are used to implement ELFv2 homogenous
6237       // float aggregates.
6238 
6239       // Named arguments go into FPRs first, and once they overflow, the
6240       // remaining arguments go into GPRs and then the parameter save area.
6241       // Unnamed arguments for vararg functions always go to GPRs and
6242       // then the parameter save area.  For now, put all arguments to vararg
6243       // routines always in both locations (FPR *and* GPR or stack slot).
6244       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6245       bool NeededLoad = false;
6246 
6247       // First load the argument into the next available FPR.
6248       if (FPR_idx != NumFPRs)
6249         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6250 
6251       // Next, load the argument into GPR or stack slot if needed.
6252       if (!NeedGPROrStack)
6253         ;
6254       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6255         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6256         // once we support fp <-> gpr moves.
6257 
6258         // In the non-vararg case, this can only ever happen in the
6259         // presence of f32 array types, since otherwise we never run
6260         // out of FPRs before running out of GPRs.
6261         SDValue ArgVal;
6262 
6263         // Double values are always passed in a single GPR.
6264         if (Arg.getValueType() != MVT::f32) {
6265           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6266 
6267         // Non-array float values are extended and passed in a GPR.
6268         } else if (!Flags.isInConsecutiveRegs()) {
6269           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6270           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6271 
6272         // If we have an array of floats, we collect every odd element
6273         // together with its predecessor into one GPR.
6274         } else if (ArgOffset % PtrByteSize != 0) {
6275           SDValue Lo, Hi;
6276           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6277           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6278           if (!isLittleEndian)
6279             std::swap(Lo, Hi);
6280           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6281 
6282         // The final element, if even, goes into the first half of a GPR.
6283         } else if (Flags.isInConsecutiveRegsLast()) {
6284           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6285           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6286           if (!isLittleEndian)
6287             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6288                                  DAG.getConstant(32, dl, MVT::i32));
6289 
6290         // Non-final even elements are skipped; they will be handled
6291         // together the with subsequent argument on the next go-around.
6292         } else
6293           ArgVal = SDValue();
6294 
6295         if (ArgVal.getNode())
6296           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6297       } else {
6298         if (CallConv == CallingConv::Fast)
6299           ComputePtrOff();
6300 
6301         // Single-precision floating-point values are mapped to the
6302         // second (rightmost) word of the stack doubleword.
6303         if (Arg.getValueType() == MVT::f32 &&
6304             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6305           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6306           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6307         }
6308 
6309         assert(HasParameterArea &&
6310                "Parameter area must exist to pass an argument in memory.");
6311         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6312                          true, isTailCall, false, MemOpChains,
6313                          TailCallArguments, dl);
6314 
6315         NeededLoad = true;
6316       }
6317       // When passing an array of floats, the array occupies consecutive
6318       // space in the argument area; only round up to the next doubleword
6319       // at the end of the array.  Otherwise, each float takes 8 bytes.
6320       if (CallConv != CallingConv::Fast || NeededLoad) {
6321         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6322                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6323         if (Flags.isInConsecutiveRegsLast())
6324           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6325       }
6326       break;
6327     }
6328     case MVT::v4f32:
6329     case MVT::v4i32:
6330     case MVT::v8i16:
6331     case MVT::v16i8:
6332     case MVT::v2f64:
6333     case MVT::v2i64:
6334     case MVT::v1i128:
6335     case MVT::f128:
6336       if (!Subtarget.hasQPX()) {
6337       // These can be scalar arguments or elements of a vector array type
6338       // passed directly.  The latter are used to implement ELFv2 homogenous
6339       // vector aggregates.
6340 
6341       // For a varargs call, named arguments go into VRs or on the stack as
6342       // usual; unnamed arguments always go to the stack or the corresponding
6343       // GPRs when within range.  For now, we always put the value in both
6344       // locations (or even all three).
6345       if (isVarArg) {
6346         assert(HasParameterArea &&
6347                "Parameter area must exist if we have a varargs call.");
6348         // We could elide this store in the case where the object fits
6349         // entirely in R registers.  Maybe later.
6350         SDValue Store =
6351             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6352         MemOpChains.push_back(Store);
6353         if (VR_idx != NumVRs) {
6354           SDValue Load =
6355               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6356           MemOpChains.push_back(Load.getValue(1));
6357           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6358         }
6359         ArgOffset += 16;
6360         for (unsigned i=0; i<16; i+=PtrByteSize) {
6361           if (GPR_idx == NumGPRs)
6362             break;
6363           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6364                                    DAG.getConstant(i, dl, PtrVT));
6365           SDValue Load =
6366               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6367           MemOpChains.push_back(Load.getValue(1));
6368           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6369         }
6370         break;
6371       }
6372 
6373       // Non-varargs Altivec params go into VRs or on the stack.
6374       if (VR_idx != NumVRs) {
6375         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6376       } else {
6377         if (CallConv == CallingConv::Fast)
6378           ComputePtrOff();
6379 
6380         assert(HasParameterArea &&
6381                "Parameter area must exist to pass an argument in memory.");
6382         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6383                          true, isTailCall, true, MemOpChains,
6384                          TailCallArguments, dl);
6385         if (CallConv == CallingConv::Fast)
6386           ArgOffset += 16;
6387       }
6388 
6389       if (CallConv != CallingConv::Fast)
6390         ArgOffset += 16;
6391       break;
6392       } // not QPX
6393 
6394       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6395              "Invalid QPX parameter type");
6396 
6397       LLVM_FALLTHROUGH;
6398     case MVT::v4f64:
6399     case MVT::v4i1: {
6400       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6401       if (isVarArg) {
6402         assert(HasParameterArea &&
6403                "Parameter area must exist if we have a varargs call.");
6404         // We could elide this store in the case where the object fits
6405         // entirely in R registers.  Maybe later.
6406         SDValue Store =
6407             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6408         MemOpChains.push_back(Store);
6409         if (QFPR_idx != NumQFPRs) {
6410           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6411                                      PtrOff, MachinePointerInfo());
6412           MemOpChains.push_back(Load.getValue(1));
6413           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6414         }
6415         ArgOffset += (IsF32 ? 16 : 32);
6416         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6417           if (GPR_idx == NumGPRs)
6418             break;
6419           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6420                                    DAG.getConstant(i, dl, PtrVT));
6421           SDValue Load =
6422               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6423           MemOpChains.push_back(Load.getValue(1));
6424           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6425         }
6426         break;
6427       }
6428 
6429       // Non-varargs QPX params go into registers or on the stack.
6430       if (QFPR_idx != NumQFPRs) {
6431         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6432       } else {
6433         if (CallConv == CallingConv::Fast)
6434           ComputePtrOff();
6435 
6436         assert(HasParameterArea &&
6437                "Parameter area must exist to pass an argument in memory.");
6438         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6439                          true, isTailCall, true, MemOpChains,
6440                          TailCallArguments, dl);
6441         if (CallConv == CallingConv::Fast)
6442           ArgOffset += (IsF32 ? 16 : 32);
6443       }
6444 
6445       if (CallConv != CallingConv::Fast)
6446         ArgOffset += (IsF32 ? 16 : 32);
6447       break;
6448       }
6449     }
6450   }
6451 
6452   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6453          "mismatch in size of parameter area");
6454   (void)NumBytesActuallyUsed;
6455 
6456   if (!MemOpChains.empty())
6457     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6458 
6459   // Check if this is an indirect call (MTCTR/BCTRL).
6460   // See prepareDescriptorIndirectCall and buildCallOperands for more
6461   // information about calls through function pointers in the 64-bit SVR4 ABI.
6462   if (!isTailCall && !isPatchPoint &&
6463       !isFunctionGlobalAddress(Callee) &&
6464       !isa<ExternalSymbolSDNode>(Callee)) {
6465     // Load r2 into a virtual register and store it to the TOC save area.
6466     setUsesTOCBasePtr(DAG);
6467     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6468     // TOC save area offset.
6469     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6470     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6471     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6472     Chain = DAG.getStore(
6473         Val.getValue(1), dl, Val, AddPtr,
6474         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6475     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6476     // This does not mean the MTCTR instruction must use R12; it's easier
6477     // to model this as an extra parameter, so do that.
6478     if (isELFv2ABI && !isPatchPoint)
6479       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6480   }
6481 
6482   // Build a sequence of copy-to-reg nodes chained together with token chain
6483   // and flag operands which copy the outgoing args into the appropriate regs.
6484   SDValue InFlag;
6485   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6486     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6487                              RegsToPass[i].second, InFlag);
6488     InFlag = Chain.getValue(1);
6489   }
6490 
6491   if (isTailCall && !IsSibCall)
6492     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6493                     TailCallArguments);
6494 
6495   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6496                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6497                     SPDiff, NumBytes, Ins, InVals, CS);
6498 }
6499 
6500 SDValue PPCTargetLowering::LowerCall_Darwin(
6501     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6502     bool isTailCall, bool isPatchPoint,
6503     const SmallVectorImpl<ISD::OutputArg> &Outs,
6504     const SmallVectorImpl<SDValue> &OutVals,
6505     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6506     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6507     ImmutableCallSite CS) const {
6508   unsigned NumOps = Outs.size();
6509 
6510   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6511   bool isPPC64 = PtrVT == MVT::i64;
6512   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6513 
6514   MachineFunction &MF = DAG.getMachineFunction();
6515 
6516   // Mark this function as potentially containing a function that contains a
6517   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6518   // and restoring the callers stack pointer in this functions epilog. This is
6519   // done because by tail calling the called function might overwrite the value
6520   // in this function's (MF) stack pointer stack slot 0(SP).
6521   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6522       CallConv == CallingConv::Fast)
6523     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6524 
6525   // Count how many bytes are to be pushed on the stack, including the linkage
6526   // area, and parameter passing area.  We start with 24/48 bytes, which is
6527   // prereserved space for [SP][CR][LR][3 x unused].
6528   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6529   unsigned NumBytes = LinkageSize;
6530 
6531   // Add up all the space actually used.
6532   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6533   // they all go in registers, but we must reserve stack space for them for
6534   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6535   // assigned stack space in order, with padding so Altivec parameters are
6536   // 16-byte aligned.
6537   unsigned nAltivecParamsAtEnd = 0;
6538   for (unsigned i = 0; i != NumOps; ++i) {
6539     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6540     EVT ArgVT = Outs[i].VT;
6541     // Varargs Altivec parameters are padded to a 16 byte boundary.
6542     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6543         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6544         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6545       if (!isVarArg && !isPPC64) {
6546         // Non-varargs Altivec parameters go after all the non-Altivec
6547         // parameters; handle those later so we know how much padding we need.
6548         nAltivecParamsAtEnd++;
6549         continue;
6550       }
6551       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6552       NumBytes = ((NumBytes+15)/16)*16;
6553     }
6554     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6555   }
6556 
6557   // Allow for Altivec parameters at the end, if needed.
6558   if (nAltivecParamsAtEnd) {
6559     NumBytes = ((NumBytes+15)/16)*16;
6560     NumBytes += 16*nAltivecParamsAtEnd;
6561   }
6562 
6563   // The prolog code of the callee may store up to 8 GPR argument registers to
6564   // the stack, allowing va_start to index over them in memory if its varargs.
6565   // Because we cannot tell if this is needed on the caller side, we have to
6566   // conservatively assume that it is needed.  As such, make sure we have at
6567   // least enough stack space for the caller to store the 8 GPRs.
6568   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6569 
6570   // Tail call needs the stack to be aligned.
6571   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6572       CallConv == CallingConv::Fast)
6573     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6574 
6575   // Calculate by how many bytes the stack has to be adjusted in case of tail
6576   // call optimization.
6577   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6578 
6579   // To protect arguments on the stack from being clobbered in a tail call,
6580   // force all the loads to happen before doing any other lowering.
6581   if (isTailCall)
6582     Chain = DAG.getStackArgumentTokenFactor(Chain);
6583 
6584   // Adjust the stack pointer for the new arguments...
6585   // These operations are automatically eliminated by the prolog/epilog pass
6586   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6587   SDValue CallSeqStart = Chain;
6588 
6589   // Load the return address and frame pointer so it can be move somewhere else
6590   // later.
6591   SDValue LROp, FPOp;
6592   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6593 
6594   // Set up a copy of the stack pointer for use loading and storing any
6595   // arguments that may not fit in the registers available for argument
6596   // passing.
6597   SDValue StackPtr;
6598   if (isPPC64)
6599     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6600   else
6601     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6602 
6603   // Figure out which arguments are going to go in registers, and which in
6604   // memory.  Also, if this is a vararg function, floating point operations
6605   // must be stored to our stack, and loaded into integer regs as well, if
6606   // any integer regs are available for argument passing.
6607   unsigned ArgOffset = LinkageSize;
6608   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6609 
6610   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6611     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6612     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6613   };
6614   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6615     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6616     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6617   };
6618   static const MCPhysReg VR[] = {
6619     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6620     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6621   };
6622   const unsigned NumGPRs = array_lengthof(GPR_32);
6623   const unsigned NumFPRs = 13;
6624   const unsigned NumVRs  = array_lengthof(VR);
6625 
6626   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6627 
6628   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6629   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6630 
6631   SmallVector<SDValue, 8> MemOpChains;
6632   for (unsigned i = 0; i != NumOps; ++i) {
6633     SDValue Arg = OutVals[i];
6634     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6635 
6636     // PtrOff will be used to store the current argument to the stack if a
6637     // register cannot be found for it.
6638     SDValue PtrOff;
6639 
6640     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6641 
6642     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6643 
6644     // On PPC64, promote integers to 64-bit values.
6645     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6646       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6647       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6648       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6649     }
6650 
6651     // FIXME memcpy is used way more than necessary.  Correctness first.
6652     // Note: "by value" is code for passing a structure by value, not
6653     // basic types.
6654     if (Flags.isByVal()) {
6655       unsigned Size = Flags.getByValSize();
6656       // Very small objects are passed right-justified.  Everything else is
6657       // passed left-justified.
6658       if (Size==1 || Size==2) {
6659         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6660         if (GPR_idx != NumGPRs) {
6661           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6662                                         MachinePointerInfo(), VT);
6663           MemOpChains.push_back(Load.getValue(1));
6664           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6665 
6666           ArgOffset += PtrByteSize;
6667         } else {
6668           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6669                                           PtrOff.getValueType());
6670           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6671           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6672                                                             CallSeqStart,
6673                                                             Flags, DAG, dl);
6674           ArgOffset += PtrByteSize;
6675         }
6676         continue;
6677       }
6678       // Copy entire object into memory.  There are cases where gcc-generated
6679       // code assumes it is there, even if it could be put entirely into
6680       // registers.  (This is not what the doc says.)
6681       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6682                                                         CallSeqStart,
6683                                                         Flags, DAG, dl);
6684 
6685       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6686       // copy the pieces of the object that fit into registers from the
6687       // parameter save area.
6688       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6689         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6690         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6691         if (GPR_idx != NumGPRs) {
6692           SDValue Load =
6693               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6694           MemOpChains.push_back(Load.getValue(1));
6695           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6696           ArgOffset += PtrByteSize;
6697         } else {
6698           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6699           break;
6700         }
6701       }
6702       continue;
6703     }
6704 
6705     switch (Arg.getSimpleValueType().SimpleTy) {
6706     default: llvm_unreachable("Unexpected ValueType for argument!");
6707     case MVT::i1:
6708     case MVT::i32:
6709     case MVT::i64:
6710       if (GPR_idx != NumGPRs) {
6711         if (Arg.getValueType() == MVT::i1)
6712           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6713 
6714         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6715       } else {
6716         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6717                          isPPC64, isTailCall, false, MemOpChains,
6718                          TailCallArguments, dl);
6719       }
6720       ArgOffset += PtrByteSize;
6721       break;
6722     case MVT::f32:
6723     case MVT::f64:
6724       if (FPR_idx != NumFPRs) {
6725         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6726 
6727         if (isVarArg) {
6728           SDValue Store =
6729               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6730           MemOpChains.push_back(Store);
6731 
6732           // Float varargs are always shadowed in available integer registers
6733           if (GPR_idx != NumGPRs) {
6734             SDValue Load =
6735                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6736             MemOpChains.push_back(Load.getValue(1));
6737             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6738           }
6739           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6740             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6741             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6742             SDValue Load =
6743                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6744             MemOpChains.push_back(Load.getValue(1));
6745             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6746           }
6747         } else {
6748           // If we have any FPRs remaining, we may also have GPRs remaining.
6749           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6750           // GPRs.
6751           if (GPR_idx != NumGPRs)
6752             ++GPR_idx;
6753           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6754               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6755             ++GPR_idx;
6756         }
6757       } else
6758         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6759                          isPPC64, isTailCall, false, MemOpChains,
6760                          TailCallArguments, dl);
6761       if (isPPC64)
6762         ArgOffset += 8;
6763       else
6764         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6765       break;
6766     case MVT::v4f32:
6767     case MVT::v4i32:
6768     case MVT::v8i16:
6769     case MVT::v16i8:
6770       if (isVarArg) {
6771         // These go aligned on the stack, or in the corresponding R registers
6772         // when within range.  The Darwin PPC ABI doc claims they also go in
6773         // V registers; in fact gcc does this only for arguments that are
6774         // prototyped, not for those that match the ...  We do it for all
6775         // arguments, seems to work.
6776         while (ArgOffset % 16 !=0) {
6777           ArgOffset += PtrByteSize;
6778           if (GPR_idx != NumGPRs)
6779             GPR_idx++;
6780         }
6781         // We could elide this store in the case where the object fits
6782         // entirely in R registers.  Maybe later.
6783         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6784                              DAG.getConstant(ArgOffset, dl, PtrVT));
6785         SDValue Store =
6786             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6787         MemOpChains.push_back(Store);
6788         if (VR_idx != NumVRs) {
6789           SDValue Load =
6790               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6791           MemOpChains.push_back(Load.getValue(1));
6792           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6793         }
6794         ArgOffset += 16;
6795         for (unsigned i=0; i<16; i+=PtrByteSize) {
6796           if (GPR_idx == NumGPRs)
6797             break;
6798           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6799                                    DAG.getConstant(i, dl, PtrVT));
6800           SDValue Load =
6801               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6802           MemOpChains.push_back(Load.getValue(1));
6803           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6804         }
6805         break;
6806       }
6807 
6808       // Non-varargs Altivec params generally go in registers, but have
6809       // stack space allocated at the end.
6810       if (VR_idx != NumVRs) {
6811         // Doesn't have GPR space allocated.
6812         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6813       } else if (nAltivecParamsAtEnd==0) {
6814         // We are emitting Altivec params in order.
6815         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6816                          isPPC64, isTailCall, true, MemOpChains,
6817                          TailCallArguments, dl);
6818         ArgOffset += 16;
6819       }
6820       break;
6821     }
6822   }
6823   // If all Altivec parameters fit in registers, as they usually do,
6824   // they get stack space following the non-Altivec parameters.  We
6825   // don't track this here because nobody below needs it.
6826   // If there are more Altivec parameters than fit in registers emit
6827   // the stores here.
6828   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6829     unsigned j = 0;
6830     // Offset is aligned; skip 1st 12 params which go in V registers.
6831     ArgOffset = ((ArgOffset+15)/16)*16;
6832     ArgOffset += 12*16;
6833     for (unsigned i = 0; i != NumOps; ++i) {
6834       SDValue Arg = OutVals[i];
6835       EVT ArgType = Outs[i].VT;
6836       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6837           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6838         if (++j > NumVRs) {
6839           SDValue PtrOff;
6840           // We are emitting Altivec params in order.
6841           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6842                            isPPC64, isTailCall, true, MemOpChains,
6843                            TailCallArguments, dl);
6844           ArgOffset += 16;
6845         }
6846       }
6847     }
6848   }
6849 
6850   if (!MemOpChains.empty())
6851     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6852 
6853   // On Darwin, R12 must contain the address of an indirect callee.  This does
6854   // not mean the MTCTR instruction must use R12; it's easier to model this as
6855   // an extra parameter, so do that.
6856   if (!isTailCall &&
6857       !isFunctionGlobalAddress(Callee) &&
6858       !isa<ExternalSymbolSDNode>(Callee) &&
6859       !isBLACompatibleAddress(Callee, DAG))
6860     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6861                                                    PPC::R12), Callee));
6862 
6863   // Build a sequence of copy-to-reg nodes chained together with token chain
6864   // and flag operands which copy the outgoing args into the appropriate regs.
6865   SDValue InFlag;
6866   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6867     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6868                              RegsToPass[i].second, InFlag);
6869     InFlag = Chain.getValue(1);
6870   }
6871 
6872   if (isTailCall)
6873     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6874                     TailCallArguments);
6875 
6876   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6877                     /* unused except on PPC64 ELFv1 */ false, DAG,
6878                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6879                     NumBytes, Ins, InVals, CS);
6880 }
6881 
6882 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6883                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6884                    CCState &State) {
6885 
6886   if (ValVT == MVT::f128)
6887     report_fatal_error("f128 is unimplemented on AIX.");
6888 
6889   if (ArgFlags.isByVal())
6890     report_fatal_error("Passing structure by value is unimplemented.");
6891 
6892   if (ArgFlags.isNest())
6893     report_fatal_error("Nest arguments are unimplemented.");
6894 
6895   if (ValVT.isVector() || LocVT.isVector())
6896     report_fatal_error("Vector arguments are unimplemented on AIX.");
6897 
6898   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6899       State.getMachineFunction().getSubtarget());
6900   const bool IsPPC64 = Subtarget.isPPC64();
6901   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6902 
6903   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6904                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6905                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6906   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6907                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6908                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6909 
6910   // Arguments always reserve parameter save area.
6911   switch (ValVT.SimpleTy) {
6912   default:
6913     report_fatal_error("Unhandled value type for argument.");
6914   case MVT::i64:
6915     // i64 arguments should have been split to i32 for PPC32.
6916     assert(IsPPC64 && "PPC32 should have split i64 values.");
6917     LLVM_FALLTHROUGH;
6918   case MVT::i1:
6919   case MVT::i32:
6920     State.AllocateStack(PtrByteSize, PtrByteSize);
6921     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6922       MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6923       // Promote integers if needed.
6924       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6925         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6926                                     : CCValAssign::LocInfo::ZExt;
6927       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6928     }
6929     else
6930       report_fatal_error("Handling of placing parameters on the stack is "
6931                          "unimplemented!");
6932     return false;
6933 
6934   case MVT::f32:
6935   case MVT::f64: {
6936     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6937     const unsigned StoreSize = LocVT.getStoreSize();
6938     // Floats are always 4-byte aligned in the PSA on AIX.
6939     // This includes f64 in 64-bit mode for ABI compatibility.
6940     State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6941     if (unsigned Reg = State.AllocateReg(FPR))
6942       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6943     else
6944       report_fatal_error("Handling of placing parameters on the stack is "
6945                          "unimplemented!");
6946 
6947     // AIX requires that GPRs are reserved for float arguments.
6948     // Successfully reserved GPRs are only initialized for vararg calls.
6949     MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6950     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6951       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6952         if (State.isVarArg()) {
6953           // Custom handling is required for:
6954           //   f64 in PPC32 needs to be split into 2 GPRs.
6955           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6956           State.addLoc(
6957               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6958         }
6959       } else if (State.isVarArg()) {
6960         report_fatal_error("Handling of placing parameters on the stack is "
6961                            "unimplemented!");
6962       }
6963     }
6964 
6965     return false;
6966   }
6967   }
6968   return true;
6969 }
6970 
6971 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6972                                                     bool IsPPC64) {
6973   assert((IsPPC64 || SVT != MVT::i64) &&
6974          "i64 should have been split for 32-bit codegen.");
6975 
6976   switch (SVT) {
6977   default:
6978     report_fatal_error("Unexpected value type for formal argument");
6979   case MVT::i1:
6980   case MVT::i32:
6981   case MVT::i64:
6982     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6983   case MVT::f32:
6984     return &PPC::F4RCRegClass;
6985   case MVT::f64:
6986     return &PPC::F8RCRegClass;
6987   }
6988 }
6989 
6990 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6991                                         SelectionDAG &DAG, SDValue ArgValue,
6992                                         MVT LocVT, const SDLoc &dl) {
6993   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6994   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6995 
6996   if (Flags.isSExt())
6997     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6998                            DAG.getValueType(ValVT));
6999   else if (Flags.isZExt())
7000     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7001                            DAG.getValueType(ValVT));
7002 
7003   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7004 }
7005 
7006 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7007     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7008     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7009     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7010 
7011   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7012           CallConv == CallingConv::Fast) &&
7013          "Unexpected calling convention!");
7014 
7015   if (isVarArg)
7016     report_fatal_error("This call type is unimplemented on AIX.");
7017 
7018   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7019     report_fatal_error("Tail call support is unimplemented on AIX.");
7020 
7021   if (useSoftFloat())
7022     report_fatal_error("Soft float support is unimplemented on AIX.");
7023 
7024   const PPCSubtarget &Subtarget =
7025       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7026   if (Subtarget.hasQPX())
7027     report_fatal_error("QPX support is not supported on AIX.");
7028 
7029   const bool IsPPC64 = Subtarget.isPPC64();
7030   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7031 
7032   // Assign locations to all of the incoming arguments.
7033   SmallVector<CCValAssign, 16> ArgLocs;
7034   MachineFunction &MF = DAG.getMachineFunction();
7035   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7036 
7037   // Reserve space for the linkage area on the stack.
7038   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7039   // On AIX a minimum of 8 words is saved to the parameter save area.
7040   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7041   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
7042   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7043 
7044   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
7045     CCValAssign &VA = ArgLocs[i];
7046     SDValue ArgValue;
7047     ISD::ArgFlagsTy Flags = Ins[i].Flags;
7048     if (VA.isRegLoc()) {
7049       EVT ValVT = VA.getValVT();
7050       MVT LocVT = VA.getLocVT();
7051       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7052       unsigned VReg =
7053           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7054       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7055       if (ValVT.isScalarInteger() &&
7056           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7057         ArgValue =
7058             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7059       }
7060       InVals.push_back(ArgValue);
7061     } else {
7062       report_fatal_error("Handling of formal arguments on the stack is "
7063                          "unimplemented!");
7064     }
7065   }
7066 
7067   // Area that is at least reserved in the caller of this function.
7068   unsigned MinReservedArea = CCInfo.getNextStackOffset();
7069 
7070   // Set the size that is at least reserved in caller of this function. Tail
7071   // call optimized function's reserved stack space needs to be aligned so
7072   // that taking the difference between two stack areas will result in an
7073   // aligned stack.
7074   MinReservedArea =
7075       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
7076   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7077   FuncInfo->setMinReservedArea(MinReservedArea);
7078 
7079   return Chain;
7080 }
7081 
7082 SDValue PPCTargetLowering::LowerCall_AIX(
7083     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
7084     bool isTailCall, bool isPatchPoint,
7085     const SmallVectorImpl<ISD::OutputArg> &Outs,
7086     const SmallVectorImpl<SDValue> &OutVals,
7087     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7088     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7089     ImmutableCallSite CS) const {
7090 
7091   assert((CallConv == CallingConv::C ||
7092           CallConv == CallingConv::Cold ||
7093           CallConv == CallingConv::Fast) && "Unexpected calling convention!");
7094 
7095   if (isPatchPoint)
7096     report_fatal_error("This call type is unimplemented on AIX.");
7097 
7098   const PPCSubtarget& Subtarget =
7099       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7100   if (Subtarget.hasQPX())
7101     report_fatal_error("QPX is not supported on AIX.");
7102   if (Subtarget.hasAltivec())
7103     report_fatal_error("Altivec support is unimplemented on AIX.");
7104 
7105   MachineFunction &MF = DAG.getMachineFunction();
7106   SmallVector<CCValAssign, 16> ArgLocs;
7107   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7108 
7109   // Reserve space for the linkage save area (LSA) on the stack.
7110   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7111   //   [SP][CR][LR][2 x reserved][TOC].
7112   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7113   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7114   const bool IsPPC64 = Subtarget.isPPC64();
7115   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7116   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7117   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7118 
7119   // The prolog code of the callee may store up to 8 GPR argument registers to
7120   // the stack, allowing va_start to index over them in memory if the callee
7121   // is variadic.
7122   // Because we cannot tell if this is needed on the caller side, we have to
7123   // conservatively assume that it is needed.  As such, make sure we have at
7124   // least enough stack space for the caller to store the 8 GPRs.
7125   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7126   const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize;
7127 
7128   // Adjust the stack pointer for the new arguments...
7129   // These operations are automatically eliminated by the prolog/epilog pass.
7130   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7131   SDValue CallSeqStart = Chain;
7132 
7133   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7134 
7135   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7136     CCValAssign &VA = ArgLocs[I++];
7137 
7138     if (VA.isMemLoc())
7139       report_fatal_error("Handling of placing parameters on the stack is "
7140                          "unimplemented!");
7141     if (!VA.isRegLoc())
7142       report_fatal_error(
7143           "Unexpected non-register location for function call argument.");
7144 
7145     SDValue Arg = OutVals[VA.getValNo()];
7146 
7147     if (!VA.needsCustom()) {
7148       switch (VA.getLocInfo()) {
7149       default:
7150         report_fatal_error("Unexpected argument extension type.");
7151       case CCValAssign::Full:
7152         break;
7153       case CCValAssign::ZExt:
7154         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7155         break;
7156       case CCValAssign::SExt:
7157         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7158         break;
7159       }
7160       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7161 
7162       continue;
7163     }
7164 
7165     // Custom handling is used for GPR initializations for vararg float
7166     // arguments.
7167     assert(isVarArg && VA.getValVT().isFloatingPoint() &&
7168            VA.getLocVT().isInteger() &&
7169            "Unexpected custom register handling for calling convention.");
7170 
7171     SDValue ArgAsInt =
7172         DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg);
7173 
7174     if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize())
7175       // f32 in 32-bit GPR
7176       // f64 in 64-bit GPR
7177       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7178     else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits())
7179       // f32 in 64-bit GPR.
7180       RegsToPass.push_back(std::make_pair(
7181           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT())));
7182     else {
7183       // f64 in two 32-bit GPRs
7184       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7185       assert(Arg.getValueType() == MVT::f64 && isVarArg && !IsPPC64 &&
7186              "Unexpected custom register for argument!");
7187       CCValAssign &GPR1 = VA;
7188       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7189                                      DAG.getConstant(32, dl, MVT::i8));
7190       RegsToPass.push_back(std::make_pair(
7191           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7192       assert(I != E && "A second custom GPR is expected!");
7193       CCValAssign &GPR2 = ArgLocs[I++];
7194       assert(GPR2.isRegLoc() && GPR2.getValNo() == GPR1.getValNo() &&
7195              GPR2.needsCustom() && "A second custom GPR is expected!");
7196       RegsToPass.push_back(std::make_pair(
7197           GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7198     }
7199   }
7200 
7201   // For indirect calls, we need to save the TOC base to the stack for
7202   // restoration after the call.
7203   if (!isTailCall && !isPatchPoint &&
7204       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) {
7205     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7206     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7207     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7208     const unsigned TOCSaveOffset =
7209         Subtarget.getFrameLowering()->getTOCSaveOffset();
7210 
7211     setUsesTOCBasePtr(DAG);
7212     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7213     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7214     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7215     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7216     Chain = DAG.getStore(
7217         Val.getValue(1), dl, Val, AddPtr,
7218         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7219   }
7220 
7221   // Build a sequence of copy-to-reg nodes chained together with token chain
7222   // and flag operands which copy the outgoing args into the appropriate regs.
7223   SDValue InFlag;
7224   for (auto Reg : RegsToPass) {
7225     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7226     InFlag = Chain.getValue(1);
7227   }
7228 
7229   const int SPDiff = 0;
7230   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
7231                     /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass,
7232                     InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins,
7233                     InVals, CS);
7234 }
7235 
7236 bool
7237 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7238                                   MachineFunction &MF, bool isVarArg,
7239                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7240                                   LLVMContext &Context) const {
7241   SmallVector<CCValAssign, 16> RVLocs;
7242   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7243   return CCInfo.CheckReturn(
7244       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7245                 ? RetCC_PPC_Cold
7246                 : RetCC_PPC);
7247 }
7248 
7249 SDValue
7250 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7251                                bool isVarArg,
7252                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7253                                const SmallVectorImpl<SDValue> &OutVals,
7254                                const SDLoc &dl, SelectionDAG &DAG) const {
7255   SmallVector<CCValAssign, 16> RVLocs;
7256   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7257                  *DAG.getContext());
7258   CCInfo.AnalyzeReturn(Outs,
7259                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7260                            ? RetCC_PPC_Cold
7261                            : RetCC_PPC);
7262 
7263   SDValue Flag;
7264   SmallVector<SDValue, 4> RetOps(1, Chain);
7265 
7266   // Copy the result values into the output registers.
7267   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7268     CCValAssign &VA = RVLocs[i];
7269     assert(VA.isRegLoc() && "Can only return in registers!");
7270 
7271     SDValue Arg = OutVals[RealResIdx];
7272 
7273     switch (VA.getLocInfo()) {
7274     default: llvm_unreachable("Unknown loc info!");
7275     case CCValAssign::Full: break;
7276     case CCValAssign::AExt:
7277       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7278       break;
7279     case CCValAssign::ZExt:
7280       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7281       break;
7282     case CCValAssign::SExt:
7283       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7284       break;
7285     }
7286     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7287       bool isLittleEndian = Subtarget.isLittleEndian();
7288       // Legalize ret f64 -> ret 2 x i32.
7289       SDValue SVal =
7290           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7291                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7292       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7293       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7294       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7295                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7296       Flag = Chain.getValue(1);
7297       VA = RVLocs[++i]; // skip ahead to next loc
7298       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7299     } else
7300       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7301     Flag = Chain.getValue(1);
7302     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7303   }
7304 
7305   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7306   const MCPhysReg *I =
7307     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7308   if (I) {
7309     for (; *I; ++I) {
7310 
7311       if (PPC::G8RCRegClass.contains(*I))
7312         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7313       else if (PPC::F8RCRegClass.contains(*I))
7314         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7315       else if (PPC::CRRCRegClass.contains(*I))
7316         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7317       else if (PPC::VRRCRegClass.contains(*I))
7318         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7319       else
7320         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7321     }
7322   }
7323 
7324   RetOps[0] = Chain;  // Update chain.
7325 
7326   // Add the flag if we have it.
7327   if (Flag.getNode())
7328     RetOps.push_back(Flag);
7329 
7330   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7331 }
7332 
7333 SDValue
7334 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7335                                                 SelectionDAG &DAG) const {
7336   SDLoc dl(Op);
7337 
7338   // Get the correct type for integers.
7339   EVT IntVT = Op.getValueType();
7340 
7341   // Get the inputs.
7342   SDValue Chain = Op.getOperand(0);
7343   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7344   // Build a DYNAREAOFFSET node.
7345   SDValue Ops[2] = {Chain, FPSIdx};
7346   SDVTList VTs = DAG.getVTList(IntVT);
7347   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7348 }
7349 
7350 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7351                                              SelectionDAG &DAG) const {
7352   // When we pop the dynamic allocation we need to restore the SP link.
7353   SDLoc dl(Op);
7354 
7355   // Get the correct type for pointers.
7356   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7357 
7358   // Construct the stack pointer operand.
7359   bool isPPC64 = Subtarget.isPPC64();
7360   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7361   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7362 
7363   // Get the operands for the STACKRESTORE.
7364   SDValue Chain = Op.getOperand(0);
7365   SDValue SaveSP = Op.getOperand(1);
7366 
7367   // Load the old link SP.
7368   SDValue LoadLinkSP =
7369       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7370 
7371   // Restore the stack pointer.
7372   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7373 
7374   // Store the old link SP.
7375   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7376 }
7377 
7378 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7379   MachineFunction &MF = DAG.getMachineFunction();
7380   bool isPPC64 = Subtarget.isPPC64();
7381   EVT PtrVT = getPointerTy(MF.getDataLayout());
7382 
7383   // Get current frame pointer save index.  The users of this index will be
7384   // primarily DYNALLOC instructions.
7385   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7386   int RASI = FI->getReturnAddrSaveIndex();
7387 
7388   // If the frame pointer save index hasn't been defined yet.
7389   if (!RASI) {
7390     // Find out what the fix offset of the frame pointer save area.
7391     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7392     // Allocate the frame index for frame pointer save area.
7393     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7394     // Save the result.
7395     FI->setReturnAddrSaveIndex(RASI);
7396   }
7397   return DAG.getFrameIndex(RASI, PtrVT);
7398 }
7399 
7400 SDValue
7401 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7402   MachineFunction &MF = DAG.getMachineFunction();
7403   bool isPPC64 = Subtarget.isPPC64();
7404   EVT PtrVT = getPointerTy(MF.getDataLayout());
7405 
7406   // Get current frame pointer save index.  The users of this index will be
7407   // primarily DYNALLOC instructions.
7408   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7409   int FPSI = FI->getFramePointerSaveIndex();
7410 
7411   // If the frame pointer save index hasn't been defined yet.
7412   if (!FPSI) {
7413     // Find out what the fix offset of the frame pointer save area.
7414     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7415     // Allocate the frame index for frame pointer save area.
7416     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7417     // Save the result.
7418     FI->setFramePointerSaveIndex(FPSI);
7419   }
7420   return DAG.getFrameIndex(FPSI, PtrVT);
7421 }
7422 
7423 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7424                                                    SelectionDAG &DAG) const {
7425   // Get the inputs.
7426   SDValue Chain = Op.getOperand(0);
7427   SDValue Size  = Op.getOperand(1);
7428   SDLoc dl(Op);
7429 
7430   // Get the correct type for pointers.
7431   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7432   // Negate the size.
7433   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7434                                 DAG.getConstant(0, dl, PtrVT), Size);
7435   // Construct a node for the frame pointer save index.
7436   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7437   // Build a DYNALLOC node.
7438   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7439   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7440   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7441 }
7442 
7443 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7444                                                      SelectionDAG &DAG) const {
7445   MachineFunction &MF = DAG.getMachineFunction();
7446 
7447   bool isPPC64 = Subtarget.isPPC64();
7448   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7449 
7450   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7451   return DAG.getFrameIndex(FI, PtrVT);
7452 }
7453 
7454 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7455                                                SelectionDAG &DAG) const {
7456   SDLoc DL(Op);
7457   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7458                      DAG.getVTList(MVT::i32, MVT::Other),
7459                      Op.getOperand(0), Op.getOperand(1));
7460 }
7461 
7462 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7463                                                 SelectionDAG &DAG) const {
7464   SDLoc DL(Op);
7465   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7466                      Op.getOperand(0), Op.getOperand(1));
7467 }
7468 
7469 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7470   if (Op.getValueType().isVector())
7471     return LowerVectorLoad(Op, DAG);
7472 
7473   assert(Op.getValueType() == MVT::i1 &&
7474          "Custom lowering only for i1 loads");
7475 
7476   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7477 
7478   SDLoc dl(Op);
7479   LoadSDNode *LD = cast<LoadSDNode>(Op);
7480 
7481   SDValue Chain = LD->getChain();
7482   SDValue BasePtr = LD->getBasePtr();
7483   MachineMemOperand *MMO = LD->getMemOperand();
7484 
7485   SDValue NewLD =
7486       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7487                      BasePtr, MVT::i8, MMO);
7488   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7489 
7490   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7491   return DAG.getMergeValues(Ops, dl);
7492 }
7493 
7494 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7495   if (Op.getOperand(1).getValueType().isVector())
7496     return LowerVectorStore(Op, DAG);
7497 
7498   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7499          "Custom lowering only for i1 stores");
7500 
7501   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7502 
7503   SDLoc dl(Op);
7504   StoreSDNode *ST = cast<StoreSDNode>(Op);
7505 
7506   SDValue Chain = ST->getChain();
7507   SDValue BasePtr = ST->getBasePtr();
7508   SDValue Value = ST->getValue();
7509   MachineMemOperand *MMO = ST->getMemOperand();
7510 
7511   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7512                       Value);
7513   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7514 }
7515 
7516 // FIXME: Remove this once the ANDI glue bug is fixed:
7517 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7518   assert(Op.getValueType() == MVT::i1 &&
7519          "Custom lowering only for i1 results");
7520 
7521   SDLoc DL(Op);
7522   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7523 }
7524 
7525 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7526                                                SelectionDAG &DAG) const {
7527 
7528   // Implements a vector truncate that fits in a vector register as a shuffle.
7529   // We want to legalize vector truncates down to where the source fits in
7530   // a vector register (and target is therefore smaller than vector register
7531   // size).  At that point legalization will try to custom lower the sub-legal
7532   // result and get here - where we can contain the truncate as a single target
7533   // operation.
7534 
7535   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7536   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7537   //
7538   // We will implement it for big-endian ordering as this (where x denotes
7539   // undefined):
7540   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7541   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7542   //
7543   // The same operation in little-endian ordering will be:
7544   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7545   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7546 
7547   assert(Op.getValueType().isVector() && "Vector type expected.");
7548 
7549   SDLoc DL(Op);
7550   SDValue N1 = Op.getOperand(0);
7551   unsigned SrcSize = N1.getValueType().getSizeInBits();
7552   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7553   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7554 
7555   EVT TrgVT = Op.getValueType();
7556   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7557   EVT EltVT = TrgVT.getVectorElementType();
7558   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7559   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7560 
7561   // First list the elements we want to keep.
7562   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7563   SmallVector<int, 16> ShuffV;
7564   if (Subtarget.isLittleEndian())
7565     for (unsigned i = 0; i < TrgNumElts; ++i)
7566       ShuffV.push_back(i * SizeMult);
7567   else
7568     for (unsigned i = 1; i <= TrgNumElts; ++i)
7569       ShuffV.push_back(i * SizeMult - 1);
7570 
7571   // Populate the remaining elements with undefs.
7572   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7573     // ShuffV.push_back(i + WideNumElts);
7574     ShuffV.push_back(WideNumElts + 1);
7575 
7576   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7577   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7578 }
7579 
7580 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7581 /// possible.
7582 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7583   // Not FP? Not a fsel.
7584   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7585       !Op.getOperand(2).getValueType().isFloatingPoint())
7586     return Op;
7587 
7588   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7589   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7590   // We might be able to do better than this under some circumstances, but in
7591   // general, fsel-based lowering of select is a finite-math-only optimization.
7592   // For more information, see section F.3 of the 2.06 ISA specification.
7593   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7594   // presence of infinities.
7595   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7596     return Op;
7597   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7598 
7599   EVT ResVT = Op.getValueType();
7600   EVT CmpVT = Op.getOperand(0).getValueType();
7601   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7602   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7603   SDLoc dl(Op);
7604 
7605   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7606     switch (CC) {
7607     default:
7608       // Not a min/max but with finite math, we may still be able to use fsel.
7609       if (HasNoInfs && HasNoNaNs)
7610         break;
7611       return Op;
7612     case ISD::SETOGT:
7613     case ISD::SETGT:
7614       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7615     case ISD::SETOLT:
7616     case ISD::SETLT:
7617       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7618     }
7619   }
7620 
7621   // TODO: Propagate flags from the select rather than global settings.
7622   SDNodeFlags Flags;
7623   Flags.setNoInfs(true);
7624   Flags.setNoNaNs(true);
7625 
7626   // If the RHS of the comparison is a 0.0, we don't need to do the
7627   // subtraction at all.
7628   SDValue Sel1;
7629   if (isFloatingPointZero(RHS))
7630     switch (CC) {
7631     default: break;       // SETUO etc aren't handled by fsel.
7632     case ISD::SETNE:
7633       std::swap(TV, FV);
7634       LLVM_FALLTHROUGH;
7635     case ISD::SETEQ:
7636       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7637         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7638       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7639       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7640         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7641       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7642                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7643     case ISD::SETULT:
7644     case ISD::SETLT:
7645       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7646       LLVM_FALLTHROUGH;
7647     case ISD::SETOGE:
7648     case ISD::SETGE:
7649       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7650         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7651       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7652     case ISD::SETUGT:
7653     case ISD::SETGT:
7654       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7655       LLVM_FALLTHROUGH;
7656     case ISD::SETOLE:
7657     case ISD::SETLE:
7658       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7659         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7660       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7661                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7662     }
7663 
7664   SDValue Cmp;
7665   switch (CC) {
7666   default: break;       // SETUO etc aren't handled by fsel.
7667   case ISD::SETNE:
7668     std::swap(TV, FV);
7669     LLVM_FALLTHROUGH;
7670   case ISD::SETEQ:
7671     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7672     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7673       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7674     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7675     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7676       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7677     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7678                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7679   case ISD::SETULT:
7680   case ISD::SETLT:
7681     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7682     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7683       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7684     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7685   case ISD::SETOGE:
7686   case ISD::SETGE:
7687     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7688     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7689       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7690     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7691   case ISD::SETUGT:
7692   case ISD::SETGT:
7693     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7694     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7695       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7696     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7697   case ISD::SETOLE:
7698   case ISD::SETLE:
7699     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7700     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7701       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7702     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7703   }
7704   return Op;
7705 }
7706 
7707 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7708                                                SelectionDAG &DAG,
7709                                                const SDLoc &dl) const {
7710   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7711   SDValue Src = Op.getOperand(0);
7712   if (Src.getValueType() == MVT::f32)
7713     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7714 
7715   SDValue Tmp;
7716   switch (Op.getSimpleValueType().SimpleTy) {
7717   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7718   case MVT::i32:
7719     Tmp = DAG.getNode(
7720         Op.getOpcode() == ISD::FP_TO_SINT
7721             ? PPCISD::FCTIWZ
7722             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7723         dl, MVT::f64, Src);
7724     break;
7725   case MVT::i64:
7726     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7727            "i64 FP_TO_UINT is supported only with FPCVT");
7728     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7729                                                         PPCISD::FCTIDUZ,
7730                       dl, MVT::f64, Src);
7731     break;
7732   }
7733 
7734   // Convert the FP value to an int value through memory.
7735   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7736     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7737   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7738   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7739   MachinePointerInfo MPI =
7740       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7741 
7742   // Emit a store to the stack slot.
7743   SDValue Chain;
7744   unsigned Alignment = DAG.getEVTAlignment(Tmp.getValueType());
7745   if (i32Stack) {
7746     MachineFunction &MF = DAG.getMachineFunction();
7747     Alignment = 4;
7748     MachineMemOperand *MMO =
7749       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7750     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7751     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7752               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7753   } else
7754     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
7755 
7756   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7757   // add in a bias on big endian.
7758   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7759     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7760                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7761     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7762   }
7763 
7764   RLI.Chain = Chain;
7765   RLI.Ptr = FIPtr;
7766   RLI.MPI = MPI;
7767   RLI.Alignment = Alignment;
7768 }
7769 
7770 /// Custom lowers floating point to integer conversions to use
7771 /// the direct move instructions available in ISA 2.07 to avoid the
7772 /// need for load/store combinations.
7773 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7774                                                     SelectionDAG &DAG,
7775                                                     const SDLoc &dl) const {
7776   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7777   SDValue Src = Op.getOperand(0);
7778 
7779   if (Src.getValueType() == MVT::f32)
7780     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7781 
7782   SDValue Tmp;
7783   switch (Op.getSimpleValueType().SimpleTy) {
7784   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7785   case MVT::i32:
7786     Tmp = DAG.getNode(
7787         Op.getOpcode() == ISD::FP_TO_SINT
7788             ? PPCISD::FCTIWZ
7789             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7790         dl, MVT::f64, Src);
7791     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7792     break;
7793   case MVT::i64:
7794     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7795            "i64 FP_TO_UINT is supported only with FPCVT");
7796     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7797                                                         PPCISD::FCTIDUZ,
7798                       dl, MVT::f64, Src);
7799     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7800     break;
7801   }
7802   return Tmp;
7803 }
7804 
7805 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7806                                           const SDLoc &dl) const {
7807 
7808   // FP to INT conversions are legal for f128.
7809   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7810     return Op;
7811 
7812   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7813   // PPC (the libcall is not available).
7814   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7815     if (Op.getValueType() == MVT::i32) {
7816       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7817         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7818                                  MVT::f64, Op.getOperand(0),
7819                                  DAG.getIntPtrConstant(0, dl));
7820         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7821                                  MVT::f64, Op.getOperand(0),
7822                                  DAG.getIntPtrConstant(1, dl));
7823 
7824         // Add the two halves of the long double in round-to-zero mode.
7825         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7826 
7827         // Now use a smaller FP_TO_SINT.
7828         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7829       }
7830       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7831         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7832         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7833         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7834         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7835         // FIXME: generated code sucks.
7836         // TODO: Are there fast-math-flags to propagate to this FSUB?
7837         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7838                                    Op.getOperand(0), Tmp);
7839         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7840         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7841                            DAG.getConstant(0x80000000, dl, MVT::i32));
7842         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7843                                     Op.getOperand(0));
7844         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7845                                ISD::SETGE);
7846       }
7847     }
7848 
7849     return SDValue();
7850   }
7851 
7852   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7853     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7854 
7855   ReuseLoadInfo RLI;
7856   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7857 
7858   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7859                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7860 }
7861 
7862 // We're trying to insert a regular store, S, and then a load, L. If the
7863 // incoming value, O, is a load, we might just be able to have our load use the
7864 // address used by O. However, we don't know if anything else will store to
7865 // that address before we can load from it. To prevent this situation, we need
7866 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7867 // the same chain operand as O, we create a token factor from the chain results
7868 // of O and L, and we replace all uses of O's chain result with that token
7869 // factor (see spliceIntoChain below for this last part).
7870 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7871                                             ReuseLoadInfo &RLI,
7872                                             SelectionDAG &DAG,
7873                                             ISD::LoadExtType ET) const {
7874   SDLoc dl(Op);
7875   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
7876                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
7877   if (ET == ISD::NON_EXTLOAD &&
7878       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
7879       isOperationLegalOrCustom(Op.getOpcode(),
7880                                Op.getOperand(0).getValueType())) {
7881 
7882     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7883     return true;
7884   }
7885 
7886   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7887   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7888       LD->isNonTemporal())
7889     return false;
7890   if (LD->getMemoryVT() != MemVT)
7891     return false;
7892 
7893   RLI.Ptr = LD->getBasePtr();
7894   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7895     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7896            "Non-pre-inc AM on PPC?");
7897     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7898                           LD->getOffset());
7899   }
7900 
7901   RLI.Chain = LD->getChain();
7902   RLI.MPI = LD->getPointerInfo();
7903   RLI.IsDereferenceable = LD->isDereferenceable();
7904   RLI.IsInvariant = LD->isInvariant();
7905   RLI.Alignment = LD->getAlignment();
7906   RLI.AAInfo = LD->getAAInfo();
7907   RLI.Ranges = LD->getRanges();
7908 
7909   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7910   return true;
7911 }
7912 
7913 // Given the head of the old chain, ResChain, insert a token factor containing
7914 // it and NewResChain, and make users of ResChain now be users of that token
7915 // factor.
7916 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7917 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7918                                         SDValue NewResChain,
7919                                         SelectionDAG &DAG) const {
7920   if (!ResChain)
7921     return;
7922 
7923   SDLoc dl(NewResChain);
7924 
7925   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7926                            NewResChain, DAG.getUNDEF(MVT::Other));
7927   assert(TF.getNode() != NewResChain.getNode() &&
7928          "A new TF really is required here");
7929 
7930   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7931   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7932 }
7933 
7934 /// Analyze profitability of direct move
7935 /// prefer float load to int load plus direct move
7936 /// when there is no integer use of int load
7937 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7938   SDNode *Origin = Op.getOperand(0).getNode();
7939   if (Origin->getOpcode() != ISD::LOAD)
7940     return true;
7941 
7942   // If there is no LXSIBZX/LXSIHZX, like Power8,
7943   // prefer direct move if the memory size is 1 or 2 bytes.
7944   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7945   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7946     return true;
7947 
7948   for (SDNode::use_iterator UI = Origin->use_begin(),
7949                             UE = Origin->use_end();
7950        UI != UE; ++UI) {
7951 
7952     // Only look at the users of the loaded value.
7953     if (UI.getUse().get().getResNo() != 0)
7954       continue;
7955 
7956     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7957         UI->getOpcode() != ISD::UINT_TO_FP)
7958       return true;
7959   }
7960 
7961   return false;
7962 }
7963 
7964 /// Custom lowers integer to floating point conversions to use
7965 /// the direct move instructions available in ISA 2.07 to avoid the
7966 /// need for load/store combinations.
7967 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7968                                                     SelectionDAG &DAG,
7969                                                     const SDLoc &dl) const {
7970   assert((Op.getValueType() == MVT::f32 ||
7971           Op.getValueType() == MVT::f64) &&
7972          "Invalid floating point type as target of conversion");
7973   assert(Subtarget.hasFPCVT() &&
7974          "Int to FP conversions with direct moves require FPCVT");
7975   SDValue FP;
7976   SDValue Src = Op.getOperand(0);
7977   bool SinglePrec = Op.getValueType() == MVT::f32;
7978   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7979   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7980   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7981                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7982 
7983   if (WordInt) {
7984     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7985                      dl, MVT::f64, Src);
7986     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7987   }
7988   else {
7989     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7990     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7991   }
7992 
7993   return FP;
7994 }
7995 
7996 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7997 
7998   EVT VecVT = Vec.getValueType();
7999   assert(VecVT.isVector() && "Expected a vector type.");
8000   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8001 
8002   EVT EltVT = VecVT.getVectorElementType();
8003   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8004   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8005 
8006   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8007   SmallVector<SDValue, 16> Ops(NumConcat);
8008   Ops[0] = Vec;
8009   SDValue UndefVec = DAG.getUNDEF(VecVT);
8010   for (unsigned i = 1; i < NumConcat; ++i)
8011     Ops[i] = UndefVec;
8012 
8013   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8014 }
8015 
8016 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8017                                                 const SDLoc &dl) const {
8018 
8019   unsigned Opc = Op.getOpcode();
8020   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8021          "Unexpected conversion type");
8022   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8023          "Supports conversions to v2f64/v4f32 only.");
8024 
8025   bool SignedConv = Opc == ISD::SINT_TO_FP;
8026   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8027 
8028   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8029   EVT WideVT = Wide.getValueType();
8030   unsigned WideNumElts = WideVT.getVectorNumElements();
8031   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8032 
8033   SmallVector<int, 16> ShuffV;
8034   for (unsigned i = 0; i < WideNumElts; ++i)
8035     ShuffV.push_back(i + WideNumElts);
8036 
8037   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8038   int SaveElts = FourEltRes ? 4 : 2;
8039   if (Subtarget.isLittleEndian())
8040     for (int i = 0; i < SaveElts; i++)
8041       ShuffV[i * Stride] = i;
8042   else
8043     for (int i = 1; i <= SaveElts; i++)
8044       ShuffV[i * Stride - 1] = i - 1;
8045 
8046   SDValue ShuffleSrc2 =
8047       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8048   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8049   unsigned ExtendOp =
8050       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
8051 
8052   SDValue Extend;
8053   if (!Subtarget.hasP9Altivec() && SignedConv) {
8054     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8055     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8056                          DAG.getValueType(Op.getOperand(0).getValueType()));
8057   } else
8058     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
8059 
8060   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8061 }
8062 
8063 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8064                                           SelectionDAG &DAG) const {
8065   SDLoc dl(Op);
8066 
8067   EVT InVT = Op.getOperand(0).getValueType();
8068   EVT OutVT = Op.getValueType();
8069   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8070       isOperationCustom(Op.getOpcode(), InVT))
8071     return LowerINT_TO_FPVector(Op, DAG, dl);
8072 
8073   // Conversions to f128 are legal.
8074   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8075     return Op;
8076 
8077   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8078     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8079       return SDValue();
8080 
8081     SDValue Value = Op.getOperand(0);
8082     // The values are now known to be -1 (false) or 1 (true). To convert this
8083     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8084     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8085     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8086 
8087     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8088 
8089     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8090 
8091     if (Op.getValueType() != MVT::v4f64)
8092       Value = DAG.getNode(ISD::FP_ROUND, dl,
8093                           Op.getValueType(), Value,
8094                           DAG.getIntPtrConstant(1, dl));
8095     return Value;
8096   }
8097 
8098   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8099   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8100     return SDValue();
8101 
8102   if (Op.getOperand(0).getValueType() == MVT::i1)
8103     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8104                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8105                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8106 
8107   // If we have direct moves, we can do all the conversion, skip the store/load
8108   // however, without FPCVT we can't do most conversions.
8109   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8110       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8111     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8112 
8113   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8114          "UINT_TO_FP is supported only with FPCVT");
8115 
8116   // If we have FCFIDS, then use it when converting to single-precision.
8117   // Otherwise, convert to double-precision and then round.
8118   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8119                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8120                                                             : PPCISD::FCFIDS)
8121                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8122                                                             : PPCISD::FCFID);
8123   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8124                   ? MVT::f32
8125                   : MVT::f64;
8126 
8127   if (Op.getOperand(0).getValueType() == MVT::i64) {
8128     SDValue SINT = Op.getOperand(0);
8129     // When converting to single-precision, we actually need to convert
8130     // to double-precision first and then round to single-precision.
8131     // To avoid double-rounding effects during that operation, we have
8132     // to prepare the input operand.  Bits that might be truncated when
8133     // converting to double-precision are replaced by a bit that won't
8134     // be lost at this stage, but is below the single-precision rounding
8135     // position.
8136     //
8137     // However, if -enable-unsafe-fp-math is in effect, accept double
8138     // rounding to avoid the extra overhead.
8139     if (Op.getValueType() == MVT::f32 &&
8140         !Subtarget.hasFPCVT() &&
8141         !DAG.getTarget().Options.UnsafeFPMath) {
8142 
8143       // Twiddle input to make sure the low 11 bits are zero.  (If this
8144       // is the case, we are guaranteed the value will fit into the 53 bit
8145       // mantissa of an IEEE double-precision value without rounding.)
8146       // If any of those low 11 bits were not zero originally, make sure
8147       // bit 12 (value 2048) is set instead, so that the final rounding
8148       // to single-precision gets the correct result.
8149       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8150                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8151       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8152                           Round, DAG.getConstant(2047, dl, MVT::i64));
8153       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8154       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8155                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8156 
8157       // However, we cannot use that value unconditionally: if the magnitude
8158       // of the input value is small, the bit-twiddling we did above might
8159       // end up visibly changing the output.  Fortunately, in that case, we
8160       // don't need to twiddle bits since the original input will convert
8161       // exactly to double-precision floating-point already.  Therefore,
8162       // construct a conditional to use the original value if the top 11
8163       // bits are all sign-bit copies, and use the rounded value computed
8164       // above otherwise.
8165       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8166                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8167       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8168                          Cond, DAG.getConstant(1, dl, MVT::i64));
8169       Cond = DAG.getSetCC(dl, MVT::i32,
8170                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8171 
8172       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8173     }
8174 
8175     ReuseLoadInfo RLI;
8176     SDValue Bits;
8177 
8178     MachineFunction &MF = DAG.getMachineFunction();
8179     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8180       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8181                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8182       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8183     } else if (Subtarget.hasLFIWAX() &&
8184                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8185       MachineMemOperand *MMO =
8186         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8187                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8188       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8189       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8190                                      DAG.getVTList(MVT::f64, MVT::Other),
8191                                      Ops, MVT::i32, MMO);
8192       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8193     } else if (Subtarget.hasFPCVT() &&
8194                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8195       MachineMemOperand *MMO =
8196         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8197                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8198       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8199       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8200                                      DAG.getVTList(MVT::f64, MVT::Other),
8201                                      Ops, MVT::i32, MMO);
8202       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8203     } else if (((Subtarget.hasLFIWAX() &&
8204                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8205                 (Subtarget.hasFPCVT() &&
8206                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8207                SINT.getOperand(0).getValueType() == MVT::i32) {
8208       MachineFrameInfo &MFI = MF.getFrameInfo();
8209       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8210 
8211       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8212       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8213 
8214       SDValue Store =
8215           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8216                        MachinePointerInfo::getFixedStack(
8217                            DAG.getMachineFunction(), FrameIdx));
8218 
8219       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8220              "Expected an i32 store");
8221 
8222       RLI.Ptr = FIdx;
8223       RLI.Chain = Store;
8224       RLI.MPI =
8225           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8226       RLI.Alignment = 4;
8227 
8228       MachineMemOperand *MMO =
8229         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8230                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8231       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8232       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8233                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8234                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8235                                      Ops, MVT::i32, MMO);
8236     } else
8237       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8238 
8239     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8240 
8241     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8242       FP = DAG.getNode(ISD::FP_ROUND, dl,
8243                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8244     return FP;
8245   }
8246 
8247   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8248          "Unhandled INT_TO_FP type in custom expander!");
8249   // Since we only generate this in 64-bit mode, we can take advantage of
8250   // 64-bit registers.  In particular, sign extend the input value into the
8251   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8252   // then lfd it and fcfid it.
8253   MachineFunction &MF = DAG.getMachineFunction();
8254   MachineFrameInfo &MFI = MF.getFrameInfo();
8255   EVT PtrVT = getPointerTy(MF.getDataLayout());
8256 
8257   SDValue Ld;
8258   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8259     ReuseLoadInfo RLI;
8260     bool ReusingLoad;
8261     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8262                                             DAG))) {
8263       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8264       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8265 
8266       SDValue Store =
8267           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8268                        MachinePointerInfo::getFixedStack(
8269                            DAG.getMachineFunction(), FrameIdx));
8270 
8271       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8272              "Expected an i32 store");
8273 
8274       RLI.Ptr = FIdx;
8275       RLI.Chain = Store;
8276       RLI.MPI =
8277           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8278       RLI.Alignment = 4;
8279     }
8280 
8281     MachineMemOperand *MMO =
8282       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8283                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8284     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8285     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8286                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8287                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8288                                  Ops, MVT::i32, MMO);
8289     if (ReusingLoad)
8290       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8291   } else {
8292     assert(Subtarget.isPPC64() &&
8293            "i32->FP without LFIWAX supported only on PPC64");
8294 
8295     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8296     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8297 
8298     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8299                                 Op.getOperand(0));
8300 
8301     // STD the extended value into the stack slot.
8302     SDValue Store = DAG.getStore(
8303         DAG.getEntryNode(), dl, Ext64, FIdx,
8304         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8305 
8306     // Load the value as a double.
8307     Ld = DAG.getLoad(
8308         MVT::f64, dl, Store, FIdx,
8309         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8310   }
8311 
8312   // FCFID it and return it.
8313   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8314   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8315     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8316                      DAG.getIntPtrConstant(0, dl));
8317   return FP;
8318 }
8319 
8320 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8321                                             SelectionDAG &DAG) const {
8322   SDLoc dl(Op);
8323   /*
8324    The rounding mode is in bits 30:31 of FPSR, and has the following
8325    settings:
8326      00 Round to nearest
8327      01 Round to 0
8328      10 Round to +inf
8329      11 Round to -inf
8330 
8331   FLT_ROUNDS, on the other hand, expects the following:
8332     -1 Undefined
8333      0 Round to 0
8334      1 Round to nearest
8335      2 Round to +inf
8336      3 Round to -inf
8337 
8338   To perform the conversion, we do:
8339     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8340   */
8341 
8342   MachineFunction &MF = DAG.getMachineFunction();
8343   EVT VT = Op.getValueType();
8344   EVT PtrVT = getPointerTy(MF.getDataLayout());
8345 
8346   // Save FP Control Word to register
8347   EVT NodeTys[] = {
8348     MVT::f64,    // return register
8349     MVT::Glue    // unused in this context
8350   };
8351   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
8352 
8353   // Save FP register to stack slot
8354   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8355   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8356   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
8357                                MachinePointerInfo());
8358 
8359   // Load FP Control Word from low 32 bits of stack slot.
8360   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8361   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8362   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
8363 
8364   // Transform as necessary
8365   SDValue CWD1 =
8366     DAG.getNode(ISD::AND, dl, MVT::i32,
8367                 CWD, DAG.getConstant(3, dl, MVT::i32));
8368   SDValue CWD2 =
8369     DAG.getNode(ISD::SRL, dl, MVT::i32,
8370                 DAG.getNode(ISD::AND, dl, MVT::i32,
8371                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8372                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8373                             DAG.getConstant(3, dl, MVT::i32)),
8374                 DAG.getConstant(1, dl, MVT::i32));
8375 
8376   SDValue RetVal =
8377     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8378 
8379   return DAG.getNode((VT.getSizeInBits() < 16 ?
8380                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8381 }
8382 
8383 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8384   EVT VT = Op.getValueType();
8385   unsigned BitWidth = VT.getSizeInBits();
8386   SDLoc dl(Op);
8387   assert(Op.getNumOperands() == 3 &&
8388          VT == Op.getOperand(1).getValueType() &&
8389          "Unexpected SHL!");
8390 
8391   // Expand into a bunch of logical ops.  Note that these ops
8392   // depend on the PPC behavior for oversized shift amounts.
8393   SDValue Lo = Op.getOperand(0);
8394   SDValue Hi = Op.getOperand(1);
8395   SDValue Amt = Op.getOperand(2);
8396   EVT AmtVT = Amt.getValueType();
8397 
8398   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8399                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8400   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8401   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8402   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8403   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8404                              DAG.getConstant(-BitWidth, dl, AmtVT));
8405   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8406   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8407   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8408   SDValue OutOps[] = { OutLo, OutHi };
8409   return DAG.getMergeValues(OutOps, dl);
8410 }
8411 
8412 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8413   EVT VT = Op.getValueType();
8414   SDLoc dl(Op);
8415   unsigned BitWidth = VT.getSizeInBits();
8416   assert(Op.getNumOperands() == 3 &&
8417          VT == Op.getOperand(1).getValueType() &&
8418          "Unexpected SRL!");
8419 
8420   // Expand into a bunch of logical ops.  Note that these ops
8421   // depend on the PPC behavior for oversized shift amounts.
8422   SDValue Lo = Op.getOperand(0);
8423   SDValue Hi = Op.getOperand(1);
8424   SDValue Amt = Op.getOperand(2);
8425   EVT AmtVT = Amt.getValueType();
8426 
8427   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8428                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8429   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8430   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8431   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8432   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8433                              DAG.getConstant(-BitWidth, dl, AmtVT));
8434   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8435   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8436   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8437   SDValue OutOps[] = { OutLo, OutHi };
8438   return DAG.getMergeValues(OutOps, dl);
8439 }
8440 
8441 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8442   SDLoc dl(Op);
8443   EVT VT = Op.getValueType();
8444   unsigned BitWidth = VT.getSizeInBits();
8445   assert(Op.getNumOperands() == 3 &&
8446          VT == Op.getOperand(1).getValueType() &&
8447          "Unexpected SRA!");
8448 
8449   // Expand into a bunch of logical ops, followed by a select_cc.
8450   SDValue Lo = Op.getOperand(0);
8451   SDValue Hi = Op.getOperand(1);
8452   SDValue Amt = Op.getOperand(2);
8453   EVT AmtVT = Amt.getValueType();
8454 
8455   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8456                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8457   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8458   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8459   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8460   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8461                              DAG.getConstant(-BitWidth, dl, AmtVT));
8462   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8463   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8464   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8465                                   Tmp4, Tmp6, ISD::SETLE);
8466   SDValue OutOps[] = { OutLo, OutHi };
8467   return DAG.getMergeValues(OutOps, dl);
8468 }
8469 
8470 //===----------------------------------------------------------------------===//
8471 // Vector related lowering.
8472 //
8473 
8474 /// BuildSplatI - Build a canonical splati of Val with an element size of
8475 /// SplatSize.  Cast the result to VT.
8476 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8477                            SelectionDAG &DAG, const SDLoc &dl) {
8478   static const MVT VTys[] = { // canonical VT to use for each size.
8479     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8480   };
8481 
8482   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8483 
8484   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8485   if (Val == -1)
8486     SplatSize = 1;
8487 
8488   EVT CanonicalVT = VTys[SplatSize-1];
8489 
8490   // Build a canonical splat for this value.
8491   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8492 }
8493 
8494 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8495 /// specified intrinsic ID.
8496 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8497                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8498   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8499   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8500                      DAG.getConstant(IID, dl, MVT::i32), Op);
8501 }
8502 
8503 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8504 /// specified intrinsic ID.
8505 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8506                                 SelectionDAG &DAG, const SDLoc &dl,
8507                                 EVT DestVT = MVT::Other) {
8508   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8509   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8510                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8511 }
8512 
8513 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8514 /// specified intrinsic ID.
8515 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8516                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8517                                 EVT DestVT = MVT::Other) {
8518   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8519   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8520                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8521 }
8522 
8523 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8524 /// amount.  The result has the specified value type.
8525 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8526                            SelectionDAG &DAG, const SDLoc &dl) {
8527   // Force LHS/RHS to be the right type.
8528   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8529   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8530 
8531   int Ops[16];
8532   for (unsigned i = 0; i != 16; ++i)
8533     Ops[i] = i + Amt;
8534   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8535   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8536 }
8537 
8538 /// Do we have an efficient pattern in a .td file for this node?
8539 ///
8540 /// \param V - pointer to the BuildVectorSDNode being matched
8541 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8542 ///
8543 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8544 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8545 /// the opposite is true (expansion is beneficial) are:
8546 /// - The node builds a vector out of integers that are not 32 or 64-bits
8547 /// - The node builds a vector out of constants
8548 /// - The node is a "load-and-splat"
8549 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8550 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8551                                             bool HasDirectMove,
8552                                             bool HasP8Vector) {
8553   EVT VecVT = V->getValueType(0);
8554   bool RightType = VecVT == MVT::v2f64 ||
8555     (HasP8Vector && VecVT == MVT::v4f32) ||
8556     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8557   if (!RightType)
8558     return false;
8559 
8560   bool IsSplat = true;
8561   bool IsLoad = false;
8562   SDValue Op0 = V->getOperand(0);
8563 
8564   // This function is called in a block that confirms the node is not a constant
8565   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8566   // different constants.
8567   if (V->isConstant())
8568     return false;
8569   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8570     if (V->getOperand(i).isUndef())
8571       return false;
8572     // We want to expand nodes that represent load-and-splat even if the
8573     // loaded value is a floating point truncation or conversion to int.
8574     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8575         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8576          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8577         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8578          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8579         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8580          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8581       IsLoad = true;
8582     // If the operands are different or the input is not a load and has more
8583     // uses than just this BV node, then it isn't a splat.
8584     if (V->getOperand(i) != Op0 ||
8585         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8586       IsSplat = false;
8587   }
8588   return !(IsSplat && IsLoad);
8589 }
8590 
8591 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8592 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8593 
8594   SDLoc dl(Op);
8595   SDValue Op0 = Op->getOperand(0);
8596 
8597   if (!EnableQuadPrecision ||
8598       (Op.getValueType() != MVT::f128 ) ||
8599       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8600       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8601       (Op0.getOperand(1).getValueType() != MVT::i64))
8602     return SDValue();
8603 
8604   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8605                      Op0.getOperand(1));
8606 }
8607 
8608 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8609   const SDValue *InputLoad = &Op;
8610   if (InputLoad->getOpcode() == ISD::BITCAST)
8611     InputLoad = &InputLoad->getOperand(0);
8612   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8613     InputLoad = &InputLoad->getOperand(0);
8614   if (InputLoad->getOpcode() != ISD::LOAD)
8615     return nullptr;
8616   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8617   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8618 }
8619 
8620 // If this is a case we can't handle, return null and let the default
8621 // expansion code take care of it.  If we CAN select this case, and if it
8622 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8623 // this case more efficiently than a constant pool load, lower it to the
8624 // sequence of ops that should be used.
8625 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8626                                              SelectionDAG &DAG) const {
8627   SDLoc dl(Op);
8628   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8629   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8630 
8631   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8632     // We first build an i32 vector, load it into a QPX register,
8633     // then convert it to a floating-point vector and compare it
8634     // to a zero vector to get the boolean result.
8635     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8636     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8637     MachinePointerInfo PtrInfo =
8638         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8639     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8640     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8641 
8642     assert(BVN->getNumOperands() == 4 &&
8643       "BUILD_VECTOR for v4i1 does not have 4 operands");
8644 
8645     bool IsConst = true;
8646     for (unsigned i = 0; i < 4; ++i) {
8647       if (BVN->getOperand(i).isUndef()) continue;
8648       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8649         IsConst = false;
8650         break;
8651       }
8652     }
8653 
8654     if (IsConst) {
8655       Constant *One =
8656         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8657       Constant *NegOne =
8658         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8659 
8660       Constant *CV[4];
8661       for (unsigned i = 0; i < 4; ++i) {
8662         if (BVN->getOperand(i).isUndef())
8663           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8664         else if (isNullConstant(BVN->getOperand(i)))
8665           CV[i] = NegOne;
8666         else
8667           CV[i] = One;
8668       }
8669 
8670       Constant *CP = ConstantVector::get(CV);
8671       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8672                                           16 /* alignment */);
8673 
8674       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8675       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8676       return DAG.getMemIntrinsicNode(
8677           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8678           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8679     }
8680 
8681     SmallVector<SDValue, 4> Stores;
8682     for (unsigned i = 0; i < 4; ++i) {
8683       if (BVN->getOperand(i).isUndef()) continue;
8684 
8685       unsigned Offset = 4*i;
8686       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8687       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8688 
8689       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8690       if (StoreSize > 4) {
8691         Stores.push_back(
8692             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8693                               PtrInfo.getWithOffset(Offset), MVT::i32));
8694       } else {
8695         SDValue StoreValue = BVN->getOperand(i);
8696         if (StoreSize < 4)
8697           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8698 
8699         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8700                                       PtrInfo.getWithOffset(Offset)));
8701       }
8702     }
8703 
8704     SDValue StoreChain;
8705     if (!Stores.empty())
8706       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8707     else
8708       StoreChain = DAG.getEntryNode();
8709 
8710     // Now load from v4i32 into the QPX register; this will extend it to
8711     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8712     // is typed as v4f64 because the QPX register integer states are not
8713     // explicitly represented.
8714 
8715     SDValue Ops[] = {StoreChain,
8716                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8717                      FIdx};
8718     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8719 
8720     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8721       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8722     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8723       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8724       LoadedVect);
8725 
8726     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8727 
8728     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8729   }
8730 
8731   // All other QPX vectors are handled by generic code.
8732   if (Subtarget.hasQPX())
8733     return SDValue();
8734 
8735   // Check if this is a splat of a constant value.
8736   APInt APSplatBits, APSplatUndef;
8737   unsigned SplatBitSize;
8738   bool HasAnyUndefs;
8739   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8740                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8741       SplatBitSize > 32) {
8742 
8743     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8744     // Handle load-and-splat patterns as we have instructions that will do this
8745     // in one go.
8746     if (InputLoad && DAG.isSplatValue(Op, true)) {
8747       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8748 
8749       // We have handling for 4 and 8 byte elements.
8750       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8751 
8752       // Checking for a single use of this load, we have to check for vector
8753       // width (128 bits) / ElementSize uses (since each operand of the
8754       // BUILD_VECTOR is a separate use of the value.
8755       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8756           ((Subtarget.hasVSX() && ElementSize == 64) ||
8757            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8758         SDValue Ops[] = {
8759           LD->getChain(),    // Chain
8760           LD->getBasePtr(),  // Ptr
8761           DAG.getValueType(Op.getValueType()) // VT
8762         };
8763         return
8764           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8765                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8766                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8767       }
8768     }
8769 
8770     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8771     // lowered to VSX instructions under certain conditions.
8772     // Without VSX, there is no pattern more efficient than expanding the node.
8773     if (Subtarget.hasVSX() &&
8774         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8775                                         Subtarget.hasP8Vector()))
8776       return Op;
8777     return SDValue();
8778   }
8779 
8780   unsigned SplatBits = APSplatBits.getZExtValue();
8781   unsigned SplatUndef = APSplatUndef.getZExtValue();
8782   unsigned SplatSize = SplatBitSize / 8;
8783 
8784   // First, handle single instruction cases.
8785 
8786   // All zeros?
8787   if (SplatBits == 0) {
8788     // Canonicalize all zero vectors to be v4i32.
8789     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8790       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8791       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8792     }
8793     return Op;
8794   }
8795 
8796   // We have XXSPLTIB for constant splats one byte wide
8797   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8798   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8799   if (Subtarget.hasP9Vector() && SplatSize == 1)
8800     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8801 
8802   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8803   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8804                     (32-SplatBitSize));
8805   if (SextVal >= -16 && SextVal <= 15)
8806     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8807 
8808   // Two instruction sequences.
8809 
8810   // If this value is in the range [-32,30] and is even, use:
8811   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8812   // If this value is in the range [17,31] and is odd, use:
8813   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8814   // If this value is in the range [-31,-17] and is odd, use:
8815   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8816   // Note the last two are three-instruction sequences.
8817   if (SextVal >= -32 && SextVal <= 31) {
8818     // To avoid having these optimizations undone by constant folding,
8819     // we convert to a pseudo that will be expanded later into one of
8820     // the above forms.
8821     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8822     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8823               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8824     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8825     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8826     if (VT == Op.getValueType())
8827       return RetVal;
8828     else
8829       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8830   }
8831 
8832   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8833   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8834   // for fneg/fabs.
8835   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8836     // Make -1 and vspltisw -1:
8837     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8838 
8839     // Make the VSLW intrinsic, computing 0x8000_0000.
8840     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8841                                    OnesV, DAG, dl);
8842 
8843     // xor by OnesV to invert it.
8844     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8845     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8846   }
8847 
8848   // Check to see if this is a wide variety of vsplti*, binop self cases.
8849   static const signed char SplatCsts[] = {
8850     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8851     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8852   };
8853 
8854   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8855     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8856     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8857     int i = SplatCsts[idx];
8858 
8859     // Figure out what shift amount will be used by altivec if shifted by i in
8860     // this splat size.
8861     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8862 
8863     // vsplti + shl self.
8864     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8865       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8866       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8867         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8868         Intrinsic::ppc_altivec_vslw
8869       };
8870       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8871       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8872     }
8873 
8874     // vsplti + srl self.
8875     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8876       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8877       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8878         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8879         Intrinsic::ppc_altivec_vsrw
8880       };
8881       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8882       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8883     }
8884 
8885     // vsplti + sra self.
8886     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8887       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8888       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8889         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8890         Intrinsic::ppc_altivec_vsraw
8891       };
8892       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8893       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8894     }
8895 
8896     // vsplti + rol self.
8897     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8898                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8899       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8900       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8901         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8902         Intrinsic::ppc_altivec_vrlw
8903       };
8904       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8905       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8906     }
8907 
8908     // t = vsplti c, result = vsldoi t, t, 1
8909     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8910       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8911       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8912       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8913     }
8914     // t = vsplti c, result = vsldoi t, t, 2
8915     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8916       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8917       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8918       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8919     }
8920     // t = vsplti c, result = vsldoi t, t, 3
8921     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8922       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8923       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8924       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8925     }
8926   }
8927 
8928   return SDValue();
8929 }
8930 
8931 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8932 /// the specified operations to build the shuffle.
8933 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8934                                       SDValue RHS, SelectionDAG &DAG,
8935                                       const SDLoc &dl) {
8936   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8937   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8938   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8939 
8940   enum {
8941     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8942     OP_VMRGHW,
8943     OP_VMRGLW,
8944     OP_VSPLTISW0,
8945     OP_VSPLTISW1,
8946     OP_VSPLTISW2,
8947     OP_VSPLTISW3,
8948     OP_VSLDOI4,
8949     OP_VSLDOI8,
8950     OP_VSLDOI12
8951   };
8952 
8953   if (OpNum == OP_COPY) {
8954     if (LHSID == (1*9+2)*9+3) return LHS;
8955     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8956     return RHS;
8957   }
8958 
8959   SDValue OpLHS, OpRHS;
8960   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8961   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8962 
8963   int ShufIdxs[16];
8964   switch (OpNum) {
8965   default: llvm_unreachable("Unknown i32 permute!");
8966   case OP_VMRGHW:
8967     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8968     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8969     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8970     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8971     break;
8972   case OP_VMRGLW:
8973     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8974     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8975     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8976     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8977     break;
8978   case OP_VSPLTISW0:
8979     for (unsigned i = 0; i != 16; ++i)
8980       ShufIdxs[i] = (i&3)+0;
8981     break;
8982   case OP_VSPLTISW1:
8983     for (unsigned i = 0; i != 16; ++i)
8984       ShufIdxs[i] = (i&3)+4;
8985     break;
8986   case OP_VSPLTISW2:
8987     for (unsigned i = 0; i != 16; ++i)
8988       ShufIdxs[i] = (i&3)+8;
8989     break;
8990   case OP_VSPLTISW3:
8991     for (unsigned i = 0; i != 16; ++i)
8992       ShufIdxs[i] = (i&3)+12;
8993     break;
8994   case OP_VSLDOI4:
8995     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8996   case OP_VSLDOI8:
8997     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8998   case OP_VSLDOI12:
8999     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9000   }
9001   EVT VT = OpLHS.getValueType();
9002   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9003   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9004   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9005   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9006 }
9007 
9008 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9009 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9010 /// SDValue.
9011 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9012                                            SelectionDAG &DAG) const {
9013   const unsigned BytesInVector = 16;
9014   bool IsLE = Subtarget.isLittleEndian();
9015   SDLoc dl(N);
9016   SDValue V1 = N->getOperand(0);
9017   SDValue V2 = N->getOperand(1);
9018   unsigned ShiftElts = 0, InsertAtByte = 0;
9019   bool Swap = false;
9020 
9021   // Shifts required to get the byte we want at element 7.
9022   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9023                                    0, 15, 14, 13, 12, 11, 10, 9};
9024   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9025                                 1, 2,  3,  4,  5,  6,  7,  8};
9026 
9027   ArrayRef<int> Mask = N->getMask();
9028   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9029 
9030   // For each mask element, find out if we're just inserting something
9031   // from V2 into V1 or vice versa.
9032   // Possible permutations inserting an element from V2 into V1:
9033   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9034   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9035   //   ...
9036   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9037   // Inserting from V1 into V2 will be similar, except mask range will be
9038   // [16,31].
9039 
9040   bool FoundCandidate = false;
9041   // If both vector operands for the shuffle are the same vector, the mask
9042   // will contain only elements from the first one and the second one will be
9043   // undef.
9044   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9045   // Go through the mask of half-words to find an element that's being moved
9046   // from one vector to the other.
9047   for (unsigned i = 0; i < BytesInVector; ++i) {
9048     unsigned CurrentElement = Mask[i];
9049     // If 2nd operand is undefined, we should only look for element 7 in the
9050     // Mask.
9051     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9052       continue;
9053 
9054     bool OtherElementsInOrder = true;
9055     // Examine the other elements in the Mask to see if they're in original
9056     // order.
9057     for (unsigned j = 0; j < BytesInVector; ++j) {
9058       if (j == i)
9059         continue;
9060       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9061       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9062       // in which we always assume we're always picking from the 1st operand.
9063       int MaskOffset =
9064           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9065       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9066         OtherElementsInOrder = false;
9067         break;
9068       }
9069     }
9070     // If other elements are in original order, we record the number of shifts
9071     // we need to get the element we want into element 7. Also record which byte
9072     // in the vector we should insert into.
9073     if (OtherElementsInOrder) {
9074       // If 2nd operand is undefined, we assume no shifts and no swapping.
9075       if (V2.isUndef()) {
9076         ShiftElts = 0;
9077         Swap = false;
9078       } else {
9079         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9080         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9081                          : BigEndianShifts[CurrentElement & 0xF];
9082         Swap = CurrentElement < BytesInVector;
9083       }
9084       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9085       FoundCandidate = true;
9086       break;
9087     }
9088   }
9089 
9090   if (!FoundCandidate)
9091     return SDValue();
9092 
9093   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9094   // optionally with VECSHL if shift is required.
9095   if (Swap)
9096     std::swap(V1, V2);
9097   if (V2.isUndef())
9098     V2 = V1;
9099   if (ShiftElts) {
9100     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9101                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9102     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9103                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9104   }
9105   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9106                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9107 }
9108 
9109 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9110 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9111 /// SDValue.
9112 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9113                                            SelectionDAG &DAG) const {
9114   const unsigned NumHalfWords = 8;
9115   const unsigned BytesInVector = NumHalfWords * 2;
9116   // Check that the shuffle is on half-words.
9117   if (!isNByteElemShuffleMask(N, 2, 1))
9118     return SDValue();
9119 
9120   bool IsLE = Subtarget.isLittleEndian();
9121   SDLoc dl(N);
9122   SDValue V1 = N->getOperand(0);
9123   SDValue V2 = N->getOperand(1);
9124   unsigned ShiftElts = 0, InsertAtByte = 0;
9125   bool Swap = false;
9126 
9127   // Shifts required to get the half-word we want at element 3.
9128   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9129   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9130 
9131   uint32_t Mask = 0;
9132   uint32_t OriginalOrderLow = 0x1234567;
9133   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9134   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9135   // 32-bit space, only need 4-bit nibbles per element.
9136   for (unsigned i = 0; i < NumHalfWords; ++i) {
9137     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9138     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9139   }
9140 
9141   // For each mask element, find out if we're just inserting something
9142   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9143   // from V2 into V1:
9144   //   X, 1, 2, 3, 4, 5, 6, 7
9145   //   0, X, 2, 3, 4, 5, 6, 7
9146   //   0, 1, X, 3, 4, 5, 6, 7
9147   //   0, 1, 2, X, 4, 5, 6, 7
9148   //   0, 1, 2, 3, X, 5, 6, 7
9149   //   0, 1, 2, 3, 4, X, 6, 7
9150   //   0, 1, 2, 3, 4, 5, X, 7
9151   //   0, 1, 2, 3, 4, 5, 6, X
9152   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9153 
9154   bool FoundCandidate = false;
9155   // Go through the mask of half-words to find an element that's being moved
9156   // from one vector to the other.
9157   for (unsigned i = 0; i < NumHalfWords; ++i) {
9158     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9159     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9160     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9161     uint32_t TargetOrder = 0x0;
9162 
9163     // If both vector operands for the shuffle are the same vector, the mask
9164     // will contain only elements from the first one and the second one will be
9165     // undef.
9166     if (V2.isUndef()) {
9167       ShiftElts = 0;
9168       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9169       TargetOrder = OriginalOrderLow;
9170       Swap = false;
9171       // Skip if not the correct element or mask of other elements don't equal
9172       // to our expected order.
9173       if (MaskOneElt == VINSERTHSrcElem &&
9174           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9175         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9176         FoundCandidate = true;
9177         break;
9178       }
9179     } else { // If both operands are defined.
9180       // Target order is [8,15] if the current mask is between [0,7].
9181       TargetOrder =
9182           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9183       // Skip if mask of other elements don't equal our expected order.
9184       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9185         // We only need the last 3 bits for the number of shifts.
9186         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9187                          : BigEndianShifts[MaskOneElt & 0x7];
9188         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9189         Swap = MaskOneElt < NumHalfWords;
9190         FoundCandidate = true;
9191         break;
9192       }
9193     }
9194   }
9195 
9196   if (!FoundCandidate)
9197     return SDValue();
9198 
9199   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9200   // optionally with VECSHL if shift is required.
9201   if (Swap)
9202     std::swap(V1, V2);
9203   if (V2.isUndef())
9204     V2 = V1;
9205   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9206   if (ShiftElts) {
9207     // Double ShiftElts because we're left shifting on v16i8 type.
9208     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9209                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9210     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9211     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9212                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9213     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9214   }
9215   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9216   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9217                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9218   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9219 }
9220 
9221 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9222 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9223 /// return the code it can be lowered into.  Worst case, it can always be
9224 /// lowered into a vperm.
9225 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9226                                                SelectionDAG &DAG) const {
9227   SDLoc dl(Op);
9228   SDValue V1 = Op.getOperand(0);
9229   SDValue V2 = Op.getOperand(1);
9230   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9231   EVT VT = Op.getValueType();
9232   bool isLittleEndian = Subtarget.isLittleEndian();
9233 
9234   unsigned ShiftElts, InsertAtByte;
9235   bool Swap = false;
9236 
9237   // If this is a load-and-splat, we can do that with a single instruction
9238   // in some cases. However if the load has multiple uses, we don't want to
9239   // combine it because that will just produce multiple loads.
9240   const SDValue *InputLoad = getNormalLoadInput(V1);
9241   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9242       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9243       InputLoad->hasOneUse()) {
9244     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9245     int SplatIdx =
9246       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9247 
9248     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9249     // For 4-byte load-and-splat, we need Power9.
9250     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9251       uint64_t Offset = 0;
9252       if (IsFourByte)
9253         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9254       else
9255         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9256       SDValue BasePtr = LD->getBasePtr();
9257       if (Offset != 0)
9258         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9259                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9260       SDValue Ops[] = {
9261         LD->getChain(),    // Chain
9262         BasePtr,           // BasePtr
9263         DAG.getValueType(Op.getValueType()) // VT
9264       };
9265       SDVTList VTL =
9266         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9267       SDValue LdSplt =
9268         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9269                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9270       if (LdSplt.getValueType() != SVOp->getValueType(0))
9271         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9272       return LdSplt;
9273     }
9274   }
9275   if (Subtarget.hasP9Vector() &&
9276       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9277                            isLittleEndian)) {
9278     if (Swap)
9279       std::swap(V1, V2);
9280     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9281     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9282     if (ShiftElts) {
9283       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9284                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9285       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9286                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9287       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9288     }
9289     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9290                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9291     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9292   }
9293 
9294   if (Subtarget.hasP9Altivec()) {
9295     SDValue NewISDNode;
9296     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9297       return NewISDNode;
9298 
9299     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9300       return NewISDNode;
9301   }
9302 
9303   if (Subtarget.hasVSX() &&
9304       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9305     if (Swap)
9306       std::swap(V1, V2);
9307     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9308     SDValue Conv2 =
9309         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9310 
9311     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9312                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9313     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9314   }
9315 
9316   if (Subtarget.hasVSX() &&
9317     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9318     if (Swap)
9319       std::swap(V1, V2);
9320     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9321     SDValue Conv2 =
9322         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9323 
9324     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9325                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9326     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9327   }
9328 
9329   if (Subtarget.hasP9Vector()) {
9330      if (PPC::isXXBRHShuffleMask(SVOp)) {
9331       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9332       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9333       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9334     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9335       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9336       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9337       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9338     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9339       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9340       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9341       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9342     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9343       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9344       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9345       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9346     }
9347   }
9348 
9349   if (Subtarget.hasVSX()) {
9350     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9351       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9352 
9353       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9354       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9355                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9356       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9357     }
9358 
9359     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9360     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9361       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9362       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9363       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9364     }
9365   }
9366 
9367   if (Subtarget.hasQPX()) {
9368     if (VT.getVectorNumElements() != 4)
9369       return SDValue();
9370 
9371     if (V2.isUndef()) V2 = V1;
9372 
9373     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9374     if (AlignIdx != -1) {
9375       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9376                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9377     } else if (SVOp->isSplat()) {
9378       int SplatIdx = SVOp->getSplatIndex();
9379       if (SplatIdx >= 4) {
9380         std::swap(V1, V2);
9381         SplatIdx -= 4;
9382       }
9383 
9384       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9385                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9386     }
9387 
9388     // Lower this into a qvgpci/qvfperm pair.
9389 
9390     // Compute the qvgpci literal
9391     unsigned idx = 0;
9392     for (unsigned i = 0; i < 4; ++i) {
9393       int m = SVOp->getMaskElt(i);
9394       unsigned mm = m >= 0 ? (unsigned) m : i;
9395       idx |= mm << (3-i)*3;
9396     }
9397 
9398     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9399                              DAG.getConstant(idx, dl, MVT::i32));
9400     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9401   }
9402 
9403   // Cases that are handled by instructions that take permute immediates
9404   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9405   // selected by the instruction selector.
9406   if (V2.isUndef()) {
9407     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9408         PPC::isSplatShuffleMask(SVOp, 2) ||
9409         PPC::isSplatShuffleMask(SVOp, 4) ||
9410         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9411         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9412         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9413         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9414         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9415         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9416         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9417         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9418         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9419         (Subtarget.hasP8Altivec() && (
9420          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9421          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9422          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9423       return Op;
9424     }
9425   }
9426 
9427   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9428   // and produce a fixed permutation.  If any of these match, do not lower to
9429   // VPERM.
9430   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9431   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9432       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9433       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9434       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9435       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9436       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9437       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9438       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9439       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9440       (Subtarget.hasP8Altivec() && (
9441        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9442        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9443        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9444     return Op;
9445 
9446   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9447   // perfect shuffle table to emit an optimal matching sequence.
9448   ArrayRef<int> PermMask = SVOp->getMask();
9449 
9450   unsigned PFIndexes[4];
9451   bool isFourElementShuffle = true;
9452   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9453     unsigned EltNo = 8;   // Start out undef.
9454     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9455       if (PermMask[i*4+j] < 0)
9456         continue;   // Undef, ignore it.
9457 
9458       unsigned ByteSource = PermMask[i*4+j];
9459       if ((ByteSource & 3) != j) {
9460         isFourElementShuffle = false;
9461         break;
9462       }
9463 
9464       if (EltNo == 8) {
9465         EltNo = ByteSource/4;
9466       } else if (EltNo != ByteSource/4) {
9467         isFourElementShuffle = false;
9468         break;
9469       }
9470     }
9471     PFIndexes[i] = EltNo;
9472   }
9473 
9474   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9475   // perfect shuffle vector to determine if it is cost effective to do this as
9476   // discrete instructions, or whether we should use a vperm.
9477   // For now, we skip this for little endian until such time as we have a
9478   // little-endian perfect shuffle table.
9479   if (isFourElementShuffle && !isLittleEndian) {
9480     // Compute the index in the perfect shuffle table.
9481     unsigned PFTableIndex =
9482       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9483 
9484     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9485     unsigned Cost  = (PFEntry >> 30);
9486 
9487     // Determining when to avoid vperm is tricky.  Many things affect the cost
9488     // of vperm, particularly how many times the perm mask needs to be computed.
9489     // For example, if the perm mask can be hoisted out of a loop or is already
9490     // used (perhaps because there are multiple permutes with the same shuffle
9491     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9492     // the loop requires an extra register.
9493     //
9494     // As a compromise, we only emit discrete instructions if the shuffle can be
9495     // generated in 3 or fewer operations.  When we have loop information
9496     // available, if this block is within a loop, we should avoid using vperm
9497     // for 3-operation perms and use a constant pool load instead.
9498     if (Cost < 3)
9499       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9500   }
9501 
9502   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9503   // vector that will get spilled to the constant pool.
9504   if (V2.isUndef()) V2 = V1;
9505 
9506   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9507   // that it is in input element units, not in bytes.  Convert now.
9508 
9509   // For little endian, the order of the input vectors is reversed, and
9510   // the permutation mask is complemented with respect to 31.  This is
9511   // necessary to produce proper semantics with the big-endian-biased vperm
9512   // instruction.
9513   EVT EltVT = V1.getValueType().getVectorElementType();
9514   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9515 
9516   SmallVector<SDValue, 16> ResultMask;
9517   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9518     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9519 
9520     for (unsigned j = 0; j != BytesPerElement; ++j)
9521       if (isLittleEndian)
9522         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9523                                              dl, MVT::i32));
9524       else
9525         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9526                                              MVT::i32));
9527   }
9528 
9529   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9530   if (isLittleEndian)
9531     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9532                        V2, V1, VPermMask);
9533   else
9534     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9535                        V1, V2, VPermMask);
9536 }
9537 
9538 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9539 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9540 /// information about the intrinsic.
9541 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9542                                  bool &isDot, const PPCSubtarget &Subtarget) {
9543   unsigned IntrinsicID =
9544       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9545   CompareOpc = -1;
9546   isDot = false;
9547   switch (IntrinsicID) {
9548   default:
9549     return false;
9550   // Comparison predicates.
9551   case Intrinsic::ppc_altivec_vcmpbfp_p:
9552     CompareOpc = 966;
9553     isDot = true;
9554     break;
9555   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9556     CompareOpc = 198;
9557     isDot = true;
9558     break;
9559   case Intrinsic::ppc_altivec_vcmpequb_p:
9560     CompareOpc = 6;
9561     isDot = true;
9562     break;
9563   case Intrinsic::ppc_altivec_vcmpequh_p:
9564     CompareOpc = 70;
9565     isDot = true;
9566     break;
9567   case Intrinsic::ppc_altivec_vcmpequw_p:
9568     CompareOpc = 134;
9569     isDot = true;
9570     break;
9571   case Intrinsic::ppc_altivec_vcmpequd_p:
9572     if (Subtarget.hasP8Altivec()) {
9573       CompareOpc = 199;
9574       isDot = true;
9575     } else
9576       return false;
9577     break;
9578   case Intrinsic::ppc_altivec_vcmpneb_p:
9579   case Intrinsic::ppc_altivec_vcmpneh_p:
9580   case Intrinsic::ppc_altivec_vcmpnew_p:
9581   case Intrinsic::ppc_altivec_vcmpnezb_p:
9582   case Intrinsic::ppc_altivec_vcmpnezh_p:
9583   case Intrinsic::ppc_altivec_vcmpnezw_p:
9584     if (Subtarget.hasP9Altivec()) {
9585       switch (IntrinsicID) {
9586       default:
9587         llvm_unreachable("Unknown comparison intrinsic.");
9588       case Intrinsic::ppc_altivec_vcmpneb_p:
9589         CompareOpc = 7;
9590         break;
9591       case Intrinsic::ppc_altivec_vcmpneh_p:
9592         CompareOpc = 71;
9593         break;
9594       case Intrinsic::ppc_altivec_vcmpnew_p:
9595         CompareOpc = 135;
9596         break;
9597       case Intrinsic::ppc_altivec_vcmpnezb_p:
9598         CompareOpc = 263;
9599         break;
9600       case Intrinsic::ppc_altivec_vcmpnezh_p:
9601         CompareOpc = 327;
9602         break;
9603       case Intrinsic::ppc_altivec_vcmpnezw_p:
9604         CompareOpc = 391;
9605         break;
9606       }
9607       isDot = true;
9608     } else
9609       return false;
9610     break;
9611   case Intrinsic::ppc_altivec_vcmpgefp_p:
9612     CompareOpc = 454;
9613     isDot = true;
9614     break;
9615   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9616     CompareOpc = 710;
9617     isDot = true;
9618     break;
9619   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9620     CompareOpc = 774;
9621     isDot = true;
9622     break;
9623   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9624     CompareOpc = 838;
9625     isDot = true;
9626     break;
9627   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9628     CompareOpc = 902;
9629     isDot = true;
9630     break;
9631   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9632     if (Subtarget.hasP8Altivec()) {
9633       CompareOpc = 967;
9634       isDot = true;
9635     } else
9636       return false;
9637     break;
9638   case Intrinsic::ppc_altivec_vcmpgtub_p:
9639     CompareOpc = 518;
9640     isDot = true;
9641     break;
9642   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9643     CompareOpc = 582;
9644     isDot = true;
9645     break;
9646   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9647     CompareOpc = 646;
9648     isDot = true;
9649     break;
9650   case Intrinsic::ppc_altivec_vcmpgtud_p:
9651     if (Subtarget.hasP8Altivec()) {
9652       CompareOpc = 711;
9653       isDot = true;
9654     } else
9655       return false;
9656     break;
9657 
9658   // VSX predicate comparisons use the same infrastructure
9659   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9660   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9661   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9662   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9663   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9664   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9665     if (Subtarget.hasVSX()) {
9666       switch (IntrinsicID) {
9667       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9668         CompareOpc = 99;
9669         break;
9670       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9671         CompareOpc = 115;
9672         break;
9673       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9674         CompareOpc = 107;
9675         break;
9676       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9677         CompareOpc = 67;
9678         break;
9679       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9680         CompareOpc = 83;
9681         break;
9682       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9683         CompareOpc = 75;
9684         break;
9685       }
9686       isDot = true;
9687     } else
9688       return false;
9689     break;
9690 
9691   // Normal Comparisons.
9692   case Intrinsic::ppc_altivec_vcmpbfp:
9693     CompareOpc = 966;
9694     break;
9695   case Intrinsic::ppc_altivec_vcmpeqfp:
9696     CompareOpc = 198;
9697     break;
9698   case Intrinsic::ppc_altivec_vcmpequb:
9699     CompareOpc = 6;
9700     break;
9701   case Intrinsic::ppc_altivec_vcmpequh:
9702     CompareOpc = 70;
9703     break;
9704   case Intrinsic::ppc_altivec_vcmpequw:
9705     CompareOpc = 134;
9706     break;
9707   case Intrinsic::ppc_altivec_vcmpequd:
9708     if (Subtarget.hasP8Altivec())
9709       CompareOpc = 199;
9710     else
9711       return false;
9712     break;
9713   case Intrinsic::ppc_altivec_vcmpneb:
9714   case Intrinsic::ppc_altivec_vcmpneh:
9715   case Intrinsic::ppc_altivec_vcmpnew:
9716   case Intrinsic::ppc_altivec_vcmpnezb:
9717   case Intrinsic::ppc_altivec_vcmpnezh:
9718   case Intrinsic::ppc_altivec_vcmpnezw:
9719     if (Subtarget.hasP9Altivec())
9720       switch (IntrinsicID) {
9721       default:
9722         llvm_unreachable("Unknown comparison intrinsic.");
9723       case Intrinsic::ppc_altivec_vcmpneb:
9724         CompareOpc = 7;
9725         break;
9726       case Intrinsic::ppc_altivec_vcmpneh:
9727         CompareOpc = 71;
9728         break;
9729       case Intrinsic::ppc_altivec_vcmpnew:
9730         CompareOpc = 135;
9731         break;
9732       case Intrinsic::ppc_altivec_vcmpnezb:
9733         CompareOpc = 263;
9734         break;
9735       case Intrinsic::ppc_altivec_vcmpnezh:
9736         CompareOpc = 327;
9737         break;
9738       case Intrinsic::ppc_altivec_vcmpnezw:
9739         CompareOpc = 391;
9740         break;
9741       }
9742     else
9743       return false;
9744     break;
9745   case Intrinsic::ppc_altivec_vcmpgefp:
9746     CompareOpc = 454;
9747     break;
9748   case Intrinsic::ppc_altivec_vcmpgtfp:
9749     CompareOpc = 710;
9750     break;
9751   case Intrinsic::ppc_altivec_vcmpgtsb:
9752     CompareOpc = 774;
9753     break;
9754   case Intrinsic::ppc_altivec_vcmpgtsh:
9755     CompareOpc = 838;
9756     break;
9757   case Intrinsic::ppc_altivec_vcmpgtsw:
9758     CompareOpc = 902;
9759     break;
9760   case Intrinsic::ppc_altivec_vcmpgtsd:
9761     if (Subtarget.hasP8Altivec())
9762       CompareOpc = 967;
9763     else
9764       return false;
9765     break;
9766   case Intrinsic::ppc_altivec_vcmpgtub:
9767     CompareOpc = 518;
9768     break;
9769   case Intrinsic::ppc_altivec_vcmpgtuh:
9770     CompareOpc = 582;
9771     break;
9772   case Intrinsic::ppc_altivec_vcmpgtuw:
9773     CompareOpc = 646;
9774     break;
9775   case Intrinsic::ppc_altivec_vcmpgtud:
9776     if (Subtarget.hasP8Altivec())
9777       CompareOpc = 711;
9778     else
9779       return false;
9780     break;
9781   }
9782   return true;
9783 }
9784 
9785 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9786 /// lower, do it, otherwise return null.
9787 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9788                                                    SelectionDAG &DAG) const {
9789   unsigned IntrinsicID =
9790     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9791 
9792   SDLoc dl(Op);
9793 
9794   if (IntrinsicID == Intrinsic::thread_pointer) {
9795     // Reads the thread pointer register, used for __builtin_thread_pointer.
9796     if (Subtarget.isPPC64())
9797       return DAG.getRegister(PPC::X13, MVT::i64);
9798     return DAG.getRegister(PPC::R2, MVT::i32);
9799   }
9800 
9801   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9802   // opcode number of the comparison.
9803   int CompareOpc;
9804   bool isDot;
9805   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9806     return SDValue();    // Don't custom lower most intrinsics.
9807 
9808   // If this is a non-dot comparison, make the VCMP node and we are done.
9809   if (!isDot) {
9810     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9811                               Op.getOperand(1), Op.getOperand(2),
9812                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9813     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9814   }
9815 
9816   // Create the PPCISD altivec 'dot' comparison node.
9817   SDValue Ops[] = {
9818     Op.getOperand(2),  // LHS
9819     Op.getOperand(3),  // RHS
9820     DAG.getConstant(CompareOpc, dl, MVT::i32)
9821   };
9822   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9823   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9824 
9825   // Now that we have the comparison, emit a copy from the CR to a GPR.
9826   // This is flagged to the above dot comparison.
9827   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9828                                 DAG.getRegister(PPC::CR6, MVT::i32),
9829                                 CompNode.getValue(1));
9830 
9831   // Unpack the result based on how the target uses it.
9832   unsigned BitNo;   // Bit # of CR6.
9833   bool InvertBit;   // Invert result?
9834   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9835   default:  // Can't happen, don't crash on invalid number though.
9836   case 0:   // Return the value of the EQ bit of CR6.
9837     BitNo = 0; InvertBit = false;
9838     break;
9839   case 1:   // Return the inverted value of the EQ bit of CR6.
9840     BitNo = 0; InvertBit = true;
9841     break;
9842   case 2:   // Return the value of the LT bit of CR6.
9843     BitNo = 2; InvertBit = false;
9844     break;
9845   case 3:   // Return the inverted value of the LT bit of CR6.
9846     BitNo = 2; InvertBit = true;
9847     break;
9848   }
9849 
9850   // Shift the bit into the low position.
9851   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9852                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9853   // Isolate the bit.
9854   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9855                       DAG.getConstant(1, dl, MVT::i32));
9856 
9857   // If we are supposed to, toggle the bit.
9858   if (InvertBit)
9859     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9860                         DAG.getConstant(1, dl, MVT::i32));
9861   return Flags;
9862 }
9863 
9864 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9865                                                SelectionDAG &DAG) const {
9866   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9867   // the beginning of the argument list.
9868   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9869   SDLoc DL(Op);
9870   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9871   case Intrinsic::ppc_cfence: {
9872     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9873     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9874     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9875                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9876                                                   Op.getOperand(ArgStart + 1)),
9877                                       Op.getOperand(0)),
9878                    0);
9879   }
9880   default:
9881     break;
9882   }
9883   return SDValue();
9884 }
9885 
9886 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9887   // Check for a DIV with the same operands as this REM.
9888   for (auto UI : Op.getOperand(1)->uses()) {
9889     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9890         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9891       if (UI->getOperand(0) == Op.getOperand(0) &&
9892           UI->getOperand(1) == Op.getOperand(1))
9893         return SDValue();
9894   }
9895   return Op;
9896 }
9897 
9898 // Lower scalar BSWAP64 to xxbrd.
9899 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9900   SDLoc dl(Op);
9901   // MTVSRDD
9902   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9903                    Op.getOperand(0));
9904   // XXBRD
9905   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
9906   // MFVSRD
9907   int VectorIndex = 0;
9908   if (Subtarget.isLittleEndian())
9909     VectorIndex = 1;
9910   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9911                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9912   return Op;
9913 }
9914 
9915 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9916 // compared to a value that is atomically loaded (atomic loads zero-extend).
9917 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9918                                                 SelectionDAG &DAG) const {
9919   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9920          "Expecting an atomic compare-and-swap here.");
9921   SDLoc dl(Op);
9922   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9923   EVT MemVT = AtomicNode->getMemoryVT();
9924   if (MemVT.getSizeInBits() >= 32)
9925     return Op;
9926 
9927   SDValue CmpOp = Op.getOperand(2);
9928   // If this is already correctly zero-extended, leave it alone.
9929   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9930   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9931     return Op;
9932 
9933   // Clear the high bits of the compare operand.
9934   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9935   SDValue NewCmpOp =
9936     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9937                 DAG.getConstant(MaskVal, dl, MVT::i32));
9938 
9939   // Replace the existing compare operand with the properly zero-extended one.
9940   SmallVector<SDValue, 4> Ops;
9941   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9942     Ops.push_back(AtomicNode->getOperand(i));
9943   Ops[2] = NewCmpOp;
9944   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9945   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9946   auto NodeTy =
9947     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9948   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9949 }
9950 
9951 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9952                                                  SelectionDAG &DAG) const {
9953   SDLoc dl(Op);
9954   // Create a stack slot that is 16-byte aligned.
9955   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9956   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9957   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9958   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9959 
9960   // Store the input value into Value#0 of the stack slot.
9961   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9962                                MachinePointerInfo());
9963   // Load it out.
9964   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9965 }
9966 
9967 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9968                                                   SelectionDAG &DAG) const {
9969   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9970          "Should only be called for ISD::INSERT_VECTOR_ELT");
9971 
9972   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9973   // We have legal lowering for constant indices but not for variable ones.
9974   if (!C)
9975     return SDValue();
9976 
9977   EVT VT = Op.getValueType();
9978   SDLoc dl(Op);
9979   SDValue V1 = Op.getOperand(0);
9980   SDValue V2 = Op.getOperand(1);
9981   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9982   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9983     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9984     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9985     unsigned InsertAtElement = C->getZExtValue();
9986     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9987     if (Subtarget.isLittleEndian()) {
9988       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9989     }
9990     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9991                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9992   }
9993   return Op;
9994 }
9995 
9996 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9997                                                    SelectionDAG &DAG) const {
9998   SDLoc dl(Op);
9999   SDNode *N = Op.getNode();
10000 
10001   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10002          "Unknown extract_vector_elt type");
10003 
10004   SDValue Value = N->getOperand(0);
10005 
10006   // The first part of this is like the store lowering except that we don't
10007   // need to track the chain.
10008 
10009   // The values are now known to be -1 (false) or 1 (true). To convert this
10010   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10011   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10012   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10013 
10014   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10015   // understand how to form the extending load.
10016   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10017 
10018   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10019 
10020   // Now convert to an integer and store.
10021   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10022     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10023     Value);
10024 
10025   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10026   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10027   MachinePointerInfo PtrInfo =
10028       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10029   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10030   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10031 
10032   SDValue StoreChain = DAG.getEntryNode();
10033   SDValue Ops[] = {StoreChain,
10034                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10035                    Value, FIdx};
10036   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10037 
10038   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10039     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10040 
10041   // Extract the value requested.
10042   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10043   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10044   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10045 
10046   SDValue IntVal =
10047       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10048 
10049   if (!Subtarget.useCRBits())
10050     return IntVal;
10051 
10052   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10053 }
10054 
10055 /// Lowering for QPX v4i1 loads
10056 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10057                                            SelectionDAG &DAG) const {
10058   SDLoc dl(Op);
10059   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10060   SDValue LoadChain = LN->getChain();
10061   SDValue BasePtr = LN->getBasePtr();
10062 
10063   if (Op.getValueType() == MVT::v4f64 ||
10064       Op.getValueType() == MVT::v4f32) {
10065     EVT MemVT = LN->getMemoryVT();
10066     unsigned Alignment = LN->getAlignment();
10067 
10068     // If this load is properly aligned, then it is legal.
10069     if (Alignment >= MemVT.getStoreSize())
10070       return Op;
10071 
10072     EVT ScalarVT = Op.getValueType().getScalarType(),
10073         ScalarMemVT = MemVT.getScalarType();
10074     unsigned Stride = ScalarMemVT.getStoreSize();
10075 
10076     SDValue Vals[4], LoadChains[4];
10077     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10078       SDValue Load;
10079       if (ScalarVT != ScalarMemVT)
10080         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10081                               BasePtr,
10082                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10083                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10084                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10085       else
10086         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10087                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10088                            MinAlign(Alignment, Idx * Stride),
10089                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10090 
10091       if (Idx == 0 && LN->isIndexed()) {
10092         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10093                "Unknown addressing mode on vector load");
10094         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10095                                   LN->getAddressingMode());
10096       }
10097 
10098       Vals[Idx] = Load;
10099       LoadChains[Idx] = Load.getValue(1);
10100 
10101       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10102                             DAG.getConstant(Stride, dl,
10103                                             BasePtr.getValueType()));
10104     }
10105 
10106     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10107     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10108 
10109     if (LN->isIndexed()) {
10110       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10111       return DAG.getMergeValues(RetOps, dl);
10112     }
10113 
10114     SDValue RetOps[] = { Value, TF };
10115     return DAG.getMergeValues(RetOps, dl);
10116   }
10117 
10118   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10119   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10120 
10121   // To lower v4i1 from a byte array, we load the byte elements of the
10122   // vector and then reuse the BUILD_VECTOR logic.
10123 
10124   SDValue VectElmts[4], VectElmtChains[4];
10125   for (unsigned i = 0; i < 4; ++i) {
10126     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10127     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10128 
10129     VectElmts[i] = DAG.getExtLoad(
10130         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10131         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10132         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10133     VectElmtChains[i] = VectElmts[i].getValue(1);
10134   }
10135 
10136   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10137   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10138 
10139   SDValue RVals[] = { Value, LoadChain };
10140   return DAG.getMergeValues(RVals, dl);
10141 }
10142 
10143 /// Lowering for QPX v4i1 stores
10144 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10145                                             SelectionDAG &DAG) const {
10146   SDLoc dl(Op);
10147   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10148   SDValue StoreChain = SN->getChain();
10149   SDValue BasePtr = SN->getBasePtr();
10150   SDValue Value = SN->getValue();
10151 
10152   if (Value.getValueType() == MVT::v4f64 ||
10153       Value.getValueType() == MVT::v4f32) {
10154     EVT MemVT = SN->getMemoryVT();
10155     unsigned Alignment = SN->getAlignment();
10156 
10157     // If this store is properly aligned, then it is legal.
10158     if (Alignment >= MemVT.getStoreSize())
10159       return Op;
10160 
10161     EVT ScalarVT = Value.getValueType().getScalarType(),
10162         ScalarMemVT = MemVT.getScalarType();
10163     unsigned Stride = ScalarMemVT.getStoreSize();
10164 
10165     SDValue Stores[4];
10166     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10167       SDValue Ex = DAG.getNode(
10168           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10169           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
10170       SDValue Store;
10171       if (ScalarVT != ScalarMemVT)
10172         Store =
10173             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10174                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10175                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10176                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10177       else
10178         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10179                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10180                              MinAlign(Alignment, Idx * Stride),
10181                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10182 
10183       if (Idx == 0 && SN->isIndexed()) {
10184         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10185                "Unknown addressing mode on vector store");
10186         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10187                                     SN->getAddressingMode());
10188       }
10189 
10190       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10191                             DAG.getConstant(Stride, dl,
10192                                             BasePtr.getValueType()));
10193       Stores[Idx] = Store;
10194     }
10195 
10196     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10197 
10198     if (SN->isIndexed()) {
10199       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10200       return DAG.getMergeValues(RetOps, dl);
10201     }
10202 
10203     return TF;
10204   }
10205 
10206   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10207   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10208 
10209   // The values are now known to be -1 (false) or 1 (true). To convert this
10210   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10211   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10212   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10213 
10214   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10215   // understand how to form the extending load.
10216   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10217 
10218   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10219 
10220   // Now convert to an integer and store.
10221   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10222     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10223     Value);
10224 
10225   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10226   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10227   MachinePointerInfo PtrInfo =
10228       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10229   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10230   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10231 
10232   SDValue Ops[] = {StoreChain,
10233                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10234                    Value, FIdx};
10235   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10236 
10237   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10238     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10239 
10240   // Move data into the byte array.
10241   SDValue Loads[4], LoadChains[4];
10242   for (unsigned i = 0; i < 4; ++i) {
10243     unsigned Offset = 4*i;
10244     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10245     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10246 
10247     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10248                            PtrInfo.getWithOffset(Offset));
10249     LoadChains[i] = Loads[i].getValue(1);
10250   }
10251 
10252   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10253 
10254   SDValue Stores[4];
10255   for (unsigned i = 0; i < 4; ++i) {
10256     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10257     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10258 
10259     Stores[i] = DAG.getTruncStore(
10260         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10261         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10262         SN->getAAInfo());
10263   }
10264 
10265   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10266 
10267   return StoreChain;
10268 }
10269 
10270 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10271   SDLoc dl(Op);
10272   if (Op.getValueType() == MVT::v4i32) {
10273     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10274 
10275     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10276     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10277 
10278     SDValue RHSSwap =   // = vrlw RHS, 16
10279       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10280 
10281     // Shrinkify inputs to v8i16.
10282     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10283     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10284     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10285 
10286     // Low parts multiplied together, generating 32-bit results (we ignore the
10287     // top parts).
10288     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10289                                         LHS, RHS, DAG, dl, MVT::v4i32);
10290 
10291     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10292                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10293     // Shift the high parts up 16 bits.
10294     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10295                               Neg16, DAG, dl);
10296     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10297   } else if (Op.getValueType() == MVT::v8i16) {
10298     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10299 
10300     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10301 
10302     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10303                             LHS, RHS, Zero, DAG, dl);
10304   } else if (Op.getValueType() == MVT::v16i8) {
10305     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10306     bool isLittleEndian = Subtarget.isLittleEndian();
10307 
10308     // Multiply the even 8-bit parts, producing 16-bit sums.
10309     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10310                                            LHS, RHS, DAG, dl, MVT::v8i16);
10311     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10312 
10313     // Multiply the odd 8-bit parts, producing 16-bit sums.
10314     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10315                                           LHS, RHS, DAG, dl, MVT::v8i16);
10316     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10317 
10318     // Merge the results together.  Because vmuleub and vmuloub are
10319     // instructions with a big-endian bias, we must reverse the
10320     // element numbering and reverse the meaning of "odd" and "even"
10321     // when generating little endian code.
10322     int Ops[16];
10323     for (unsigned i = 0; i != 8; ++i) {
10324       if (isLittleEndian) {
10325         Ops[i*2  ] = 2*i;
10326         Ops[i*2+1] = 2*i+16;
10327       } else {
10328         Ops[i*2  ] = 2*i+1;
10329         Ops[i*2+1] = 2*i+1+16;
10330       }
10331     }
10332     if (isLittleEndian)
10333       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10334     else
10335       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10336   } else {
10337     llvm_unreachable("Unknown mul to lower!");
10338   }
10339 }
10340 
10341 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10342 
10343   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10344 
10345   EVT VT = Op.getValueType();
10346   assert(VT.isVector() &&
10347          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10348   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10349           VT == MVT::v16i8) &&
10350          "Unexpected vector element type!");
10351   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10352          "Current subtarget doesn't support smax v2i64!");
10353 
10354   // For vector abs, it can be lowered to:
10355   // abs x
10356   // ==>
10357   // y = -x
10358   // smax(x, y)
10359 
10360   SDLoc dl(Op);
10361   SDValue X = Op.getOperand(0);
10362   SDValue Zero = DAG.getConstant(0, dl, VT);
10363   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10364 
10365   // SMAX patch https://reviews.llvm.org/D47332
10366   // hasn't landed yet, so use intrinsic first here.
10367   // TODO: Should use SMAX directly once SMAX patch landed
10368   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10369   if (VT == MVT::v2i64)
10370     BifID = Intrinsic::ppc_altivec_vmaxsd;
10371   else if (VT == MVT::v8i16)
10372     BifID = Intrinsic::ppc_altivec_vmaxsh;
10373   else if (VT == MVT::v16i8)
10374     BifID = Intrinsic::ppc_altivec_vmaxsb;
10375 
10376   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10377 }
10378 
10379 // Custom lowering for fpext vf32 to v2f64
10380 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10381 
10382   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10383          "Should only be called for ISD::FP_EXTEND");
10384 
10385   // FIXME: handle extends from half precision float vectors on P9.
10386   // We only want to custom lower an extend from v2f32 to v2f64.
10387   if (Op.getValueType() != MVT::v2f64 ||
10388       Op.getOperand(0).getValueType() != MVT::v2f32)
10389     return SDValue();
10390 
10391   SDLoc dl(Op);
10392   SDValue Op0 = Op.getOperand(0);
10393 
10394   switch (Op0.getOpcode()) {
10395   default:
10396     return SDValue();
10397   case ISD::EXTRACT_SUBVECTOR: {
10398     assert(Op0.getNumOperands() == 2 &&
10399            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10400            "Node should have 2 operands with second one being a constant!");
10401 
10402     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10403       return SDValue();
10404 
10405     // Custom lower is only done for high or low doubleword.
10406     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10407     if (Idx % 2 != 0)
10408       return SDValue();
10409 
10410     // Since input is v4f32, at this point Idx is either 0 or 2.
10411     // Shift to get the doubleword position we want.
10412     int DWord = Idx >> 1;
10413 
10414     // High and low word positions are different on little endian.
10415     if (Subtarget.isLittleEndian())
10416       DWord ^= 0x1;
10417 
10418     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10419                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10420   }
10421   case ISD::FADD:
10422   case ISD::FMUL:
10423   case ISD::FSUB: {
10424     SDValue NewLoad[2];
10425     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10426       // Ensure both input are loads.
10427       SDValue LdOp = Op0.getOperand(i);
10428       if (LdOp.getOpcode() != ISD::LOAD)
10429         return SDValue();
10430       // Generate new load node.
10431       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10432       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10433       NewLoad[i] = DAG.getMemIntrinsicNode(
10434           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10435           LD->getMemoryVT(), LD->getMemOperand());
10436     }
10437     SDValue NewOp =
10438         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10439                     NewLoad[1], Op0.getNode()->getFlags());
10440     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10441                        DAG.getConstant(0, dl, MVT::i32));
10442   }
10443   case ISD::LOAD: {
10444     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10445     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10446     SDValue NewLd = DAG.getMemIntrinsicNode(
10447         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10448         LD->getMemoryVT(), LD->getMemOperand());
10449     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10450                        DAG.getConstant(0, dl, MVT::i32));
10451   }
10452   }
10453   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10454 }
10455 
10456 /// LowerOperation - Provide custom lowering hooks for some operations.
10457 ///
10458 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10459   switch (Op.getOpcode()) {
10460   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10461   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10462   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10463   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10464   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10465   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10466   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10467   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10468   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10469 
10470   // Variable argument lowering.
10471   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10472   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10473   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10474 
10475   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10476   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10477   case ISD::GET_DYNAMIC_AREA_OFFSET:
10478     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10479 
10480   // Exception handling lowering.
10481   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10482   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10483   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10484 
10485   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10486   case ISD::STORE:              return LowerSTORE(Op, DAG);
10487   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10488   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10489   case ISD::FP_TO_UINT:
10490   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10491   case ISD::UINT_TO_FP:
10492   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10493   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10494 
10495   // Lower 64-bit shifts.
10496   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10497   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10498   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10499 
10500   // Vector-related lowering.
10501   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10502   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10503   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10504   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10505   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10506   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10507   case ISD::MUL:                return LowerMUL(Op, DAG);
10508   case ISD::ABS:                return LowerABS(Op, DAG);
10509   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10510 
10511   // For counter-based loop handling.
10512   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10513 
10514   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10515 
10516   // Frame & Return address.
10517   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10518   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10519 
10520   case ISD::INTRINSIC_VOID:
10521     return LowerINTRINSIC_VOID(Op, DAG);
10522   case ISD::SREM:
10523   case ISD::UREM:
10524     return LowerREM(Op, DAG);
10525   case ISD::BSWAP:
10526     return LowerBSWAP(Op, DAG);
10527   case ISD::ATOMIC_CMP_SWAP:
10528     return LowerATOMIC_CMP_SWAP(Op, DAG);
10529   }
10530 }
10531 
10532 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10533                                            SmallVectorImpl<SDValue>&Results,
10534                                            SelectionDAG &DAG) const {
10535   SDLoc dl(N);
10536   switch (N->getOpcode()) {
10537   default:
10538     llvm_unreachable("Do not know how to custom type legalize this operation!");
10539   case ISD::READCYCLECOUNTER: {
10540     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10541     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10542 
10543     Results.push_back(RTB);
10544     Results.push_back(RTB.getValue(1));
10545     Results.push_back(RTB.getValue(2));
10546     break;
10547   }
10548   case ISD::INTRINSIC_W_CHAIN: {
10549     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10550         Intrinsic::loop_decrement)
10551       break;
10552 
10553     assert(N->getValueType(0) == MVT::i1 &&
10554            "Unexpected result type for CTR decrement intrinsic");
10555     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10556                                  N->getValueType(0));
10557     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10558     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10559                                  N->getOperand(1));
10560 
10561     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10562     Results.push_back(NewInt.getValue(1));
10563     break;
10564   }
10565   case ISD::VAARG: {
10566     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10567       return;
10568 
10569     EVT VT = N->getValueType(0);
10570 
10571     if (VT == MVT::i64) {
10572       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10573 
10574       Results.push_back(NewNode);
10575       Results.push_back(NewNode.getValue(1));
10576     }
10577     return;
10578   }
10579   case ISD::FP_TO_SINT:
10580   case ISD::FP_TO_UINT:
10581     // LowerFP_TO_INT() can only handle f32 and f64.
10582     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10583       return;
10584     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10585     return;
10586   case ISD::TRUNCATE: {
10587     EVT TrgVT = N->getValueType(0);
10588     EVT OpVT = N->getOperand(0).getValueType();
10589     if (TrgVT.isVector() &&
10590         isOperationCustom(N->getOpcode(), TrgVT) &&
10591         OpVT.getSizeInBits() <= 128 &&
10592         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10593       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10594     return;
10595   }
10596   case ISD::BITCAST:
10597     // Don't handle bitcast here.
10598     return;
10599   case ISD::FP_EXTEND:
10600     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10601     if (Lowered)
10602       Results.push_back(Lowered);
10603     return;
10604   }
10605 }
10606 
10607 //===----------------------------------------------------------------------===//
10608 //  Other Lowering Code
10609 //===----------------------------------------------------------------------===//
10610 
10611 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10612   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10613   Function *Func = Intrinsic::getDeclaration(M, Id);
10614   return Builder.CreateCall(Func, {});
10615 }
10616 
10617 // The mappings for emitLeading/TrailingFence is taken from
10618 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10619 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10620                                                  Instruction *Inst,
10621                                                  AtomicOrdering Ord) const {
10622   if (Ord == AtomicOrdering::SequentiallyConsistent)
10623     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10624   if (isReleaseOrStronger(Ord))
10625     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10626   return nullptr;
10627 }
10628 
10629 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10630                                                   Instruction *Inst,
10631                                                   AtomicOrdering Ord) const {
10632   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10633     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10634     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10635     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10636     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10637       return Builder.CreateCall(
10638           Intrinsic::getDeclaration(
10639               Builder.GetInsertBlock()->getParent()->getParent(),
10640               Intrinsic::ppc_cfence, {Inst->getType()}),
10641           {Inst});
10642     // FIXME: Can use isync for rmw operation.
10643     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10644   }
10645   return nullptr;
10646 }
10647 
10648 MachineBasicBlock *
10649 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10650                                     unsigned AtomicSize,
10651                                     unsigned BinOpcode,
10652                                     unsigned CmpOpcode,
10653                                     unsigned CmpPred) const {
10654   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10655   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10656 
10657   auto LoadMnemonic = PPC::LDARX;
10658   auto StoreMnemonic = PPC::STDCX;
10659   switch (AtomicSize) {
10660   default:
10661     llvm_unreachable("Unexpected size of atomic entity");
10662   case 1:
10663     LoadMnemonic = PPC::LBARX;
10664     StoreMnemonic = PPC::STBCX;
10665     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10666     break;
10667   case 2:
10668     LoadMnemonic = PPC::LHARX;
10669     StoreMnemonic = PPC::STHCX;
10670     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10671     break;
10672   case 4:
10673     LoadMnemonic = PPC::LWARX;
10674     StoreMnemonic = PPC::STWCX;
10675     break;
10676   case 8:
10677     LoadMnemonic = PPC::LDARX;
10678     StoreMnemonic = PPC::STDCX;
10679     break;
10680   }
10681 
10682   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10683   MachineFunction *F = BB->getParent();
10684   MachineFunction::iterator It = ++BB->getIterator();
10685 
10686   Register dest = MI.getOperand(0).getReg();
10687   Register ptrA = MI.getOperand(1).getReg();
10688   Register ptrB = MI.getOperand(2).getReg();
10689   Register incr = MI.getOperand(3).getReg();
10690   DebugLoc dl = MI.getDebugLoc();
10691 
10692   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10693   MachineBasicBlock *loop2MBB =
10694     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10695   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10696   F->insert(It, loopMBB);
10697   if (CmpOpcode)
10698     F->insert(It, loop2MBB);
10699   F->insert(It, exitMBB);
10700   exitMBB->splice(exitMBB->begin(), BB,
10701                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10702   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10703 
10704   MachineRegisterInfo &RegInfo = F->getRegInfo();
10705   Register TmpReg = (!BinOpcode) ? incr :
10706     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10707                                            : &PPC::GPRCRegClass);
10708 
10709   //  thisMBB:
10710   //   ...
10711   //   fallthrough --> loopMBB
10712   BB->addSuccessor(loopMBB);
10713 
10714   //  loopMBB:
10715   //   l[wd]arx dest, ptr
10716   //   add r0, dest, incr
10717   //   st[wd]cx. r0, ptr
10718   //   bne- loopMBB
10719   //   fallthrough --> exitMBB
10720 
10721   // For max/min...
10722   //  loopMBB:
10723   //   l[wd]arx dest, ptr
10724   //   cmpl?[wd] incr, dest
10725   //   bgt exitMBB
10726   //  loop2MBB:
10727   //   st[wd]cx. dest, ptr
10728   //   bne- loopMBB
10729   //   fallthrough --> exitMBB
10730 
10731   BB = loopMBB;
10732   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10733     .addReg(ptrA).addReg(ptrB);
10734   if (BinOpcode)
10735     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10736   if (CmpOpcode) {
10737     // Signed comparisons of byte or halfword values must be sign-extended.
10738     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10739       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10740       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10741               ExtReg).addReg(dest);
10742       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10743         .addReg(incr).addReg(ExtReg);
10744     } else
10745       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10746         .addReg(incr).addReg(dest);
10747 
10748     BuildMI(BB, dl, TII->get(PPC::BCC))
10749       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10750     BB->addSuccessor(loop2MBB);
10751     BB->addSuccessor(exitMBB);
10752     BB = loop2MBB;
10753   }
10754   BuildMI(BB, dl, TII->get(StoreMnemonic))
10755     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10756   BuildMI(BB, dl, TII->get(PPC::BCC))
10757     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10758   BB->addSuccessor(loopMBB);
10759   BB->addSuccessor(exitMBB);
10760 
10761   //  exitMBB:
10762   //   ...
10763   BB = exitMBB;
10764   return BB;
10765 }
10766 
10767 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10768     MachineInstr &MI, MachineBasicBlock *BB,
10769     bool is8bit, // operation
10770     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10771   // If we support part-word atomic mnemonics, just use them
10772   if (Subtarget.hasPartwordAtomics())
10773     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10774                             CmpPred);
10775 
10776   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10777   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10778   // In 64 bit mode we have to use 64 bits for addresses, even though the
10779   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10780   // registers without caring whether they're 32 or 64, but here we're
10781   // doing actual arithmetic on the addresses.
10782   bool is64bit = Subtarget.isPPC64();
10783   bool isLittleEndian = Subtarget.isLittleEndian();
10784   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10785 
10786   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10787   MachineFunction *F = BB->getParent();
10788   MachineFunction::iterator It = ++BB->getIterator();
10789 
10790   Register dest = MI.getOperand(0).getReg();
10791   Register ptrA = MI.getOperand(1).getReg();
10792   Register ptrB = MI.getOperand(2).getReg();
10793   Register incr = MI.getOperand(3).getReg();
10794   DebugLoc dl = MI.getDebugLoc();
10795 
10796   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10797   MachineBasicBlock *loop2MBB =
10798       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10799   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10800   F->insert(It, loopMBB);
10801   if (CmpOpcode)
10802     F->insert(It, loop2MBB);
10803   F->insert(It, exitMBB);
10804   exitMBB->splice(exitMBB->begin(), BB,
10805                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10806   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10807 
10808   MachineRegisterInfo &RegInfo = F->getRegInfo();
10809   const TargetRegisterClass *RC =
10810       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10811   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10812 
10813   Register PtrReg = RegInfo.createVirtualRegister(RC);
10814   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10815   Register ShiftReg =
10816       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10817   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10818   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10819   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10820   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10821   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10822   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10823   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10824   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10825   Register Ptr1Reg;
10826   Register TmpReg =
10827       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10828 
10829   //  thisMBB:
10830   //   ...
10831   //   fallthrough --> loopMBB
10832   BB->addSuccessor(loopMBB);
10833 
10834   // The 4-byte load must be aligned, while a char or short may be
10835   // anywhere in the word.  Hence all this nasty bookkeeping code.
10836   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10837   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10838   //   xori shift, shift1, 24 [16]
10839   //   rlwinm ptr, ptr1, 0, 0, 29
10840   //   slw incr2, incr, shift
10841   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10842   //   slw mask, mask2, shift
10843   //  loopMBB:
10844   //   lwarx tmpDest, ptr
10845   //   add tmp, tmpDest, incr2
10846   //   andc tmp2, tmpDest, mask
10847   //   and tmp3, tmp, mask
10848   //   or tmp4, tmp3, tmp2
10849   //   stwcx. tmp4, ptr
10850   //   bne- loopMBB
10851   //   fallthrough --> exitMBB
10852   //   srw dest, tmpDest, shift
10853   if (ptrA != ZeroReg) {
10854     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10855     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10856         .addReg(ptrA)
10857         .addReg(ptrB);
10858   } else {
10859     Ptr1Reg = ptrB;
10860   }
10861   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10862   // mode.
10863   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10864       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10865       .addImm(3)
10866       .addImm(27)
10867       .addImm(is8bit ? 28 : 27);
10868   if (!isLittleEndian)
10869     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10870         .addReg(Shift1Reg)
10871         .addImm(is8bit ? 24 : 16);
10872   if (is64bit)
10873     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10874         .addReg(Ptr1Reg)
10875         .addImm(0)
10876         .addImm(61);
10877   else
10878     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10879         .addReg(Ptr1Reg)
10880         .addImm(0)
10881         .addImm(0)
10882         .addImm(29);
10883   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10884   if (is8bit)
10885     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10886   else {
10887     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10888     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10889         .addReg(Mask3Reg)
10890         .addImm(65535);
10891   }
10892   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10893       .addReg(Mask2Reg)
10894       .addReg(ShiftReg);
10895 
10896   BB = loopMBB;
10897   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10898       .addReg(ZeroReg)
10899       .addReg(PtrReg);
10900   if (BinOpcode)
10901     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10902         .addReg(Incr2Reg)
10903         .addReg(TmpDestReg);
10904   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10905       .addReg(TmpDestReg)
10906       .addReg(MaskReg);
10907   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10908   if (CmpOpcode) {
10909     // For unsigned comparisons, we can directly compare the shifted values.
10910     // For signed comparisons we shift and sign extend.
10911     Register SReg = RegInfo.createVirtualRegister(GPRC);
10912     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10913         .addReg(TmpDestReg)
10914         .addReg(MaskReg);
10915     unsigned ValueReg = SReg;
10916     unsigned CmpReg = Incr2Reg;
10917     if (CmpOpcode == PPC::CMPW) {
10918       ValueReg = RegInfo.createVirtualRegister(GPRC);
10919       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10920           .addReg(SReg)
10921           .addReg(ShiftReg);
10922       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10923       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10924           .addReg(ValueReg);
10925       ValueReg = ValueSReg;
10926       CmpReg = incr;
10927     }
10928     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10929         .addReg(CmpReg)
10930         .addReg(ValueReg);
10931     BuildMI(BB, dl, TII->get(PPC::BCC))
10932         .addImm(CmpPred)
10933         .addReg(PPC::CR0)
10934         .addMBB(exitMBB);
10935     BB->addSuccessor(loop2MBB);
10936     BB->addSuccessor(exitMBB);
10937     BB = loop2MBB;
10938   }
10939   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10940   BuildMI(BB, dl, TII->get(PPC::STWCX))
10941       .addReg(Tmp4Reg)
10942       .addReg(ZeroReg)
10943       .addReg(PtrReg);
10944   BuildMI(BB, dl, TII->get(PPC::BCC))
10945       .addImm(PPC::PRED_NE)
10946       .addReg(PPC::CR0)
10947       .addMBB(loopMBB);
10948   BB->addSuccessor(loopMBB);
10949   BB->addSuccessor(exitMBB);
10950 
10951   //  exitMBB:
10952   //   ...
10953   BB = exitMBB;
10954   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10955       .addReg(TmpDestReg)
10956       .addReg(ShiftReg);
10957   return BB;
10958 }
10959 
10960 llvm::MachineBasicBlock *
10961 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10962                                     MachineBasicBlock *MBB) const {
10963   DebugLoc DL = MI.getDebugLoc();
10964   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10965   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10966 
10967   MachineFunction *MF = MBB->getParent();
10968   MachineRegisterInfo &MRI = MF->getRegInfo();
10969 
10970   const BasicBlock *BB = MBB->getBasicBlock();
10971   MachineFunction::iterator I = ++MBB->getIterator();
10972 
10973   Register DstReg = MI.getOperand(0).getReg();
10974   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10975   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10976   Register mainDstReg = MRI.createVirtualRegister(RC);
10977   Register restoreDstReg = MRI.createVirtualRegister(RC);
10978 
10979   MVT PVT = getPointerTy(MF->getDataLayout());
10980   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10981          "Invalid Pointer Size!");
10982   // For v = setjmp(buf), we generate
10983   //
10984   // thisMBB:
10985   //  SjLjSetup mainMBB
10986   //  bl mainMBB
10987   //  v_restore = 1
10988   //  b sinkMBB
10989   //
10990   // mainMBB:
10991   //  buf[LabelOffset] = LR
10992   //  v_main = 0
10993   //
10994   // sinkMBB:
10995   //  v = phi(main, restore)
10996   //
10997 
10998   MachineBasicBlock *thisMBB = MBB;
10999   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11000   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11001   MF->insert(I, mainMBB);
11002   MF->insert(I, sinkMBB);
11003 
11004   MachineInstrBuilder MIB;
11005 
11006   // Transfer the remainder of BB and its successor edges to sinkMBB.
11007   sinkMBB->splice(sinkMBB->begin(), MBB,
11008                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11009   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11010 
11011   // Note that the structure of the jmp_buf used here is not compatible
11012   // with that used by libc, and is not designed to be. Specifically, it
11013   // stores only those 'reserved' registers that LLVM does not otherwise
11014   // understand how to spill. Also, by convention, by the time this
11015   // intrinsic is called, Clang has already stored the frame address in the
11016   // first slot of the buffer and stack address in the third. Following the
11017   // X86 target code, we'll store the jump address in the second slot. We also
11018   // need to save the TOC pointer (R2) to handle jumps between shared
11019   // libraries, and that will be stored in the fourth slot. The thread
11020   // identifier (R13) is not affected.
11021 
11022   // thisMBB:
11023   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11024   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11025   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11026 
11027   // Prepare IP either in reg.
11028   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11029   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11030   Register BufReg = MI.getOperand(1).getReg();
11031 
11032   if (Subtarget.is64BitELFABI()) {
11033     setUsesTOCBasePtr(*MBB->getParent());
11034     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11035               .addReg(PPC::X2)
11036               .addImm(TOCOffset)
11037               .addReg(BufReg)
11038               .cloneMemRefs(MI);
11039   }
11040 
11041   // Naked functions never have a base pointer, and so we use r1. For all
11042   // other functions, this decision must be delayed until during PEI.
11043   unsigned BaseReg;
11044   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11045     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11046   else
11047     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11048 
11049   MIB = BuildMI(*thisMBB, MI, DL,
11050                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11051             .addReg(BaseReg)
11052             .addImm(BPOffset)
11053             .addReg(BufReg)
11054             .cloneMemRefs(MI);
11055 
11056   // Setup
11057   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11058   MIB.addRegMask(TRI->getNoPreservedMask());
11059 
11060   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11061 
11062   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11063           .addMBB(mainMBB);
11064   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11065 
11066   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11067   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11068 
11069   // mainMBB:
11070   //  mainDstReg = 0
11071   MIB =
11072       BuildMI(mainMBB, DL,
11073               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11074 
11075   // Store IP
11076   if (Subtarget.isPPC64()) {
11077     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11078             .addReg(LabelReg)
11079             .addImm(LabelOffset)
11080             .addReg(BufReg);
11081   } else {
11082     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11083             .addReg(LabelReg)
11084             .addImm(LabelOffset)
11085             .addReg(BufReg);
11086   }
11087   MIB.cloneMemRefs(MI);
11088 
11089   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11090   mainMBB->addSuccessor(sinkMBB);
11091 
11092   // sinkMBB:
11093   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11094           TII->get(PPC::PHI), DstReg)
11095     .addReg(mainDstReg).addMBB(mainMBB)
11096     .addReg(restoreDstReg).addMBB(thisMBB);
11097 
11098   MI.eraseFromParent();
11099   return sinkMBB;
11100 }
11101 
11102 MachineBasicBlock *
11103 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11104                                      MachineBasicBlock *MBB) const {
11105   DebugLoc DL = MI.getDebugLoc();
11106   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11107 
11108   MachineFunction *MF = MBB->getParent();
11109   MachineRegisterInfo &MRI = MF->getRegInfo();
11110 
11111   MVT PVT = getPointerTy(MF->getDataLayout());
11112   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11113          "Invalid Pointer Size!");
11114 
11115   const TargetRegisterClass *RC =
11116     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11117   Register Tmp = MRI.createVirtualRegister(RC);
11118   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11119   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11120   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11121   unsigned BP =
11122       (PVT == MVT::i64)
11123           ? PPC::X30
11124           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11125                                                               : PPC::R30);
11126 
11127   MachineInstrBuilder MIB;
11128 
11129   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11130   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11131   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11132   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11133 
11134   Register BufReg = MI.getOperand(0).getReg();
11135 
11136   // Reload FP (the jumped-to function may not have had a
11137   // frame pointer, and if so, then its r31 will be restored
11138   // as necessary).
11139   if (PVT == MVT::i64) {
11140     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11141             .addImm(0)
11142             .addReg(BufReg);
11143   } else {
11144     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11145             .addImm(0)
11146             .addReg(BufReg);
11147   }
11148   MIB.cloneMemRefs(MI);
11149 
11150   // Reload IP
11151   if (PVT == MVT::i64) {
11152     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11153             .addImm(LabelOffset)
11154             .addReg(BufReg);
11155   } else {
11156     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11157             .addImm(LabelOffset)
11158             .addReg(BufReg);
11159   }
11160   MIB.cloneMemRefs(MI);
11161 
11162   // Reload SP
11163   if (PVT == MVT::i64) {
11164     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11165             .addImm(SPOffset)
11166             .addReg(BufReg);
11167   } else {
11168     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11169             .addImm(SPOffset)
11170             .addReg(BufReg);
11171   }
11172   MIB.cloneMemRefs(MI);
11173 
11174   // Reload BP
11175   if (PVT == MVT::i64) {
11176     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11177             .addImm(BPOffset)
11178             .addReg(BufReg);
11179   } else {
11180     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11181             .addImm(BPOffset)
11182             .addReg(BufReg);
11183   }
11184   MIB.cloneMemRefs(MI);
11185 
11186   // Reload TOC
11187   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11188     setUsesTOCBasePtr(*MBB->getParent());
11189     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11190               .addImm(TOCOffset)
11191               .addReg(BufReg)
11192               .cloneMemRefs(MI);
11193   }
11194 
11195   // Jump
11196   BuildMI(*MBB, MI, DL,
11197           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11198   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11199 
11200   MI.eraseFromParent();
11201   return MBB;
11202 }
11203 
11204 MachineBasicBlock *
11205 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11206                                                MachineBasicBlock *BB) const {
11207   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11208       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11209     if (Subtarget.is64BitELFABI() &&
11210         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11211       // Call lowering should have added an r2 operand to indicate a dependence
11212       // on the TOC base pointer value. It can't however, because there is no
11213       // way to mark the dependence as implicit there, and so the stackmap code
11214       // will confuse it with a regular operand. Instead, add the dependence
11215       // here.
11216       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11217     }
11218 
11219     return emitPatchPoint(MI, BB);
11220   }
11221 
11222   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11223       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11224     return emitEHSjLjSetJmp(MI, BB);
11225   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11226              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11227     return emitEHSjLjLongJmp(MI, BB);
11228   }
11229 
11230   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11231 
11232   // To "insert" these instructions we actually have to insert their
11233   // control-flow patterns.
11234   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11235   MachineFunction::iterator It = ++BB->getIterator();
11236 
11237   MachineFunction *F = BB->getParent();
11238 
11239   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11240       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11241       MI.getOpcode() == PPC::SELECT_I8) {
11242     SmallVector<MachineOperand, 2> Cond;
11243     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11244         MI.getOpcode() == PPC::SELECT_CC_I8)
11245       Cond.push_back(MI.getOperand(4));
11246     else
11247       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11248     Cond.push_back(MI.getOperand(1));
11249 
11250     DebugLoc dl = MI.getDebugLoc();
11251     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11252                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11253   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11254              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11255              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11256              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11257              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11258              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11259              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11260              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11261              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11262              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11263              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11264              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11265              MI.getOpcode() == PPC::SELECT_F4 ||
11266              MI.getOpcode() == PPC::SELECT_F8 ||
11267              MI.getOpcode() == PPC::SELECT_F16 ||
11268              MI.getOpcode() == PPC::SELECT_QFRC ||
11269              MI.getOpcode() == PPC::SELECT_QSRC ||
11270              MI.getOpcode() == PPC::SELECT_QBRC ||
11271              MI.getOpcode() == PPC::SELECT_SPE ||
11272              MI.getOpcode() == PPC::SELECT_SPE4 ||
11273              MI.getOpcode() == PPC::SELECT_VRRC ||
11274              MI.getOpcode() == PPC::SELECT_VSFRC ||
11275              MI.getOpcode() == PPC::SELECT_VSSRC ||
11276              MI.getOpcode() == PPC::SELECT_VSRC) {
11277     // The incoming instruction knows the destination vreg to set, the
11278     // condition code register to branch on, the true/false values to
11279     // select between, and a branch opcode to use.
11280 
11281     //  thisMBB:
11282     //  ...
11283     //   TrueVal = ...
11284     //   cmpTY ccX, r1, r2
11285     //   bCC copy1MBB
11286     //   fallthrough --> copy0MBB
11287     MachineBasicBlock *thisMBB = BB;
11288     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11289     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11290     DebugLoc dl = MI.getDebugLoc();
11291     F->insert(It, copy0MBB);
11292     F->insert(It, sinkMBB);
11293 
11294     // Transfer the remainder of BB and its successor edges to sinkMBB.
11295     sinkMBB->splice(sinkMBB->begin(), BB,
11296                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11297     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11298 
11299     // Next, add the true and fallthrough blocks as its successors.
11300     BB->addSuccessor(copy0MBB);
11301     BB->addSuccessor(sinkMBB);
11302 
11303     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11304         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11305         MI.getOpcode() == PPC::SELECT_F16 ||
11306         MI.getOpcode() == PPC::SELECT_SPE4 ||
11307         MI.getOpcode() == PPC::SELECT_SPE ||
11308         MI.getOpcode() == PPC::SELECT_QFRC ||
11309         MI.getOpcode() == PPC::SELECT_QSRC ||
11310         MI.getOpcode() == PPC::SELECT_QBRC ||
11311         MI.getOpcode() == PPC::SELECT_VRRC ||
11312         MI.getOpcode() == PPC::SELECT_VSFRC ||
11313         MI.getOpcode() == PPC::SELECT_VSSRC ||
11314         MI.getOpcode() == PPC::SELECT_VSRC) {
11315       BuildMI(BB, dl, TII->get(PPC::BC))
11316           .addReg(MI.getOperand(1).getReg())
11317           .addMBB(sinkMBB);
11318     } else {
11319       unsigned SelectPred = MI.getOperand(4).getImm();
11320       BuildMI(BB, dl, TII->get(PPC::BCC))
11321           .addImm(SelectPred)
11322           .addReg(MI.getOperand(1).getReg())
11323           .addMBB(sinkMBB);
11324     }
11325 
11326     //  copy0MBB:
11327     //   %FalseValue = ...
11328     //   # fallthrough to sinkMBB
11329     BB = copy0MBB;
11330 
11331     // Update machine-CFG edges
11332     BB->addSuccessor(sinkMBB);
11333 
11334     //  sinkMBB:
11335     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11336     //  ...
11337     BB = sinkMBB;
11338     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11339         .addReg(MI.getOperand(3).getReg())
11340         .addMBB(copy0MBB)
11341         .addReg(MI.getOperand(2).getReg())
11342         .addMBB(thisMBB);
11343   } else if (MI.getOpcode() == PPC::ReadTB) {
11344     // To read the 64-bit time-base register on a 32-bit target, we read the
11345     // two halves. Should the counter have wrapped while it was being read, we
11346     // need to try again.
11347     // ...
11348     // readLoop:
11349     // mfspr Rx,TBU # load from TBU
11350     // mfspr Ry,TB  # load from TB
11351     // mfspr Rz,TBU # load from TBU
11352     // cmpw crX,Rx,Rz # check if 'old'='new'
11353     // bne readLoop   # branch if they're not equal
11354     // ...
11355 
11356     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11357     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11358     DebugLoc dl = MI.getDebugLoc();
11359     F->insert(It, readMBB);
11360     F->insert(It, sinkMBB);
11361 
11362     // Transfer the remainder of BB and its successor edges to sinkMBB.
11363     sinkMBB->splice(sinkMBB->begin(), BB,
11364                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11365     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11366 
11367     BB->addSuccessor(readMBB);
11368     BB = readMBB;
11369 
11370     MachineRegisterInfo &RegInfo = F->getRegInfo();
11371     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11372     Register LoReg = MI.getOperand(0).getReg();
11373     Register HiReg = MI.getOperand(1).getReg();
11374 
11375     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11376     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11377     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11378 
11379     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11380 
11381     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11382         .addReg(HiReg)
11383         .addReg(ReadAgainReg);
11384     BuildMI(BB, dl, TII->get(PPC::BCC))
11385         .addImm(PPC::PRED_NE)
11386         .addReg(CmpReg)
11387         .addMBB(readMBB);
11388 
11389     BB->addSuccessor(readMBB);
11390     BB->addSuccessor(sinkMBB);
11391   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11392     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11393   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11394     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11395   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11396     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11397   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11398     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11399 
11400   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11401     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11402   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11403     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11404   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11405     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11406   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11407     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11408 
11409   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11410     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11411   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11412     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11413   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11414     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11415   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11416     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11417 
11418   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11419     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11420   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11421     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11422   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11423     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11424   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11425     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11426 
11427   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11428     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11429   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11430     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11431   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11432     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11433   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11434     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11435 
11436   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11437     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11438   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11439     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11440   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11441     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11442   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11443     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11444 
11445   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11446     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11447   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11448     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11449   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11450     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11451   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11452     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11453 
11454   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11455     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11456   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11457     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11458   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11459     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11460   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11461     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11462 
11463   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11464     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11465   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11466     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11467   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11468     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11469   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11470     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11471 
11472   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11473     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11474   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11475     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11476   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11477     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11478   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11479     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11480 
11481   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11482     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11483   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11484     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11485   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11486     BB = EmitAtomicBinary(MI, BB, 4, 0);
11487   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11488     BB = EmitAtomicBinary(MI, BB, 8, 0);
11489   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11490            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11491            (Subtarget.hasPartwordAtomics() &&
11492             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11493            (Subtarget.hasPartwordAtomics() &&
11494             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11495     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11496 
11497     auto LoadMnemonic = PPC::LDARX;
11498     auto StoreMnemonic = PPC::STDCX;
11499     switch (MI.getOpcode()) {
11500     default:
11501       llvm_unreachable("Compare and swap of unknown size");
11502     case PPC::ATOMIC_CMP_SWAP_I8:
11503       LoadMnemonic = PPC::LBARX;
11504       StoreMnemonic = PPC::STBCX;
11505       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11506       break;
11507     case PPC::ATOMIC_CMP_SWAP_I16:
11508       LoadMnemonic = PPC::LHARX;
11509       StoreMnemonic = PPC::STHCX;
11510       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11511       break;
11512     case PPC::ATOMIC_CMP_SWAP_I32:
11513       LoadMnemonic = PPC::LWARX;
11514       StoreMnemonic = PPC::STWCX;
11515       break;
11516     case PPC::ATOMIC_CMP_SWAP_I64:
11517       LoadMnemonic = PPC::LDARX;
11518       StoreMnemonic = PPC::STDCX;
11519       break;
11520     }
11521     Register dest = MI.getOperand(0).getReg();
11522     Register ptrA = MI.getOperand(1).getReg();
11523     Register ptrB = MI.getOperand(2).getReg();
11524     Register oldval = MI.getOperand(3).getReg();
11525     Register newval = MI.getOperand(4).getReg();
11526     DebugLoc dl = MI.getDebugLoc();
11527 
11528     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11529     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11530     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11531     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11532     F->insert(It, loop1MBB);
11533     F->insert(It, loop2MBB);
11534     F->insert(It, midMBB);
11535     F->insert(It, exitMBB);
11536     exitMBB->splice(exitMBB->begin(), BB,
11537                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11538     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11539 
11540     //  thisMBB:
11541     //   ...
11542     //   fallthrough --> loopMBB
11543     BB->addSuccessor(loop1MBB);
11544 
11545     // loop1MBB:
11546     //   l[bhwd]arx dest, ptr
11547     //   cmp[wd] dest, oldval
11548     //   bne- midMBB
11549     // loop2MBB:
11550     //   st[bhwd]cx. newval, ptr
11551     //   bne- loopMBB
11552     //   b exitBB
11553     // midMBB:
11554     //   st[bhwd]cx. dest, ptr
11555     // exitBB:
11556     BB = loop1MBB;
11557     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11558     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11559         .addReg(oldval)
11560         .addReg(dest);
11561     BuildMI(BB, dl, TII->get(PPC::BCC))
11562         .addImm(PPC::PRED_NE)
11563         .addReg(PPC::CR0)
11564         .addMBB(midMBB);
11565     BB->addSuccessor(loop2MBB);
11566     BB->addSuccessor(midMBB);
11567 
11568     BB = loop2MBB;
11569     BuildMI(BB, dl, TII->get(StoreMnemonic))
11570         .addReg(newval)
11571         .addReg(ptrA)
11572         .addReg(ptrB);
11573     BuildMI(BB, dl, TII->get(PPC::BCC))
11574         .addImm(PPC::PRED_NE)
11575         .addReg(PPC::CR0)
11576         .addMBB(loop1MBB);
11577     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11578     BB->addSuccessor(loop1MBB);
11579     BB->addSuccessor(exitMBB);
11580 
11581     BB = midMBB;
11582     BuildMI(BB, dl, TII->get(StoreMnemonic))
11583         .addReg(dest)
11584         .addReg(ptrA)
11585         .addReg(ptrB);
11586     BB->addSuccessor(exitMBB);
11587 
11588     //  exitMBB:
11589     //   ...
11590     BB = exitMBB;
11591   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11592              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11593     // We must use 64-bit registers for addresses when targeting 64-bit,
11594     // since we're actually doing arithmetic on them.  Other registers
11595     // can be 32-bit.
11596     bool is64bit = Subtarget.isPPC64();
11597     bool isLittleEndian = Subtarget.isLittleEndian();
11598     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11599 
11600     Register dest = MI.getOperand(0).getReg();
11601     Register ptrA = MI.getOperand(1).getReg();
11602     Register ptrB = MI.getOperand(2).getReg();
11603     Register oldval = MI.getOperand(3).getReg();
11604     Register newval = MI.getOperand(4).getReg();
11605     DebugLoc dl = MI.getDebugLoc();
11606 
11607     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11608     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11609     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11610     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11611     F->insert(It, loop1MBB);
11612     F->insert(It, loop2MBB);
11613     F->insert(It, midMBB);
11614     F->insert(It, exitMBB);
11615     exitMBB->splice(exitMBB->begin(), BB,
11616                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11617     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11618 
11619     MachineRegisterInfo &RegInfo = F->getRegInfo();
11620     const TargetRegisterClass *RC =
11621         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11622     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11623 
11624     Register PtrReg = RegInfo.createVirtualRegister(RC);
11625     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11626     Register ShiftReg =
11627         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11628     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11629     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11630     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11631     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11632     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11633     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11634     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11635     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11636     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11637     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11638     Register Ptr1Reg;
11639     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11640     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11641     //  thisMBB:
11642     //   ...
11643     //   fallthrough --> loopMBB
11644     BB->addSuccessor(loop1MBB);
11645 
11646     // The 4-byte load must be aligned, while a char or short may be
11647     // anywhere in the word.  Hence all this nasty bookkeeping code.
11648     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11649     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11650     //   xori shift, shift1, 24 [16]
11651     //   rlwinm ptr, ptr1, 0, 0, 29
11652     //   slw newval2, newval, shift
11653     //   slw oldval2, oldval,shift
11654     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11655     //   slw mask, mask2, shift
11656     //   and newval3, newval2, mask
11657     //   and oldval3, oldval2, mask
11658     // loop1MBB:
11659     //   lwarx tmpDest, ptr
11660     //   and tmp, tmpDest, mask
11661     //   cmpw tmp, oldval3
11662     //   bne- midMBB
11663     // loop2MBB:
11664     //   andc tmp2, tmpDest, mask
11665     //   or tmp4, tmp2, newval3
11666     //   stwcx. tmp4, ptr
11667     //   bne- loop1MBB
11668     //   b exitBB
11669     // midMBB:
11670     //   stwcx. tmpDest, ptr
11671     // exitBB:
11672     //   srw dest, tmpDest, shift
11673     if (ptrA != ZeroReg) {
11674       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11675       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11676           .addReg(ptrA)
11677           .addReg(ptrB);
11678     } else {
11679       Ptr1Reg = ptrB;
11680     }
11681 
11682     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11683     // mode.
11684     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11685         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11686         .addImm(3)
11687         .addImm(27)
11688         .addImm(is8bit ? 28 : 27);
11689     if (!isLittleEndian)
11690       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11691           .addReg(Shift1Reg)
11692           .addImm(is8bit ? 24 : 16);
11693     if (is64bit)
11694       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11695           .addReg(Ptr1Reg)
11696           .addImm(0)
11697           .addImm(61);
11698     else
11699       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11700           .addReg(Ptr1Reg)
11701           .addImm(0)
11702           .addImm(0)
11703           .addImm(29);
11704     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11705         .addReg(newval)
11706         .addReg(ShiftReg);
11707     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11708         .addReg(oldval)
11709         .addReg(ShiftReg);
11710     if (is8bit)
11711       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11712     else {
11713       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11714       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11715           .addReg(Mask3Reg)
11716           .addImm(65535);
11717     }
11718     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11719         .addReg(Mask2Reg)
11720         .addReg(ShiftReg);
11721     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11722         .addReg(NewVal2Reg)
11723         .addReg(MaskReg);
11724     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11725         .addReg(OldVal2Reg)
11726         .addReg(MaskReg);
11727 
11728     BB = loop1MBB;
11729     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11730         .addReg(ZeroReg)
11731         .addReg(PtrReg);
11732     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11733         .addReg(TmpDestReg)
11734         .addReg(MaskReg);
11735     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11736         .addReg(TmpReg)
11737         .addReg(OldVal3Reg);
11738     BuildMI(BB, dl, TII->get(PPC::BCC))
11739         .addImm(PPC::PRED_NE)
11740         .addReg(PPC::CR0)
11741         .addMBB(midMBB);
11742     BB->addSuccessor(loop2MBB);
11743     BB->addSuccessor(midMBB);
11744 
11745     BB = loop2MBB;
11746     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11747         .addReg(TmpDestReg)
11748         .addReg(MaskReg);
11749     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11750         .addReg(Tmp2Reg)
11751         .addReg(NewVal3Reg);
11752     BuildMI(BB, dl, TII->get(PPC::STWCX))
11753         .addReg(Tmp4Reg)
11754         .addReg(ZeroReg)
11755         .addReg(PtrReg);
11756     BuildMI(BB, dl, TII->get(PPC::BCC))
11757         .addImm(PPC::PRED_NE)
11758         .addReg(PPC::CR0)
11759         .addMBB(loop1MBB);
11760     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11761     BB->addSuccessor(loop1MBB);
11762     BB->addSuccessor(exitMBB);
11763 
11764     BB = midMBB;
11765     BuildMI(BB, dl, TII->get(PPC::STWCX))
11766         .addReg(TmpDestReg)
11767         .addReg(ZeroReg)
11768         .addReg(PtrReg);
11769     BB->addSuccessor(exitMBB);
11770 
11771     //  exitMBB:
11772     //   ...
11773     BB = exitMBB;
11774     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11775         .addReg(TmpReg)
11776         .addReg(ShiftReg);
11777   } else if (MI.getOpcode() == PPC::FADDrtz) {
11778     // This pseudo performs an FADD with rounding mode temporarily forced
11779     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11780     // is not modeled at the SelectionDAG level.
11781     Register Dest = MI.getOperand(0).getReg();
11782     Register Src1 = MI.getOperand(1).getReg();
11783     Register Src2 = MI.getOperand(2).getReg();
11784     DebugLoc dl = MI.getDebugLoc();
11785 
11786     MachineRegisterInfo &RegInfo = F->getRegInfo();
11787     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11788 
11789     // Save FPSCR value.
11790     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11791 
11792     // Set rounding mode to round-to-zero.
11793     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11794     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11795 
11796     // Perform addition.
11797     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11798 
11799     // Restore FPSCR value.
11800     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11801   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11802              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11803              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11804              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11805     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11806                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11807                           ? PPC::ANDI8_rec
11808                           : PPC::ANDI_rec;
11809     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11810                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11811 
11812     MachineRegisterInfo &RegInfo = F->getRegInfo();
11813     Register Dest = RegInfo.createVirtualRegister(
11814         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11815 
11816     DebugLoc Dl = MI.getDebugLoc();
11817     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11818         .addReg(MI.getOperand(1).getReg())
11819         .addImm(1);
11820     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11821             MI.getOperand(0).getReg())
11822         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11823   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11824     DebugLoc Dl = MI.getDebugLoc();
11825     MachineRegisterInfo &RegInfo = F->getRegInfo();
11826     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11827     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11828     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11829             MI.getOperand(0).getReg())
11830         .addReg(CRReg);
11831   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11832     DebugLoc Dl = MI.getDebugLoc();
11833     unsigned Imm = MI.getOperand(1).getImm();
11834     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11835     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11836             MI.getOperand(0).getReg())
11837         .addReg(PPC::CR0EQ);
11838   } else if (MI.getOpcode() == PPC::SETRNDi) {
11839     DebugLoc dl = MI.getDebugLoc();
11840     Register OldFPSCRReg = MI.getOperand(0).getReg();
11841 
11842     // Save FPSCR value.
11843     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11844 
11845     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11846     // the following settings:
11847     //   00 Round to nearest
11848     //   01 Round to 0
11849     //   10 Round to +inf
11850     //   11 Round to -inf
11851 
11852     // When the operand is immediate, using the two least significant bits of
11853     // the immediate to set the bits 62:63 of FPSCR.
11854     unsigned Mode = MI.getOperand(1).getImm();
11855     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11856       .addImm(31);
11857 
11858     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11859       .addImm(30);
11860   } else if (MI.getOpcode() == PPC::SETRND) {
11861     DebugLoc dl = MI.getDebugLoc();
11862 
11863     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11864     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11865     // If the target doesn't have DirectMove, we should use stack to do the
11866     // conversion, because the target doesn't have the instructions like mtvsrd
11867     // or mfvsrd to do this conversion directly.
11868     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11869       if (Subtarget.hasDirectMove()) {
11870         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11871           .addReg(SrcReg);
11872       } else {
11873         // Use stack to do the register copy.
11874         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11875         MachineRegisterInfo &RegInfo = F->getRegInfo();
11876         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11877         if (RC == &PPC::F8RCRegClass) {
11878           // Copy register from F8RCRegClass to G8RCRegclass.
11879           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11880                  "Unsupported RegClass.");
11881 
11882           StoreOp = PPC::STFD;
11883           LoadOp = PPC::LD;
11884         } else {
11885           // Copy register from G8RCRegClass to F8RCRegclass.
11886           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11887                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11888                  "Unsupported RegClass.");
11889         }
11890 
11891         MachineFrameInfo &MFI = F->getFrameInfo();
11892         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11893 
11894         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11895           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11896           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11897           MFI.getObjectAlignment(FrameIdx));
11898 
11899         // Store the SrcReg into the stack.
11900         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11901           .addReg(SrcReg)
11902           .addImm(0)
11903           .addFrameIndex(FrameIdx)
11904           .addMemOperand(MMOStore);
11905 
11906         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11907           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11908           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11909           MFI.getObjectAlignment(FrameIdx));
11910 
11911         // Load from the stack where SrcReg is stored, and save to DestReg,
11912         // so we have done the RegClass conversion from RegClass::SrcReg to
11913         // RegClass::DestReg.
11914         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11915           .addImm(0)
11916           .addFrameIndex(FrameIdx)
11917           .addMemOperand(MMOLoad);
11918       }
11919     };
11920 
11921     Register OldFPSCRReg = MI.getOperand(0).getReg();
11922 
11923     // Save FPSCR value.
11924     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11925 
11926     // When the operand is gprc register, use two least significant bits of the
11927     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11928     //
11929     // copy OldFPSCRTmpReg, OldFPSCRReg
11930     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11931     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11932     // copy NewFPSCRReg, NewFPSCRTmpReg
11933     // mtfsf 255, NewFPSCRReg
11934     MachineOperand SrcOp = MI.getOperand(1);
11935     MachineRegisterInfo &RegInfo = F->getRegInfo();
11936     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11937 
11938     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11939 
11940     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11941     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11942 
11943     // The first operand of INSERT_SUBREG should be a register which has
11944     // subregisters, we only care about its RegClass, so we should use an
11945     // IMPLICIT_DEF register.
11946     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11947     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11948       .addReg(ImDefReg)
11949       .add(SrcOp)
11950       .addImm(1);
11951 
11952     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11953     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11954       .addReg(OldFPSCRTmpReg)
11955       .addReg(ExtSrcReg)
11956       .addImm(0)
11957       .addImm(62);
11958 
11959     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11960     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11961 
11962     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11963     // bits of FPSCR.
11964     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11965       .addImm(255)
11966       .addReg(NewFPSCRReg)
11967       .addImm(0)
11968       .addImm(0);
11969   } else {
11970     llvm_unreachable("Unexpected instr type to insert");
11971   }
11972 
11973   MI.eraseFromParent(); // The pseudo instruction is gone now.
11974   return BB;
11975 }
11976 
11977 //===----------------------------------------------------------------------===//
11978 // Target Optimization Hooks
11979 //===----------------------------------------------------------------------===//
11980 
11981 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11982   // For the estimates, convergence is quadratic, so we essentially double the
11983   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11984   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11985   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11986   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11987   if (VT.getScalarType() == MVT::f64)
11988     RefinementSteps++;
11989   return RefinementSteps;
11990 }
11991 
11992 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11993                                            int Enabled, int &RefinementSteps,
11994                                            bool &UseOneConstNR,
11995                                            bool Reciprocal) const {
11996   EVT VT = Operand.getValueType();
11997   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11998       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11999       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12000       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12001       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12002       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12003     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12004       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12005 
12006     // The Newton-Raphson computation with a single constant does not provide
12007     // enough accuracy on some CPUs.
12008     UseOneConstNR = !Subtarget.needsTwoConstNR();
12009     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12010   }
12011   return SDValue();
12012 }
12013 
12014 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12015                                             int Enabled,
12016                                             int &RefinementSteps) const {
12017   EVT VT = Operand.getValueType();
12018   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12019       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12020       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12021       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12022       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12023       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12024     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12025       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12026     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12027   }
12028   return SDValue();
12029 }
12030 
12031 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12032   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12033   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12034   // enabled for division), this functionality is redundant with the default
12035   // combiner logic (once the division -> reciprocal/multiply transformation
12036   // has taken place). As a result, this matters more for older cores than for
12037   // newer ones.
12038 
12039   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12040   // reciprocal if there are two or more FDIVs (for embedded cores with only
12041   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12042   switch (Subtarget.getCPUDirective()) {
12043   default:
12044     return 3;
12045   case PPC::DIR_440:
12046   case PPC::DIR_A2:
12047   case PPC::DIR_E500:
12048   case PPC::DIR_E500mc:
12049   case PPC::DIR_E5500:
12050     return 2;
12051   }
12052 }
12053 
12054 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12055 // collapsed, and so we need to look through chains of them.
12056 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12057                                      int64_t& Offset, SelectionDAG &DAG) {
12058   if (DAG.isBaseWithConstantOffset(Loc)) {
12059     Base = Loc.getOperand(0);
12060     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12061 
12062     // The base might itself be a base plus an offset, and if so, accumulate
12063     // that as well.
12064     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12065   }
12066 }
12067 
12068 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12069                             unsigned Bytes, int Dist,
12070                             SelectionDAG &DAG) {
12071   if (VT.getSizeInBits() / 8 != Bytes)
12072     return false;
12073 
12074   SDValue BaseLoc = Base->getBasePtr();
12075   if (Loc.getOpcode() == ISD::FrameIndex) {
12076     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12077       return false;
12078     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12079     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12080     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12081     int FS  = MFI.getObjectSize(FI);
12082     int BFS = MFI.getObjectSize(BFI);
12083     if (FS != BFS || FS != (int)Bytes) return false;
12084     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12085   }
12086 
12087   SDValue Base1 = Loc, Base2 = BaseLoc;
12088   int64_t Offset1 = 0, Offset2 = 0;
12089   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12090   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12091   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12092     return true;
12093 
12094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12095   const GlobalValue *GV1 = nullptr;
12096   const GlobalValue *GV2 = nullptr;
12097   Offset1 = 0;
12098   Offset2 = 0;
12099   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12100   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12101   if (isGA1 && isGA2 && GV1 == GV2)
12102     return Offset1 == (Offset2 + Dist*Bytes);
12103   return false;
12104 }
12105 
12106 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12107 // not enforce equality of the chain operands.
12108 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12109                             unsigned Bytes, int Dist,
12110                             SelectionDAG &DAG) {
12111   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12112     EVT VT = LS->getMemoryVT();
12113     SDValue Loc = LS->getBasePtr();
12114     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12115   }
12116 
12117   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12118     EVT VT;
12119     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12120     default: return false;
12121     case Intrinsic::ppc_qpx_qvlfd:
12122     case Intrinsic::ppc_qpx_qvlfda:
12123       VT = MVT::v4f64;
12124       break;
12125     case Intrinsic::ppc_qpx_qvlfs:
12126     case Intrinsic::ppc_qpx_qvlfsa:
12127       VT = MVT::v4f32;
12128       break;
12129     case Intrinsic::ppc_qpx_qvlfcd:
12130     case Intrinsic::ppc_qpx_qvlfcda:
12131       VT = MVT::v2f64;
12132       break;
12133     case Intrinsic::ppc_qpx_qvlfcs:
12134     case Intrinsic::ppc_qpx_qvlfcsa:
12135       VT = MVT::v2f32;
12136       break;
12137     case Intrinsic::ppc_qpx_qvlfiwa:
12138     case Intrinsic::ppc_qpx_qvlfiwz:
12139     case Intrinsic::ppc_altivec_lvx:
12140     case Intrinsic::ppc_altivec_lvxl:
12141     case Intrinsic::ppc_vsx_lxvw4x:
12142     case Intrinsic::ppc_vsx_lxvw4x_be:
12143       VT = MVT::v4i32;
12144       break;
12145     case Intrinsic::ppc_vsx_lxvd2x:
12146     case Intrinsic::ppc_vsx_lxvd2x_be:
12147       VT = MVT::v2f64;
12148       break;
12149     case Intrinsic::ppc_altivec_lvebx:
12150       VT = MVT::i8;
12151       break;
12152     case Intrinsic::ppc_altivec_lvehx:
12153       VT = MVT::i16;
12154       break;
12155     case Intrinsic::ppc_altivec_lvewx:
12156       VT = MVT::i32;
12157       break;
12158     }
12159 
12160     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12161   }
12162 
12163   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12164     EVT VT;
12165     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12166     default: return false;
12167     case Intrinsic::ppc_qpx_qvstfd:
12168     case Intrinsic::ppc_qpx_qvstfda:
12169       VT = MVT::v4f64;
12170       break;
12171     case Intrinsic::ppc_qpx_qvstfs:
12172     case Intrinsic::ppc_qpx_qvstfsa:
12173       VT = MVT::v4f32;
12174       break;
12175     case Intrinsic::ppc_qpx_qvstfcd:
12176     case Intrinsic::ppc_qpx_qvstfcda:
12177       VT = MVT::v2f64;
12178       break;
12179     case Intrinsic::ppc_qpx_qvstfcs:
12180     case Intrinsic::ppc_qpx_qvstfcsa:
12181       VT = MVT::v2f32;
12182       break;
12183     case Intrinsic::ppc_qpx_qvstfiw:
12184     case Intrinsic::ppc_qpx_qvstfiwa:
12185     case Intrinsic::ppc_altivec_stvx:
12186     case Intrinsic::ppc_altivec_stvxl:
12187     case Intrinsic::ppc_vsx_stxvw4x:
12188       VT = MVT::v4i32;
12189       break;
12190     case Intrinsic::ppc_vsx_stxvd2x:
12191       VT = MVT::v2f64;
12192       break;
12193     case Intrinsic::ppc_vsx_stxvw4x_be:
12194       VT = MVT::v4i32;
12195       break;
12196     case Intrinsic::ppc_vsx_stxvd2x_be:
12197       VT = MVT::v2f64;
12198       break;
12199     case Intrinsic::ppc_altivec_stvebx:
12200       VT = MVT::i8;
12201       break;
12202     case Intrinsic::ppc_altivec_stvehx:
12203       VT = MVT::i16;
12204       break;
12205     case Intrinsic::ppc_altivec_stvewx:
12206       VT = MVT::i32;
12207       break;
12208     }
12209 
12210     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12211   }
12212 
12213   return false;
12214 }
12215 
12216 // Return true is there is a nearyby consecutive load to the one provided
12217 // (regardless of alignment). We search up and down the chain, looking though
12218 // token factors and other loads (but nothing else). As a result, a true result
12219 // indicates that it is safe to create a new consecutive load adjacent to the
12220 // load provided.
12221 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12222   SDValue Chain = LD->getChain();
12223   EVT VT = LD->getMemoryVT();
12224 
12225   SmallSet<SDNode *, 16> LoadRoots;
12226   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12227   SmallSet<SDNode *, 16> Visited;
12228 
12229   // First, search up the chain, branching to follow all token-factor operands.
12230   // If we find a consecutive load, then we're done, otherwise, record all
12231   // nodes just above the top-level loads and token factors.
12232   while (!Queue.empty()) {
12233     SDNode *ChainNext = Queue.pop_back_val();
12234     if (!Visited.insert(ChainNext).second)
12235       continue;
12236 
12237     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12238       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12239         return true;
12240 
12241       if (!Visited.count(ChainLD->getChain().getNode()))
12242         Queue.push_back(ChainLD->getChain().getNode());
12243     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12244       for (const SDUse &O : ChainNext->ops())
12245         if (!Visited.count(O.getNode()))
12246           Queue.push_back(O.getNode());
12247     } else
12248       LoadRoots.insert(ChainNext);
12249   }
12250 
12251   // Second, search down the chain, starting from the top-level nodes recorded
12252   // in the first phase. These top-level nodes are the nodes just above all
12253   // loads and token factors. Starting with their uses, recursively look though
12254   // all loads (just the chain uses) and token factors to find a consecutive
12255   // load.
12256   Visited.clear();
12257   Queue.clear();
12258 
12259   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12260        IE = LoadRoots.end(); I != IE; ++I) {
12261     Queue.push_back(*I);
12262 
12263     while (!Queue.empty()) {
12264       SDNode *LoadRoot = Queue.pop_back_val();
12265       if (!Visited.insert(LoadRoot).second)
12266         continue;
12267 
12268       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12269         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12270           return true;
12271 
12272       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12273            UE = LoadRoot->use_end(); UI != UE; ++UI)
12274         if (((isa<MemSDNode>(*UI) &&
12275             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12276             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12277           Queue.push_back(*UI);
12278     }
12279   }
12280 
12281   return false;
12282 }
12283 
12284 /// This function is called when we have proved that a SETCC node can be replaced
12285 /// by subtraction (and other supporting instructions) so that the result of
12286 /// comparison is kept in a GPR instead of CR. This function is purely for
12287 /// codegen purposes and has some flags to guide the codegen process.
12288 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12289                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12290   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12291 
12292   // Zero extend the operands to the largest legal integer. Originally, they
12293   // must be of a strictly smaller size.
12294   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12295                          DAG.getConstant(Size, DL, MVT::i32));
12296   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12297                          DAG.getConstant(Size, DL, MVT::i32));
12298 
12299   // Swap if needed. Depends on the condition code.
12300   if (Swap)
12301     std::swap(Op0, Op1);
12302 
12303   // Subtract extended integers.
12304   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12305 
12306   // Move the sign bit to the least significant position and zero out the rest.
12307   // Now the least significant bit carries the result of original comparison.
12308   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12309                              DAG.getConstant(Size - 1, DL, MVT::i32));
12310   auto Final = Shifted;
12311 
12312   // Complement the result if needed. Based on the condition code.
12313   if (Complement)
12314     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12315                         DAG.getConstant(1, DL, MVT::i64));
12316 
12317   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12318 }
12319 
12320 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12321                                                   DAGCombinerInfo &DCI) const {
12322   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12323 
12324   SelectionDAG &DAG = DCI.DAG;
12325   SDLoc DL(N);
12326 
12327   // Size of integers being compared has a critical role in the following
12328   // analysis, so we prefer to do this when all types are legal.
12329   if (!DCI.isAfterLegalizeDAG())
12330     return SDValue();
12331 
12332   // If all users of SETCC extend its value to a legal integer type
12333   // then we replace SETCC with a subtraction
12334   for (SDNode::use_iterator UI = N->use_begin(),
12335        UE = N->use_end(); UI != UE; ++UI) {
12336     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12337       return SDValue();
12338   }
12339 
12340   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12341   auto OpSize = N->getOperand(0).getValueSizeInBits();
12342 
12343   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12344 
12345   if (OpSize < Size) {
12346     switch (CC) {
12347     default: break;
12348     case ISD::SETULT:
12349       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12350     case ISD::SETULE:
12351       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12352     case ISD::SETUGT:
12353       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12354     case ISD::SETUGE:
12355       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12356     }
12357   }
12358 
12359   return SDValue();
12360 }
12361 
12362 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12363                                                   DAGCombinerInfo &DCI) const {
12364   SelectionDAG &DAG = DCI.DAG;
12365   SDLoc dl(N);
12366 
12367   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12368   // If we're tracking CR bits, we need to be careful that we don't have:
12369   //   trunc(binary-ops(zext(x), zext(y)))
12370   // or
12371   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12372   // such that we're unnecessarily moving things into GPRs when it would be
12373   // better to keep them in CR bits.
12374 
12375   // Note that trunc here can be an actual i1 trunc, or can be the effective
12376   // truncation that comes from a setcc or select_cc.
12377   if (N->getOpcode() == ISD::TRUNCATE &&
12378       N->getValueType(0) != MVT::i1)
12379     return SDValue();
12380 
12381   if (N->getOperand(0).getValueType() != MVT::i32 &&
12382       N->getOperand(0).getValueType() != MVT::i64)
12383     return SDValue();
12384 
12385   if (N->getOpcode() == ISD::SETCC ||
12386       N->getOpcode() == ISD::SELECT_CC) {
12387     // If we're looking at a comparison, then we need to make sure that the
12388     // high bits (all except for the first) don't matter the result.
12389     ISD::CondCode CC =
12390       cast<CondCodeSDNode>(N->getOperand(
12391         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12392     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12393 
12394     if (ISD::isSignedIntSetCC(CC)) {
12395       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12396           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12397         return SDValue();
12398     } else if (ISD::isUnsignedIntSetCC(CC)) {
12399       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12400                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12401           !DAG.MaskedValueIsZero(N->getOperand(1),
12402                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12403         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12404                                              : SDValue());
12405     } else {
12406       // This is neither a signed nor an unsigned comparison, just make sure
12407       // that the high bits are equal.
12408       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12409       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12410 
12411       // We don't really care about what is known about the first bit (if
12412       // anything), so clear it in all masks prior to comparing them.
12413       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12414       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12415 
12416       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12417         return SDValue();
12418     }
12419   }
12420 
12421   // We now know that the higher-order bits are irrelevant, we just need to
12422   // make sure that all of the intermediate operations are bit operations, and
12423   // all inputs are extensions.
12424   if (N->getOperand(0).getOpcode() != ISD::AND &&
12425       N->getOperand(0).getOpcode() != ISD::OR  &&
12426       N->getOperand(0).getOpcode() != ISD::XOR &&
12427       N->getOperand(0).getOpcode() != ISD::SELECT &&
12428       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12429       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12430       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12431       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12432       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12433     return SDValue();
12434 
12435   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12436       N->getOperand(1).getOpcode() != ISD::AND &&
12437       N->getOperand(1).getOpcode() != ISD::OR  &&
12438       N->getOperand(1).getOpcode() != ISD::XOR &&
12439       N->getOperand(1).getOpcode() != ISD::SELECT &&
12440       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12441       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12442       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12443       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12444       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12445     return SDValue();
12446 
12447   SmallVector<SDValue, 4> Inputs;
12448   SmallVector<SDValue, 8> BinOps, PromOps;
12449   SmallPtrSet<SDNode *, 16> Visited;
12450 
12451   for (unsigned i = 0; i < 2; ++i) {
12452     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12453           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12454           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12455           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12456         isa<ConstantSDNode>(N->getOperand(i)))
12457       Inputs.push_back(N->getOperand(i));
12458     else
12459       BinOps.push_back(N->getOperand(i));
12460 
12461     if (N->getOpcode() == ISD::TRUNCATE)
12462       break;
12463   }
12464 
12465   // Visit all inputs, collect all binary operations (and, or, xor and
12466   // select) that are all fed by extensions.
12467   while (!BinOps.empty()) {
12468     SDValue BinOp = BinOps.back();
12469     BinOps.pop_back();
12470 
12471     if (!Visited.insert(BinOp.getNode()).second)
12472       continue;
12473 
12474     PromOps.push_back(BinOp);
12475 
12476     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12477       // The condition of the select is not promoted.
12478       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12479         continue;
12480       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12481         continue;
12482 
12483       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12484             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12485             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12486            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12487           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12488         Inputs.push_back(BinOp.getOperand(i));
12489       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12490                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12491                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12492                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12493                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12494                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12495                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12496                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12497                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12498         BinOps.push_back(BinOp.getOperand(i));
12499       } else {
12500         // We have an input that is not an extension or another binary
12501         // operation; we'll abort this transformation.
12502         return SDValue();
12503       }
12504     }
12505   }
12506 
12507   // Make sure that this is a self-contained cluster of operations (which
12508   // is not quite the same thing as saying that everything has only one
12509   // use).
12510   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12511     if (isa<ConstantSDNode>(Inputs[i]))
12512       continue;
12513 
12514     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12515                               UE = Inputs[i].getNode()->use_end();
12516          UI != UE; ++UI) {
12517       SDNode *User = *UI;
12518       if (User != N && !Visited.count(User))
12519         return SDValue();
12520 
12521       // Make sure that we're not going to promote the non-output-value
12522       // operand(s) or SELECT or SELECT_CC.
12523       // FIXME: Although we could sometimes handle this, and it does occur in
12524       // practice that one of the condition inputs to the select is also one of
12525       // the outputs, we currently can't deal with this.
12526       if (User->getOpcode() == ISD::SELECT) {
12527         if (User->getOperand(0) == Inputs[i])
12528           return SDValue();
12529       } else if (User->getOpcode() == ISD::SELECT_CC) {
12530         if (User->getOperand(0) == Inputs[i] ||
12531             User->getOperand(1) == Inputs[i])
12532           return SDValue();
12533       }
12534     }
12535   }
12536 
12537   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12538     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12539                               UE = PromOps[i].getNode()->use_end();
12540          UI != UE; ++UI) {
12541       SDNode *User = *UI;
12542       if (User != N && !Visited.count(User))
12543         return SDValue();
12544 
12545       // Make sure that we're not going to promote the non-output-value
12546       // operand(s) or SELECT or SELECT_CC.
12547       // FIXME: Although we could sometimes handle this, and it does occur in
12548       // practice that one of the condition inputs to the select is also one of
12549       // the outputs, we currently can't deal with this.
12550       if (User->getOpcode() == ISD::SELECT) {
12551         if (User->getOperand(0) == PromOps[i])
12552           return SDValue();
12553       } else if (User->getOpcode() == ISD::SELECT_CC) {
12554         if (User->getOperand(0) == PromOps[i] ||
12555             User->getOperand(1) == PromOps[i])
12556           return SDValue();
12557       }
12558     }
12559   }
12560 
12561   // Replace all inputs with the extension operand.
12562   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12563     // Constants may have users outside the cluster of to-be-promoted nodes,
12564     // and so we need to replace those as we do the promotions.
12565     if (isa<ConstantSDNode>(Inputs[i]))
12566       continue;
12567     else
12568       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12569   }
12570 
12571   std::list<HandleSDNode> PromOpHandles;
12572   for (auto &PromOp : PromOps)
12573     PromOpHandles.emplace_back(PromOp);
12574 
12575   // Replace all operations (these are all the same, but have a different
12576   // (i1) return type). DAG.getNode will validate that the types of
12577   // a binary operator match, so go through the list in reverse so that
12578   // we've likely promoted both operands first. Any intermediate truncations or
12579   // extensions disappear.
12580   while (!PromOpHandles.empty()) {
12581     SDValue PromOp = PromOpHandles.back().getValue();
12582     PromOpHandles.pop_back();
12583 
12584     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12585         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12586         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12587         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12588       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12589           PromOp.getOperand(0).getValueType() != MVT::i1) {
12590         // The operand is not yet ready (see comment below).
12591         PromOpHandles.emplace_front(PromOp);
12592         continue;
12593       }
12594 
12595       SDValue RepValue = PromOp.getOperand(0);
12596       if (isa<ConstantSDNode>(RepValue))
12597         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12598 
12599       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12600       continue;
12601     }
12602 
12603     unsigned C;
12604     switch (PromOp.getOpcode()) {
12605     default:             C = 0; break;
12606     case ISD::SELECT:    C = 1; break;
12607     case ISD::SELECT_CC: C = 2; break;
12608     }
12609 
12610     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12611          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12612         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12613          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12614       // The to-be-promoted operands of this node have not yet been
12615       // promoted (this should be rare because we're going through the
12616       // list backward, but if one of the operands has several users in
12617       // this cluster of to-be-promoted nodes, it is possible).
12618       PromOpHandles.emplace_front(PromOp);
12619       continue;
12620     }
12621 
12622     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12623                                 PromOp.getNode()->op_end());
12624 
12625     // If there are any constant inputs, make sure they're replaced now.
12626     for (unsigned i = 0; i < 2; ++i)
12627       if (isa<ConstantSDNode>(Ops[C+i]))
12628         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12629 
12630     DAG.ReplaceAllUsesOfValueWith(PromOp,
12631       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12632   }
12633 
12634   // Now we're left with the initial truncation itself.
12635   if (N->getOpcode() == ISD::TRUNCATE)
12636     return N->getOperand(0);
12637 
12638   // Otherwise, this is a comparison. The operands to be compared have just
12639   // changed type (to i1), but everything else is the same.
12640   return SDValue(N, 0);
12641 }
12642 
12643 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12644                                                   DAGCombinerInfo &DCI) const {
12645   SelectionDAG &DAG = DCI.DAG;
12646   SDLoc dl(N);
12647 
12648   // If we're tracking CR bits, we need to be careful that we don't have:
12649   //   zext(binary-ops(trunc(x), trunc(y)))
12650   // or
12651   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12652   // such that we're unnecessarily moving things into CR bits that can more
12653   // efficiently stay in GPRs. Note that if we're not certain that the high
12654   // bits are set as required by the final extension, we still may need to do
12655   // some masking to get the proper behavior.
12656 
12657   // This same functionality is important on PPC64 when dealing with
12658   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12659   // the return values of functions. Because it is so similar, it is handled
12660   // here as well.
12661 
12662   if (N->getValueType(0) != MVT::i32 &&
12663       N->getValueType(0) != MVT::i64)
12664     return SDValue();
12665 
12666   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12667         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12668     return SDValue();
12669 
12670   if (N->getOperand(0).getOpcode() != ISD::AND &&
12671       N->getOperand(0).getOpcode() != ISD::OR  &&
12672       N->getOperand(0).getOpcode() != ISD::XOR &&
12673       N->getOperand(0).getOpcode() != ISD::SELECT &&
12674       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12675     return SDValue();
12676 
12677   SmallVector<SDValue, 4> Inputs;
12678   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12679   SmallPtrSet<SDNode *, 16> Visited;
12680 
12681   // Visit all inputs, collect all binary operations (and, or, xor and
12682   // select) that are all fed by truncations.
12683   while (!BinOps.empty()) {
12684     SDValue BinOp = BinOps.back();
12685     BinOps.pop_back();
12686 
12687     if (!Visited.insert(BinOp.getNode()).second)
12688       continue;
12689 
12690     PromOps.push_back(BinOp);
12691 
12692     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12693       // The condition of the select is not promoted.
12694       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12695         continue;
12696       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12697         continue;
12698 
12699       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12700           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12701         Inputs.push_back(BinOp.getOperand(i));
12702       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12703                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12704                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12705                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12706                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12707         BinOps.push_back(BinOp.getOperand(i));
12708       } else {
12709         // We have an input that is not a truncation or another binary
12710         // operation; we'll abort this transformation.
12711         return SDValue();
12712       }
12713     }
12714   }
12715 
12716   // The operands of a select that must be truncated when the select is
12717   // promoted because the operand is actually part of the to-be-promoted set.
12718   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12719 
12720   // Make sure that this is a self-contained cluster of operations (which
12721   // is not quite the same thing as saying that everything has only one
12722   // use).
12723   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12724     if (isa<ConstantSDNode>(Inputs[i]))
12725       continue;
12726 
12727     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12728                               UE = Inputs[i].getNode()->use_end();
12729          UI != UE; ++UI) {
12730       SDNode *User = *UI;
12731       if (User != N && !Visited.count(User))
12732         return SDValue();
12733 
12734       // If we're going to promote the non-output-value operand(s) or SELECT or
12735       // SELECT_CC, record them for truncation.
12736       if (User->getOpcode() == ISD::SELECT) {
12737         if (User->getOperand(0) == Inputs[i])
12738           SelectTruncOp[0].insert(std::make_pair(User,
12739                                     User->getOperand(0).getValueType()));
12740       } else if (User->getOpcode() == ISD::SELECT_CC) {
12741         if (User->getOperand(0) == Inputs[i])
12742           SelectTruncOp[0].insert(std::make_pair(User,
12743                                     User->getOperand(0).getValueType()));
12744         if (User->getOperand(1) == Inputs[i])
12745           SelectTruncOp[1].insert(std::make_pair(User,
12746                                     User->getOperand(1).getValueType()));
12747       }
12748     }
12749   }
12750 
12751   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12752     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12753                               UE = PromOps[i].getNode()->use_end();
12754          UI != UE; ++UI) {
12755       SDNode *User = *UI;
12756       if (User != N && !Visited.count(User))
12757         return SDValue();
12758 
12759       // If we're going to promote the non-output-value operand(s) or SELECT or
12760       // SELECT_CC, record them for truncation.
12761       if (User->getOpcode() == ISD::SELECT) {
12762         if (User->getOperand(0) == PromOps[i])
12763           SelectTruncOp[0].insert(std::make_pair(User,
12764                                     User->getOperand(0).getValueType()));
12765       } else if (User->getOpcode() == ISD::SELECT_CC) {
12766         if (User->getOperand(0) == PromOps[i])
12767           SelectTruncOp[0].insert(std::make_pair(User,
12768                                     User->getOperand(0).getValueType()));
12769         if (User->getOperand(1) == PromOps[i])
12770           SelectTruncOp[1].insert(std::make_pair(User,
12771                                     User->getOperand(1).getValueType()));
12772       }
12773     }
12774   }
12775 
12776   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12777   bool ReallyNeedsExt = false;
12778   if (N->getOpcode() != ISD::ANY_EXTEND) {
12779     // If all of the inputs are not already sign/zero extended, then
12780     // we'll still need to do that at the end.
12781     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12782       if (isa<ConstantSDNode>(Inputs[i]))
12783         continue;
12784 
12785       unsigned OpBits =
12786         Inputs[i].getOperand(0).getValueSizeInBits();
12787       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12788 
12789       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12790            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12791                                   APInt::getHighBitsSet(OpBits,
12792                                                         OpBits-PromBits))) ||
12793           (N->getOpcode() == ISD::SIGN_EXTEND &&
12794            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12795              (OpBits-(PromBits-1)))) {
12796         ReallyNeedsExt = true;
12797         break;
12798       }
12799     }
12800   }
12801 
12802   // Replace all inputs, either with the truncation operand, or a
12803   // truncation or extension to the final output type.
12804   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12805     // Constant inputs need to be replaced with the to-be-promoted nodes that
12806     // use them because they might have users outside of the cluster of
12807     // promoted nodes.
12808     if (isa<ConstantSDNode>(Inputs[i]))
12809       continue;
12810 
12811     SDValue InSrc = Inputs[i].getOperand(0);
12812     if (Inputs[i].getValueType() == N->getValueType(0))
12813       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12814     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12815       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12816         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12817     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12818       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12819         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12820     else
12821       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12822         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12823   }
12824 
12825   std::list<HandleSDNode> PromOpHandles;
12826   for (auto &PromOp : PromOps)
12827     PromOpHandles.emplace_back(PromOp);
12828 
12829   // Replace all operations (these are all the same, but have a different
12830   // (promoted) return type). DAG.getNode will validate that the types of
12831   // a binary operator match, so go through the list in reverse so that
12832   // we've likely promoted both operands first.
12833   while (!PromOpHandles.empty()) {
12834     SDValue PromOp = PromOpHandles.back().getValue();
12835     PromOpHandles.pop_back();
12836 
12837     unsigned C;
12838     switch (PromOp.getOpcode()) {
12839     default:             C = 0; break;
12840     case ISD::SELECT:    C = 1; break;
12841     case ISD::SELECT_CC: C = 2; break;
12842     }
12843 
12844     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12845          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12846         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12847          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12848       // The to-be-promoted operands of this node have not yet been
12849       // promoted (this should be rare because we're going through the
12850       // list backward, but if one of the operands has several users in
12851       // this cluster of to-be-promoted nodes, it is possible).
12852       PromOpHandles.emplace_front(PromOp);
12853       continue;
12854     }
12855 
12856     // For SELECT and SELECT_CC nodes, we do a similar check for any
12857     // to-be-promoted comparison inputs.
12858     if (PromOp.getOpcode() == ISD::SELECT ||
12859         PromOp.getOpcode() == ISD::SELECT_CC) {
12860       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12861            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12862           (SelectTruncOp[1].count(PromOp.getNode()) &&
12863            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12864         PromOpHandles.emplace_front(PromOp);
12865         continue;
12866       }
12867     }
12868 
12869     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12870                                 PromOp.getNode()->op_end());
12871 
12872     // If this node has constant inputs, then they'll need to be promoted here.
12873     for (unsigned i = 0; i < 2; ++i) {
12874       if (!isa<ConstantSDNode>(Ops[C+i]))
12875         continue;
12876       if (Ops[C+i].getValueType() == N->getValueType(0))
12877         continue;
12878 
12879       if (N->getOpcode() == ISD::SIGN_EXTEND)
12880         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12881       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12882         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12883       else
12884         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12885     }
12886 
12887     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12888     // truncate them again to the original value type.
12889     if (PromOp.getOpcode() == ISD::SELECT ||
12890         PromOp.getOpcode() == ISD::SELECT_CC) {
12891       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12892       if (SI0 != SelectTruncOp[0].end())
12893         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12894       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12895       if (SI1 != SelectTruncOp[1].end())
12896         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12897     }
12898 
12899     DAG.ReplaceAllUsesOfValueWith(PromOp,
12900       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12901   }
12902 
12903   // Now we're left with the initial extension itself.
12904   if (!ReallyNeedsExt)
12905     return N->getOperand(0);
12906 
12907   // To zero extend, just mask off everything except for the first bit (in the
12908   // i1 case).
12909   if (N->getOpcode() == ISD::ZERO_EXTEND)
12910     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12911                        DAG.getConstant(APInt::getLowBitsSet(
12912                                          N->getValueSizeInBits(0), PromBits),
12913                                        dl, N->getValueType(0)));
12914 
12915   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12916          "Invalid extension type");
12917   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12918   SDValue ShiftCst =
12919       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12920   return DAG.getNode(
12921       ISD::SRA, dl, N->getValueType(0),
12922       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12923       ShiftCst);
12924 }
12925 
12926 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12927                                         DAGCombinerInfo &DCI) const {
12928   assert(N->getOpcode() == ISD::SETCC &&
12929          "Should be called with a SETCC node");
12930 
12931   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12932   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12933     SDValue LHS = N->getOperand(0);
12934     SDValue RHS = N->getOperand(1);
12935 
12936     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12937     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12938         LHS.hasOneUse())
12939       std::swap(LHS, RHS);
12940 
12941     // x == 0-y --> x+y == 0
12942     // x != 0-y --> x+y != 0
12943     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12944         RHS.hasOneUse()) {
12945       SDLoc DL(N);
12946       SelectionDAG &DAG = DCI.DAG;
12947       EVT VT = N->getValueType(0);
12948       EVT OpVT = LHS.getValueType();
12949       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12950       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12951     }
12952   }
12953 
12954   return DAGCombineTruncBoolExt(N, DCI);
12955 }
12956 
12957 // Is this an extending load from an f32 to an f64?
12958 static bool isFPExtLoad(SDValue Op) {
12959   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12960     return LD->getExtensionType() == ISD::EXTLOAD &&
12961       Op.getValueType() == MVT::f64;
12962   return false;
12963 }
12964 
12965 /// Reduces the number of fp-to-int conversion when building a vector.
12966 ///
12967 /// If this vector is built out of floating to integer conversions,
12968 /// transform it to a vector built out of floating point values followed by a
12969 /// single floating to integer conversion of the vector.
12970 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12971 /// becomes (fptosi (build_vector ($A, $B, ...)))
12972 SDValue PPCTargetLowering::
12973 combineElementTruncationToVectorTruncation(SDNode *N,
12974                                            DAGCombinerInfo &DCI) const {
12975   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12976          "Should be called with a BUILD_VECTOR node");
12977 
12978   SelectionDAG &DAG = DCI.DAG;
12979   SDLoc dl(N);
12980 
12981   SDValue FirstInput = N->getOperand(0);
12982   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12983          "The input operand must be an fp-to-int conversion.");
12984 
12985   // This combine happens after legalization so the fp_to_[su]i nodes are
12986   // already converted to PPCSISD nodes.
12987   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12988   if (FirstConversion == PPCISD::FCTIDZ ||
12989       FirstConversion == PPCISD::FCTIDUZ ||
12990       FirstConversion == PPCISD::FCTIWZ ||
12991       FirstConversion == PPCISD::FCTIWUZ) {
12992     bool IsSplat = true;
12993     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12994       FirstConversion == PPCISD::FCTIWUZ;
12995     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12996     SmallVector<SDValue, 4> Ops;
12997     EVT TargetVT = N->getValueType(0);
12998     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12999       SDValue NextOp = N->getOperand(i);
13000       if (NextOp.getOpcode() != PPCISD::MFVSR)
13001         return SDValue();
13002       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13003       if (NextConversion != FirstConversion)
13004         return SDValue();
13005       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13006       // This is not valid if the input was originally double precision. It is
13007       // also not profitable to do unless this is an extending load in which
13008       // case doing this combine will allow us to combine consecutive loads.
13009       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13010         return SDValue();
13011       if (N->getOperand(i) != FirstInput)
13012         IsSplat = false;
13013     }
13014 
13015     // If this is a splat, we leave it as-is since there will be only a single
13016     // fp-to-int conversion followed by a splat of the integer. This is better
13017     // for 32-bit and smaller ints and neutral for 64-bit ints.
13018     if (IsSplat)
13019       return SDValue();
13020 
13021     // Now that we know we have the right type of node, get its operands
13022     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13023       SDValue In = N->getOperand(i).getOperand(0);
13024       if (Is32Bit) {
13025         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13026         // here, we know that all inputs are extending loads so this is safe).
13027         if (In.isUndef())
13028           Ops.push_back(DAG.getUNDEF(SrcVT));
13029         else {
13030           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13031                                       MVT::f32, In.getOperand(0),
13032                                       DAG.getIntPtrConstant(1, dl));
13033           Ops.push_back(Trunc);
13034         }
13035       } else
13036         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13037     }
13038 
13039     unsigned Opcode;
13040     if (FirstConversion == PPCISD::FCTIDZ ||
13041         FirstConversion == PPCISD::FCTIWZ)
13042       Opcode = ISD::FP_TO_SINT;
13043     else
13044       Opcode = ISD::FP_TO_UINT;
13045 
13046     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13047     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13048     return DAG.getNode(Opcode, dl, TargetVT, BV);
13049   }
13050   return SDValue();
13051 }
13052 
13053 /// Reduce the number of loads when building a vector.
13054 ///
13055 /// Building a vector out of multiple loads can be converted to a load
13056 /// of the vector type if the loads are consecutive. If the loads are
13057 /// consecutive but in descending order, a shuffle is added at the end
13058 /// to reorder the vector.
13059 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13060   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13061          "Should be called with a BUILD_VECTOR node");
13062 
13063   SDLoc dl(N);
13064 
13065   // Return early for non byte-sized type, as they can't be consecutive.
13066   if (!N->getValueType(0).getVectorElementType().isByteSized())
13067     return SDValue();
13068 
13069   bool InputsAreConsecutiveLoads = true;
13070   bool InputsAreReverseConsecutive = true;
13071   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13072   SDValue FirstInput = N->getOperand(0);
13073   bool IsRoundOfExtLoad = false;
13074 
13075   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13076       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13077     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13078     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13079   }
13080   // Not a build vector of (possibly fp_rounded) loads.
13081   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13082       N->getNumOperands() == 1)
13083     return SDValue();
13084 
13085   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13086     // If any inputs are fp_round(extload), they all must be.
13087     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13088       return SDValue();
13089 
13090     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13091       N->getOperand(i);
13092     if (NextInput.getOpcode() != ISD::LOAD)
13093       return SDValue();
13094 
13095     SDValue PreviousInput =
13096       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13097     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13098     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13099 
13100     // If any inputs are fp_round(extload), they all must be.
13101     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13102       return SDValue();
13103 
13104     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13105       InputsAreConsecutiveLoads = false;
13106     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13107       InputsAreReverseConsecutive = false;
13108 
13109     // Exit early if the loads are neither consecutive nor reverse consecutive.
13110     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13111       return SDValue();
13112   }
13113 
13114   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13115          "The loads cannot be both consecutive and reverse consecutive.");
13116 
13117   SDValue FirstLoadOp =
13118     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13119   SDValue LastLoadOp =
13120     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13121                        N->getOperand(N->getNumOperands()-1);
13122 
13123   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13124   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13125   if (InputsAreConsecutiveLoads) {
13126     assert(LD1 && "Input needs to be a LoadSDNode.");
13127     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13128                        LD1->getBasePtr(), LD1->getPointerInfo(),
13129                        LD1->getAlignment());
13130   }
13131   if (InputsAreReverseConsecutive) {
13132     assert(LDL && "Input needs to be a LoadSDNode.");
13133     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13134                                LDL->getBasePtr(), LDL->getPointerInfo(),
13135                                LDL->getAlignment());
13136     SmallVector<int, 16> Ops;
13137     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13138       Ops.push_back(i);
13139 
13140     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13141                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13142   }
13143   return SDValue();
13144 }
13145 
13146 // This function adds the required vector_shuffle needed to get
13147 // the elements of the vector extract in the correct position
13148 // as specified by the CorrectElems encoding.
13149 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13150                                       SDValue Input, uint64_t Elems,
13151                                       uint64_t CorrectElems) {
13152   SDLoc dl(N);
13153 
13154   unsigned NumElems = Input.getValueType().getVectorNumElements();
13155   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13156 
13157   // Knowing the element indices being extracted from the original
13158   // vector and the order in which they're being inserted, just put
13159   // them at element indices required for the instruction.
13160   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13161     if (DAG.getDataLayout().isLittleEndian())
13162       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13163     else
13164       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13165     CorrectElems = CorrectElems >> 8;
13166     Elems = Elems >> 8;
13167   }
13168 
13169   SDValue Shuffle =
13170       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13171                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13172 
13173   EVT Ty = N->getValueType(0);
13174   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
13175   return BV;
13176 }
13177 
13178 // Look for build vector patterns where input operands come from sign
13179 // extended vector_extract elements of specific indices. If the correct indices
13180 // aren't used, add a vector shuffle to fix up the indices and create a new
13181 // PPCISD:SExtVElems node which selects the vector sign extend instructions
13182 // during instruction selection.
13183 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13184   // This array encodes the indices that the vector sign extend instructions
13185   // extract from when extending from one type to another for both BE and LE.
13186   // The right nibble of each byte corresponds to the LE incides.
13187   // and the left nibble of each byte corresponds to the BE incides.
13188   // For example: 0x3074B8FC  byte->word
13189   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13190   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13191   // For example: 0x000070F8  byte->double word
13192   // For LE: the allowed indices are: 0x0,0x8
13193   // For BE: the allowed indices are: 0x7,0xF
13194   uint64_t TargetElems[] = {
13195       0x3074B8FC, // b->w
13196       0x000070F8, // b->d
13197       0x10325476, // h->w
13198       0x00003074, // h->d
13199       0x00001032, // w->d
13200   };
13201 
13202   uint64_t Elems = 0;
13203   int Index;
13204   SDValue Input;
13205 
13206   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13207     if (!Op)
13208       return false;
13209     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13210         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13211       return false;
13212 
13213     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13214     // of the right width.
13215     SDValue Extract = Op.getOperand(0);
13216     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13217       Extract = Extract.getOperand(0);
13218     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13219       return false;
13220 
13221     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13222     if (!ExtOp)
13223       return false;
13224 
13225     Index = ExtOp->getZExtValue();
13226     if (Input && Input != Extract.getOperand(0))
13227       return false;
13228 
13229     if (!Input)
13230       Input = Extract.getOperand(0);
13231 
13232     Elems = Elems << 8;
13233     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13234     Elems |= Index;
13235 
13236     return true;
13237   };
13238 
13239   // If the build vector operands aren't sign extended vector extracts,
13240   // of the same input vector, then return.
13241   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13242     if (!isSExtOfVecExtract(N->getOperand(i))) {
13243       return SDValue();
13244     }
13245   }
13246 
13247   // If the vector extract indicies are not correct, add the appropriate
13248   // vector_shuffle.
13249   int TgtElemArrayIdx;
13250   int InputSize = Input.getValueType().getScalarSizeInBits();
13251   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13252   if (InputSize + OutputSize == 40)
13253     TgtElemArrayIdx = 0;
13254   else if (InputSize + OutputSize == 72)
13255     TgtElemArrayIdx = 1;
13256   else if (InputSize + OutputSize == 48)
13257     TgtElemArrayIdx = 2;
13258   else if (InputSize + OutputSize == 80)
13259     TgtElemArrayIdx = 3;
13260   else if (InputSize + OutputSize == 96)
13261     TgtElemArrayIdx = 4;
13262   else
13263     return SDValue();
13264 
13265   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13266   CorrectElems = DAG.getDataLayout().isLittleEndian()
13267                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13268                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13269   if (Elems != CorrectElems) {
13270     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13271   }
13272 
13273   // Regular lowering will catch cases where a shuffle is not needed.
13274   return SDValue();
13275 }
13276 
13277 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13278                                                  DAGCombinerInfo &DCI) const {
13279   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13280          "Should be called with a BUILD_VECTOR node");
13281 
13282   SelectionDAG &DAG = DCI.DAG;
13283   SDLoc dl(N);
13284 
13285   if (!Subtarget.hasVSX())
13286     return SDValue();
13287 
13288   // The target independent DAG combiner will leave a build_vector of
13289   // float-to-int conversions intact. We can generate MUCH better code for
13290   // a float-to-int conversion of a vector of floats.
13291   SDValue FirstInput = N->getOperand(0);
13292   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13293     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13294     if (Reduced)
13295       return Reduced;
13296   }
13297 
13298   // If we're building a vector out of consecutive loads, just load that
13299   // vector type.
13300   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13301   if (Reduced)
13302     return Reduced;
13303 
13304   // If we're building a vector out of extended elements from another vector
13305   // we have P9 vector integer extend instructions. The code assumes legal
13306   // input types (i.e. it can't handle things like v4i16) so do not run before
13307   // legalization.
13308   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13309     Reduced = combineBVOfVecSExt(N, DAG);
13310     if (Reduced)
13311       return Reduced;
13312   }
13313 
13314 
13315   if (N->getValueType(0) != MVT::v2f64)
13316     return SDValue();
13317 
13318   // Looking for:
13319   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13320   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13321       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13322     return SDValue();
13323   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13324       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13325     return SDValue();
13326   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13327     return SDValue();
13328 
13329   SDValue Ext1 = FirstInput.getOperand(0);
13330   SDValue Ext2 = N->getOperand(1).getOperand(0);
13331   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13332      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13333     return SDValue();
13334 
13335   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13336   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13337   if (!Ext1Op || !Ext2Op)
13338     return SDValue();
13339   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13340       Ext1.getOperand(0) != Ext2.getOperand(0))
13341     return SDValue();
13342 
13343   int FirstElem = Ext1Op->getZExtValue();
13344   int SecondElem = Ext2Op->getZExtValue();
13345   int SubvecIdx;
13346   if (FirstElem == 0 && SecondElem == 1)
13347     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13348   else if (FirstElem == 2 && SecondElem == 3)
13349     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13350   else
13351     return SDValue();
13352 
13353   SDValue SrcVec = Ext1.getOperand(0);
13354   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13355     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13356   return DAG.getNode(NodeType, dl, MVT::v2f64,
13357                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13358 }
13359 
13360 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13361                                               DAGCombinerInfo &DCI) const {
13362   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13363           N->getOpcode() == ISD::UINT_TO_FP) &&
13364          "Need an int -> FP conversion node here");
13365 
13366   if (useSoftFloat() || !Subtarget.has64BitSupport())
13367     return SDValue();
13368 
13369   SelectionDAG &DAG = DCI.DAG;
13370   SDLoc dl(N);
13371   SDValue Op(N, 0);
13372 
13373   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13374   // from the hardware.
13375   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13376     return SDValue();
13377   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13378       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13379     return SDValue();
13380 
13381   SDValue FirstOperand(Op.getOperand(0));
13382   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13383     (FirstOperand.getValueType() == MVT::i8 ||
13384      FirstOperand.getValueType() == MVT::i16);
13385   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13386     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13387     bool DstDouble = Op.getValueType() == MVT::f64;
13388     unsigned ConvOp = Signed ?
13389       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13390       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13391     SDValue WidthConst =
13392       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13393                             dl, false);
13394     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13395     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13396     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13397                                          DAG.getVTList(MVT::f64, MVT::Other),
13398                                          Ops, MVT::i8, LDN->getMemOperand());
13399 
13400     // For signed conversion, we need to sign-extend the value in the VSR
13401     if (Signed) {
13402       SDValue ExtOps[] = { Ld, WidthConst };
13403       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13404       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13405     } else
13406       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13407   }
13408 
13409 
13410   // For i32 intermediate values, unfortunately, the conversion functions
13411   // leave the upper 32 bits of the value are undefined. Within the set of
13412   // scalar instructions, we have no method for zero- or sign-extending the
13413   // value. Thus, we cannot handle i32 intermediate values here.
13414   if (Op.getOperand(0).getValueType() == MVT::i32)
13415     return SDValue();
13416 
13417   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13418          "UINT_TO_FP is supported only with FPCVT");
13419 
13420   // If we have FCFIDS, then use it when converting to single-precision.
13421   // Otherwise, convert to double-precision and then round.
13422   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13423                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13424                                                             : PPCISD::FCFIDS)
13425                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13426                                                             : PPCISD::FCFID);
13427   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13428                   ? MVT::f32
13429                   : MVT::f64;
13430 
13431   // If we're converting from a float, to an int, and back to a float again,
13432   // then we don't need the store/load pair at all.
13433   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13434        Subtarget.hasFPCVT()) ||
13435       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13436     SDValue Src = Op.getOperand(0).getOperand(0);
13437     if (Src.getValueType() == MVT::f32) {
13438       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13439       DCI.AddToWorklist(Src.getNode());
13440     } else if (Src.getValueType() != MVT::f64) {
13441       // Make sure that we don't pick up a ppc_fp128 source value.
13442       return SDValue();
13443     }
13444 
13445     unsigned FCTOp =
13446       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13447                                                         PPCISD::FCTIDUZ;
13448 
13449     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13450     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13451 
13452     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13453       FP = DAG.getNode(ISD::FP_ROUND, dl,
13454                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13455       DCI.AddToWorklist(FP.getNode());
13456     }
13457 
13458     return FP;
13459   }
13460 
13461   return SDValue();
13462 }
13463 
13464 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13465 // builtins) into loads with swaps.
13466 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13467                                               DAGCombinerInfo &DCI) const {
13468   SelectionDAG &DAG = DCI.DAG;
13469   SDLoc dl(N);
13470   SDValue Chain;
13471   SDValue Base;
13472   MachineMemOperand *MMO;
13473 
13474   switch (N->getOpcode()) {
13475   default:
13476     llvm_unreachable("Unexpected opcode for little endian VSX load");
13477   case ISD::LOAD: {
13478     LoadSDNode *LD = cast<LoadSDNode>(N);
13479     Chain = LD->getChain();
13480     Base = LD->getBasePtr();
13481     MMO = LD->getMemOperand();
13482     // If the MMO suggests this isn't a load of a full vector, leave
13483     // things alone.  For a built-in, we have to make the change for
13484     // correctness, so if there is a size problem that will be a bug.
13485     if (MMO->getSize() < 16)
13486       return SDValue();
13487     break;
13488   }
13489   case ISD::INTRINSIC_W_CHAIN: {
13490     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13491     Chain = Intrin->getChain();
13492     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13493     // us what we want. Get operand 2 instead.
13494     Base = Intrin->getOperand(2);
13495     MMO = Intrin->getMemOperand();
13496     break;
13497   }
13498   }
13499 
13500   MVT VecTy = N->getValueType(0).getSimpleVT();
13501 
13502   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13503   // aligned and the type is a vector with elements up to 4 bytes
13504   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13505       && VecTy.getScalarSizeInBits() <= 32 ) {
13506     return SDValue();
13507   }
13508 
13509   SDValue LoadOps[] = { Chain, Base };
13510   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13511                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13512                                          LoadOps, MVT::v2f64, MMO);
13513 
13514   DCI.AddToWorklist(Load.getNode());
13515   Chain = Load.getValue(1);
13516   SDValue Swap = DAG.getNode(
13517       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13518   DCI.AddToWorklist(Swap.getNode());
13519 
13520   // Add a bitcast if the resulting load type doesn't match v2f64.
13521   if (VecTy != MVT::v2f64) {
13522     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13523     DCI.AddToWorklist(N.getNode());
13524     // Package {bitcast value, swap's chain} to match Load's shape.
13525     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13526                        N, Swap.getValue(1));
13527   }
13528 
13529   return Swap;
13530 }
13531 
13532 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13533 // builtins) into stores with swaps.
13534 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13535                                                DAGCombinerInfo &DCI) const {
13536   SelectionDAG &DAG = DCI.DAG;
13537   SDLoc dl(N);
13538   SDValue Chain;
13539   SDValue Base;
13540   unsigned SrcOpnd;
13541   MachineMemOperand *MMO;
13542 
13543   switch (N->getOpcode()) {
13544   default:
13545     llvm_unreachable("Unexpected opcode for little endian VSX store");
13546   case ISD::STORE: {
13547     StoreSDNode *ST = cast<StoreSDNode>(N);
13548     Chain = ST->getChain();
13549     Base = ST->getBasePtr();
13550     MMO = ST->getMemOperand();
13551     SrcOpnd = 1;
13552     // If the MMO suggests this isn't a store of a full vector, leave
13553     // things alone.  For a built-in, we have to make the change for
13554     // correctness, so if there is a size problem that will be a bug.
13555     if (MMO->getSize() < 16)
13556       return SDValue();
13557     break;
13558   }
13559   case ISD::INTRINSIC_VOID: {
13560     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13561     Chain = Intrin->getChain();
13562     // Intrin->getBasePtr() oddly does not get what we want.
13563     Base = Intrin->getOperand(3);
13564     MMO = Intrin->getMemOperand();
13565     SrcOpnd = 2;
13566     break;
13567   }
13568   }
13569 
13570   SDValue Src = N->getOperand(SrcOpnd);
13571   MVT VecTy = Src.getValueType().getSimpleVT();
13572 
13573   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13574   // aligned and the type is a vector with elements up to 4 bytes
13575   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13576       && VecTy.getScalarSizeInBits() <= 32 ) {
13577     return SDValue();
13578   }
13579 
13580   // All stores are done as v2f64 and possible bit cast.
13581   if (VecTy != MVT::v2f64) {
13582     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13583     DCI.AddToWorklist(Src.getNode());
13584   }
13585 
13586   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13587                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13588   DCI.AddToWorklist(Swap.getNode());
13589   Chain = Swap.getValue(1);
13590   SDValue StoreOps[] = { Chain, Swap, Base };
13591   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13592                                           DAG.getVTList(MVT::Other),
13593                                           StoreOps, VecTy, MMO);
13594   DCI.AddToWorklist(Store.getNode());
13595   return Store;
13596 }
13597 
13598 // Handle DAG combine for STORE (FP_TO_INT F).
13599 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13600                                                DAGCombinerInfo &DCI) const {
13601 
13602   SelectionDAG &DAG = DCI.DAG;
13603   SDLoc dl(N);
13604   unsigned Opcode = N->getOperand(1).getOpcode();
13605 
13606   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13607          && "Not a FP_TO_INT Instruction!");
13608 
13609   SDValue Val = N->getOperand(1).getOperand(0);
13610   EVT Op1VT = N->getOperand(1).getValueType();
13611   EVT ResVT = Val.getValueType();
13612 
13613   // Floating point types smaller than 32 bits are not legal on Power.
13614   if (ResVT.getScalarSizeInBits() < 32)
13615     return SDValue();
13616 
13617   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13618   bool ValidTypeForStoreFltAsInt =
13619         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13620          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13621 
13622   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13623       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13624     return SDValue();
13625 
13626   // Extend f32 values to f64
13627   if (ResVT.getScalarSizeInBits() == 32) {
13628     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13629     DCI.AddToWorklist(Val.getNode());
13630   }
13631 
13632   // Set signed or unsigned conversion opcode.
13633   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13634                           PPCISD::FP_TO_SINT_IN_VSR :
13635                           PPCISD::FP_TO_UINT_IN_VSR;
13636 
13637   Val = DAG.getNode(ConvOpcode,
13638                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13639   DCI.AddToWorklist(Val.getNode());
13640 
13641   // Set number of bytes being converted.
13642   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13643   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13644                     DAG.getIntPtrConstant(ByteSize, dl, false),
13645                     DAG.getValueType(Op1VT) };
13646 
13647   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13648           DAG.getVTList(MVT::Other), Ops,
13649           cast<StoreSDNode>(N)->getMemoryVT(),
13650           cast<StoreSDNode>(N)->getMemOperand());
13651 
13652   DCI.AddToWorklist(Val.getNode());
13653   return Val;
13654 }
13655 
13656 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13657                                                 LSBaseSDNode *LSBase,
13658                                                 DAGCombinerInfo &DCI) const {
13659   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13660         "Not a reverse memop pattern!");
13661 
13662   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13663     auto Mask = SVN->getMask();
13664     int i = 0;
13665     auto I = Mask.rbegin();
13666     auto E = Mask.rend();
13667 
13668     for (; I != E; ++I) {
13669       if (*I != i)
13670         return false;
13671       i++;
13672     }
13673     return true;
13674   };
13675 
13676   SelectionDAG &DAG = DCI.DAG;
13677   EVT VT = SVN->getValueType(0);
13678 
13679   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13680     return SDValue();
13681 
13682   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13683   // See comment in PPCVSXSwapRemoval.cpp.
13684   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13685   if (!Subtarget.hasP9Vector())
13686     return SDValue();
13687 
13688   if(!IsElementReverse(SVN))
13689     return SDValue();
13690 
13691   if (LSBase->getOpcode() == ISD::LOAD) {
13692     SDLoc dl(SVN);
13693     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13694     return DAG.getMemIntrinsicNode(
13695         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13696         LSBase->getMemoryVT(), LSBase->getMemOperand());
13697   }
13698 
13699   if (LSBase->getOpcode() == ISD::STORE) {
13700     SDLoc dl(LSBase);
13701     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13702                           LSBase->getBasePtr()};
13703     return DAG.getMemIntrinsicNode(
13704         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13705         LSBase->getMemoryVT(), LSBase->getMemOperand());
13706   }
13707 
13708   llvm_unreachable("Expected a load or store node here");
13709 }
13710 
13711 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13712                                              DAGCombinerInfo &DCI) const {
13713   SelectionDAG &DAG = DCI.DAG;
13714   SDLoc dl(N);
13715   switch (N->getOpcode()) {
13716   default: break;
13717   case ISD::ADD:
13718     return combineADD(N, DCI);
13719   case ISD::SHL:
13720     return combineSHL(N, DCI);
13721   case ISD::SRA:
13722     return combineSRA(N, DCI);
13723   case ISD::SRL:
13724     return combineSRL(N, DCI);
13725   case ISD::MUL:
13726     return combineMUL(N, DCI);
13727   case PPCISD::SHL:
13728     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13729         return N->getOperand(0);
13730     break;
13731   case PPCISD::SRL:
13732     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13733         return N->getOperand(0);
13734     break;
13735   case PPCISD::SRA:
13736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13737       if (C->isNullValue() ||   //  0 >>s V -> 0.
13738           C->isAllOnesValue())    // -1 >>s V -> -1.
13739         return N->getOperand(0);
13740     }
13741     break;
13742   case ISD::SIGN_EXTEND:
13743   case ISD::ZERO_EXTEND:
13744   case ISD::ANY_EXTEND:
13745     return DAGCombineExtBoolTrunc(N, DCI);
13746   case ISD::TRUNCATE:
13747     return combineTRUNCATE(N, DCI);
13748   case ISD::SETCC:
13749     if (SDValue CSCC = combineSetCC(N, DCI))
13750       return CSCC;
13751     LLVM_FALLTHROUGH;
13752   case ISD::SELECT_CC:
13753     return DAGCombineTruncBoolExt(N, DCI);
13754   case ISD::SINT_TO_FP:
13755   case ISD::UINT_TO_FP:
13756     return combineFPToIntToFP(N, DCI);
13757   case ISD::VECTOR_SHUFFLE:
13758     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13759       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13760       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13761     }
13762     break;
13763   case ISD::STORE: {
13764 
13765     EVT Op1VT = N->getOperand(1).getValueType();
13766     unsigned Opcode = N->getOperand(1).getOpcode();
13767 
13768     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13769       SDValue Val= combineStoreFPToInt(N, DCI);
13770       if (Val)
13771         return Val;
13772     }
13773 
13774     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13775       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13776       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13777       if (Val)
13778         return Val;
13779     }
13780 
13781     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13782     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13783         N->getOperand(1).getNode()->hasOneUse() &&
13784         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13785          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13786 
13787       // STBRX can only handle simple types and it makes no sense to store less
13788       // two bytes in byte-reversed order.
13789       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13790       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13791         break;
13792 
13793       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13794       // Do an any-extend to 32-bits if this is a half-word input.
13795       if (BSwapOp.getValueType() == MVT::i16)
13796         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13797 
13798       // If the type of BSWAP operand is wider than stored memory width
13799       // it need to be shifted to the right side before STBRX.
13800       if (Op1VT.bitsGT(mVT)) {
13801         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13802         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13803                               DAG.getConstant(Shift, dl, MVT::i32));
13804         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13805         if (Op1VT == MVT::i64)
13806           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13807       }
13808 
13809       SDValue Ops[] = {
13810         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13811       };
13812       return
13813         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13814                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13815                                 cast<StoreSDNode>(N)->getMemOperand());
13816     }
13817 
13818     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13819     // So it can increase the chance of CSE constant construction.
13820     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13821         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13822       // Need to sign-extended to 64-bits to handle negative values.
13823       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13824       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13825                                     MemVT.getSizeInBits());
13826       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13827 
13828       // DAG.getTruncStore() can't be used here because it doesn't accept
13829       // the general (base + offset) addressing mode.
13830       // So we use UpdateNodeOperands and setTruncatingStore instead.
13831       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13832                              N->getOperand(3));
13833       cast<StoreSDNode>(N)->setTruncatingStore(true);
13834       return SDValue(N, 0);
13835     }
13836 
13837     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13838     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13839     if (Op1VT.isSimple()) {
13840       MVT StoreVT = Op1VT.getSimpleVT();
13841       if (Subtarget.needsSwapsForVSXMemOps() &&
13842           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13843            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13844         return expandVSXStoreForLE(N, DCI);
13845     }
13846     break;
13847   }
13848   case ISD::LOAD: {
13849     LoadSDNode *LD = cast<LoadSDNode>(N);
13850     EVT VT = LD->getValueType(0);
13851 
13852     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13853     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13854     if (VT.isSimple()) {
13855       MVT LoadVT = VT.getSimpleVT();
13856       if (Subtarget.needsSwapsForVSXMemOps() &&
13857           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13858            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13859         return expandVSXLoadForLE(N, DCI);
13860     }
13861 
13862     // We sometimes end up with a 64-bit integer load, from which we extract
13863     // two single-precision floating-point numbers. This happens with
13864     // std::complex<float>, and other similar structures, because of the way we
13865     // canonicalize structure copies. However, if we lack direct moves,
13866     // then the final bitcasts from the extracted integer values to the
13867     // floating-point numbers turn into store/load pairs. Even with direct moves,
13868     // just loading the two floating-point numbers is likely better.
13869     auto ReplaceTwoFloatLoad = [&]() {
13870       if (VT != MVT::i64)
13871         return false;
13872 
13873       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13874           LD->isVolatile())
13875         return false;
13876 
13877       //  We're looking for a sequence like this:
13878       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13879       //      t16: i64 = srl t13, Constant:i32<32>
13880       //    t17: i32 = truncate t16
13881       //  t18: f32 = bitcast t17
13882       //    t19: i32 = truncate t13
13883       //  t20: f32 = bitcast t19
13884 
13885       if (!LD->hasNUsesOfValue(2, 0))
13886         return false;
13887 
13888       auto UI = LD->use_begin();
13889       while (UI.getUse().getResNo() != 0) ++UI;
13890       SDNode *Trunc = *UI++;
13891       while (UI.getUse().getResNo() != 0) ++UI;
13892       SDNode *RightShift = *UI;
13893       if (Trunc->getOpcode() != ISD::TRUNCATE)
13894         std::swap(Trunc, RightShift);
13895 
13896       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13897           Trunc->getValueType(0) != MVT::i32 ||
13898           !Trunc->hasOneUse())
13899         return false;
13900       if (RightShift->getOpcode() != ISD::SRL ||
13901           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13902           RightShift->getConstantOperandVal(1) != 32 ||
13903           !RightShift->hasOneUse())
13904         return false;
13905 
13906       SDNode *Trunc2 = *RightShift->use_begin();
13907       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13908           Trunc2->getValueType(0) != MVT::i32 ||
13909           !Trunc2->hasOneUse())
13910         return false;
13911 
13912       SDNode *Bitcast = *Trunc->use_begin();
13913       SDNode *Bitcast2 = *Trunc2->use_begin();
13914 
13915       if (Bitcast->getOpcode() != ISD::BITCAST ||
13916           Bitcast->getValueType(0) != MVT::f32)
13917         return false;
13918       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13919           Bitcast2->getValueType(0) != MVT::f32)
13920         return false;
13921 
13922       if (Subtarget.isLittleEndian())
13923         std::swap(Bitcast, Bitcast2);
13924 
13925       // Bitcast has the second float (in memory-layout order) and Bitcast2
13926       // has the first one.
13927 
13928       SDValue BasePtr = LD->getBasePtr();
13929       if (LD->isIndexed()) {
13930         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13931                "Non-pre-inc AM on PPC?");
13932         BasePtr =
13933           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13934                       LD->getOffset());
13935       }
13936 
13937       auto MMOFlags =
13938           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13939       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13940                                       LD->getPointerInfo(), LD->getAlignment(),
13941                                       MMOFlags, LD->getAAInfo());
13942       SDValue AddPtr =
13943         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13944                     BasePtr, DAG.getIntPtrConstant(4, dl));
13945       SDValue FloatLoad2 = DAG.getLoad(
13946           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13947           LD->getPointerInfo().getWithOffset(4),
13948           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13949 
13950       if (LD->isIndexed()) {
13951         // Note that DAGCombine should re-form any pre-increment load(s) from
13952         // what is produced here if that makes sense.
13953         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13954       }
13955 
13956       DCI.CombineTo(Bitcast2, FloatLoad);
13957       DCI.CombineTo(Bitcast, FloatLoad2);
13958 
13959       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13960                                     SDValue(FloatLoad2.getNode(), 1));
13961       return true;
13962     };
13963 
13964     if (ReplaceTwoFloatLoad())
13965       return SDValue(N, 0);
13966 
13967     EVT MemVT = LD->getMemoryVT();
13968     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13969     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13970     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13971     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13972     if (LD->isUnindexed() && VT.isVector() &&
13973         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13974           // P8 and later hardware should just use LOAD.
13975           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13976                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13977          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13978           LD->getAlignment() >= ScalarABIAlignment)) &&
13979         LD->getAlignment() < ABIAlignment) {
13980       // This is a type-legal unaligned Altivec or QPX load.
13981       SDValue Chain = LD->getChain();
13982       SDValue Ptr = LD->getBasePtr();
13983       bool isLittleEndian = Subtarget.isLittleEndian();
13984 
13985       // This implements the loading of unaligned vectors as described in
13986       // the venerable Apple Velocity Engine overview. Specifically:
13987       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13988       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13989       //
13990       // The general idea is to expand a sequence of one or more unaligned
13991       // loads into an alignment-based permutation-control instruction (lvsl
13992       // or lvsr), a series of regular vector loads (which always truncate
13993       // their input address to an aligned address), and a series of
13994       // permutations.  The results of these permutations are the requested
13995       // loaded values.  The trick is that the last "extra" load is not taken
13996       // from the address you might suspect (sizeof(vector) bytes after the
13997       // last requested load), but rather sizeof(vector) - 1 bytes after the
13998       // last requested vector. The point of this is to avoid a page fault if
13999       // the base address happened to be aligned. This works because if the
14000       // base address is aligned, then adding less than a full vector length
14001       // will cause the last vector in the sequence to be (re)loaded.
14002       // Otherwise, the next vector will be fetched as you might suspect was
14003       // necessary.
14004 
14005       // We might be able to reuse the permutation generation from
14006       // a different base address offset from this one by an aligned amount.
14007       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14008       // optimization later.
14009       Intrinsic::ID Intr, IntrLD, IntrPerm;
14010       MVT PermCntlTy, PermTy, LDTy;
14011       if (Subtarget.hasAltivec()) {
14012         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14013                                  Intrinsic::ppc_altivec_lvsl;
14014         IntrLD = Intrinsic::ppc_altivec_lvx;
14015         IntrPerm = Intrinsic::ppc_altivec_vperm;
14016         PermCntlTy = MVT::v16i8;
14017         PermTy = MVT::v4i32;
14018         LDTy = MVT::v4i32;
14019       } else {
14020         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14021                                        Intrinsic::ppc_qpx_qvlpcls;
14022         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14023                                        Intrinsic::ppc_qpx_qvlfs;
14024         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14025         PermCntlTy = MVT::v4f64;
14026         PermTy = MVT::v4f64;
14027         LDTy = MemVT.getSimpleVT();
14028       }
14029 
14030       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14031 
14032       // Create the new MMO for the new base load. It is like the original MMO,
14033       // but represents an area in memory almost twice the vector size centered
14034       // on the original address. If the address is unaligned, we might start
14035       // reading up to (sizeof(vector)-1) bytes below the address of the
14036       // original unaligned load.
14037       MachineFunction &MF = DAG.getMachineFunction();
14038       MachineMemOperand *BaseMMO =
14039         MF.getMachineMemOperand(LD->getMemOperand(),
14040                                 -(long)MemVT.getStoreSize()+1,
14041                                 2*MemVT.getStoreSize()-1);
14042 
14043       // Create the new base load.
14044       SDValue LDXIntID =
14045           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14046       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14047       SDValue BaseLoad =
14048         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14049                                 DAG.getVTList(PermTy, MVT::Other),
14050                                 BaseLoadOps, LDTy, BaseMMO);
14051 
14052       // Note that the value of IncOffset (which is provided to the next
14053       // load's pointer info offset value, and thus used to calculate the
14054       // alignment), and the value of IncValue (which is actually used to
14055       // increment the pointer value) are different! This is because we
14056       // require the next load to appear to be aligned, even though it
14057       // is actually offset from the base pointer by a lesser amount.
14058       int IncOffset = VT.getSizeInBits() / 8;
14059       int IncValue = IncOffset;
14060 
14061       // Walk (both up and down) the chain looking for another load at the real
14062       // (aligned) offset (the alignment of the other load does not matter in
14063       // this case). If found, then do not use the offset reduction trick, as
14064       // that will prevent the loads from being later combined (as they would
14065       // otherwise be duplicates).
14066       if (!findConsecutiveLoad(LD, DAG))
14067         --IncValue;
14068 
14069       SDValue Increment =
14070           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14071       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14072 
14073       MachineMemOperand *ExtraMMO =
14074         MF.getMachineMemOperand(LD->getMemOperand(),
14075                                 1, 2*MemVT.getStoreSize()-1);
14076       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14077       SDValue ExtraLoad =
14078         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14079                                 DAG.getVTList(PermTy, MVT::Other),
14080                                 ExtraLoadOps, LDTy, ExtraMMO);
14081 
14082       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14083         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14084 
14085       // Because vperm has a big-endian bias, we must reverse the order
14086       // of the input vectors and complement the permute control vector
14087       // when generating little endian code.  We have already handled the
14088       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14089       // and ExtraLoad here.
14090       SDValue Perm;
14091       if (isLittleEndian)
14092         Perm = BuildIntrinsicOp(IntrPerm,
14093                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14094       else
14095         Perm = BuildIntrinsicOp(IntrPerm,
14096                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14097 
14098       if (VT != PermTy)
14099         Perm = Subtarget.hasAltivec() ?
14100                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14101                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14102                                DAG.getTargetConstant(1, dl, MVT::i64));
14103                                // second argument is 1 because this rounding
14104                                // is always exact.
14105 
14106       // The output of the permutation is our loaded result, the TokenFactor is
14107       // our new chain.
14108       DCI.CombineTo(N, Perm, TF);
14109       return SDValue(N, 0);
14110     }
14111     }
14112     break;
14113     case ISD::INTRINSIC_WO_CHAIN: {
14114       bool isLittleEndian = Subtarget.isLittleEndian();
14115       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14116       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14117                                            : Intrinsic::ppc_altivec_lvsl);
14118       if ((IID == Intr ||
14119            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14120            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14121         N->getOperand(1)->getOpcode() == ISD::ADD) {
14122         SDValue Add = N->getOperand(1);
14123 
14124         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14125                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14126 
14127         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14128                                   APInt::getAllOnesValue(Bits /* alignment */)
14129                                       .zext(Add.getScalarValueSizeInBits()))) {
14130           SDNode *BasePtr = Add->getOperand(0).getNode();
14131           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14132                                     UE = BasePtr->use_end();
14133                UI != UE; ++UI) {
14134             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14135                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14136               // We've found another LVSL/LVSR, and this address is an aligned
14137               // multiple of that one. The results will be the same, so use the
14138               // one we've just found instead.
14139 
14140               return SDValue(*UI, 0);
14141             }
14142           }
14143         }
14144 
14145         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14146           SDNode *BasePtr = Add->getOperand(0).getNode();
14147           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14148                UE = BasePtr->use_end(); UI != UE; ++UI) {
14149             if (UI->getOpcode() == ISD::ADD &&
14150                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14151                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14152                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14153                 (1ULL << Bits) == 0) {
14154               SDNode *OtherAdd = *UI;
14155               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14156                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14157                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14158                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14159                   return SDValue(*VI, 0);
14160                 }
14161               }
14162             }
14163           }
14164         }
14165       }
14166 
14167       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14168       // Expose the vabsduw/h/b opportunity for down stream
14169       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14170           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14171            IID == Intrinsic::ppc_altivec_vmaxsh ||
14172            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14173         SDValue V1 = N->getOperand(1);
14174         SDValue V2 = N->getOperand(2);
14175         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14176              V1.getSimpleValueType() == MVT::v8i16 ||
14177              V1.getSimpleValueType() == MVT::v16i8) &&
14178             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14179           // (0-a, a)
14180           if (V1.getOpcode() == ISD::SUB &&
14181               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14182               V1.getOperand(1) == V2) {
14183             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14184           }
14185           // (a, 0-a)
14186           if (V2.getOpcode() == ISD::SUB &&
14187               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14188               V2.getOperand(1) == V1) {
14189             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14190           }
14191           // (x-y, y-x)
14192           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14193               V1.getOperand(0) == V2.getOperand(1) &&
14194               V1.getOperand(1) == V2.getOperand(0)) {
14195             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14196           }
14197         }
14198       }
14199     }
14200 
14201     break;
14202   case ISD::INTRINSIC_W_CHAIN:
14203     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14204     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14205     if (Subtarget.needsSwapsForVSXMemOps()) {
14206       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14207       default:
14208         break;
14209       case Intrinsic::ppc_vsx_lxvw4x:
14210       case Intrinsic::ppc_vsx_lxvd2x:
14211         return expandVSXLoadForLE(N, DCI);
14212       }
14213     }
14214     break;
14215   case ISD::INTRINSIC_VOID:
14216     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14217     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14218     if (Subtarget.needsSwapsForVSXMemOps()) {
14219       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14220       default:
14221         break;
14222       case Intrinsic::ppc_vsx_stxvw4x:
14223       case Intrinsic::ppc_vsx_stxvd2x:
14224         return expandVSXStoreForLE(N, DCI);
14225       }
14226     }
14227     break;
14228   case ISD::BSWAP:
14229     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14230     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14231         N->getOperand(0).hasOneUse() &&
14232         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14233          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14234           N->getValueType(0) == MVT::i64))) {
14235       SDValue Load = N->getOperand(0);
14236       LoadSDNode *LD = cast<LoadSDNode>(Load);
14237       // Create the byte-swapping load.
14238       SDValue Ops[] = {
14239         LD->getChain(),    // Chain
14240         LD->getBasePtr(),  // Ptr
14241         DAG.getValueType(N->getValueType(0)) // VT
14242       };
14243       SDValue BSLoad =
14244         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14245                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14246                                               MVT::i64 : MVT::i32, MVT::Other),
14247                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14248 
14249       // If this is an i16 load, insert the truncate.
14250       SDValue ResVal = BSLoad;
14251       if (N->getValueType(0) == MVT::i16)
14252         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14253 
14254       // First, combine the bswap away.  This makes the value produced by the
14255       // load dead.
14256       DCI.CombineTo(N, ResVal);
14257 
14258       // Next, combine the load away, we give it a bogus result value but a real
14259       // chain result.  The result value is dead because the bswap is dead.
14260       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14261 
14262       // Return N so it doesn't get rechecked!
14263       return SDValue(N, 0);
14264     }
14265     break;
14266   case PPCISD::VCMP:
14267     // If a VCMPo node already exists with exactly the same operands as this
14268     // node, use its result instead of this node (VCMPo computes both a CR6 and
14269     // a normal output).
14270     //
14271     if (!N->getOperand(0).hasOneUse() &&
14272         !N->getOperand(1).hasOneUse() &&
14273         !N->getOperand(2).hasOneUse()) {
14274 
14275       // Scan all of the users of the LHS, looking for VCMPo's that match.
14276       SDNode *VCMPoNode = nullptr;
14277 
14278       SDNode *LHSN = N->getOperand(0).getNode();
14279       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14280            UI != E; ++UI)
14281         if (UI->getOpcode() == PPCISD::VCMPo &&
14282             UI->getOperand(1) == N->getOperand(1) &&
14283             UI->getOperand(2) == N->getOperand(2) &&
14284             UI->getOperand(0) == N->getOperand(0)) {
14285           VCMPoNode = *UI;
14286           break;
14287         }
14288 
14289       // If there is no VCMPo node, or if the flag value has a single use, don't
14290       // transform this.
14291       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14292         break;
14293 
14294       // Look at the (necessarily single) use of the flag value.  If it has a
14295       // chain, this transformation is more complex.  Note that multiple things
14296       // could use the value result, which we should ignore.
14297       SDNode *FlagUser = nullptr;
14298       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14299            FlagUser == nullptr; ++UI) {
14300         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14301         SDNode *User = *UI;
14302         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14303           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14304             FlagUser = User;
14305             break;
14306           }
14307         }
14308       }
14309 
14310       // If the user is a MFOCRF instruction, we know this is safe.
14311       // Otherwise we give up for right now.
14312       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14313         return SDValue(VCMPoNode, 0);
14314     }
14315     break;
14316   case ISD::BRCOND: {
14317     SDValue Cond = N->getOperand(1);
14318     SDValue Target = N->getOperand(2);
14319 
14320     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14321         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14322           Intrinsic::loop_decrement) {
14323 
14324       // We now need to make the intrinsic dead (it cannot be instruction
14325       // selected).
14326       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14327       assert(Cond.getNode()->hasOneUse() &&
14328              "Counter decrement has more than one use");
14329 
14330       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14331                          N->getOperand(0), Target);
14332     }
14333   }
14334   break;
14335   case ISD::BR_CC: {
14336     // If this is a branch on an altivec predicate comparison, lower this so
14337     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14338     // lowering is done pre-legalize, because the legalizer lowers the predicate
14339     // compare down to code that is difficult to reassemble.
14340     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14341     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14342 
14343     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14344     // value. If so, pass-through the AND to get to the intrinsic.
14345     if (LHS.getOpcode() == ISD::AND &&
14346         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14347         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14348           Intrinsic::loop_decrement &&
14349         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14350         !isNullConstant(LHS.getOperand(1)))
14351       LHS = LHS.getOperand(0);
14352 
14353     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14354         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14355           Intrinsic::loop_decrement &&
14356         isa<ConstantSDNode>(RHS)) {
14357       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14358              "Counter decrement comparison is not EQ or NE");
14359 
14360       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14361       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14362                     (CC == ISD::SETNE && !Val);
14363 
14364       // We now need to make the intrinsic dead (it cannot be instruction
14365       // selected).
14366       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14367       assert(LHS.getNode()->hasOneUse() &&
14368              "Counter decrement has more than one use");
14369 
14370       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14371                          N->getOperand(0), N->getOperand(4));
14372     }
14373 
14374     int CompareOpc;
14375     bool isDot;
14376 
14377     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14378         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14379         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14380       assert(isDot && "Can't compare against a vector result!");
14381 
14382       // If this is a comparison against something other than 0/1, then we know
14383       // that the condition is never/always true.
14384       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14385       if (Val != 0 && Val != 1) {
14386         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14387           return N->getOperand(0);
14388         // Always !=, turn it into an unconditional branch.
14389         return DAG.getNode(ISD::BR, dl, MVT::Other,
14390                            N->getOperand(0), N->getOperand(4));
14391       }
14392 
14393       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14394 
14395       // Create the PPCISD altivec 'dot' comparison node.
14396       SDValue Ops[] = {
14397         LHS.getOperand(2),  // LHS of compare
14398         LHS.getOperand(3),  // RHS of compare
14399         DAG.getConstant(CompareOpc, dl, MVT::i32)
14400       };
14401       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14402       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14403 
14404       // Unpack the result based on how the target uses it.
14405       PPC::Predicate CompOpc;
14406       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14407       default:  // Can't happen, don't crash on invalid number though.
14408       case 0:   // Branch on the value of the EQ bit of CR6.
14409         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14410         break;
14411       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14412         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14413         break;
14414       case 2:   // Branch on the value of the LT bit of CR6.
14415         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14416         break;
14417       case 3:   // Branch on the inverted value of the LT bit of CR6.
14418         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14419         break;
14420       }
14421 
14422       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14423                          DAG.getConstant(CompOpc, dl, MVT::i32),
14424                          DAG.getRegister(PPC::CR6, MVT::i32),
14425                          N->getOperand(4), CompNode.getValue(1));
14426     }
14427     break;
14428   }
14429   case ISD::BUILD_VECTOR:
14430     return DAGCombineBuildVector(N, DCI);
14431   case ISD::ABS:
14432     return combineABS(N, DCI);
14433   case ISD::VSELECT:
14434     return combineVSelect(N, DCI);
14435   }
14436 
14437   return SDValue();
14438 }
14439 
14440 SDValue
14441 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14442                                  SelectionDAG &DAG,
14443                                  SmallVectorImpl<SDNode *> &Created) const {
14444   // fold (sdiv X, pow2)
14445   EVT VT = N->getValueType(0);
14446   if (VT == MVT::i64 && !Subtarget.isPPC64())
14447     return SDValue();
14448   if ((VT != MVT::i32 && VT != MVT::i64) ||
14449       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14450     return SDValue();
14451 
14452   SDLoc DL(N);
14453   SDValue N0 = N->getOperand(0);
14454 
14455   bool IsNegPow2 = (-Divisor).isPowerOf2();
14456   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14457   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14458 
14459   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14460   Created.push_back(Op.getNode());
14461 
14462   if (IsNegPow2) {
14463     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14464     Created.push_back(Op.getNode());
14465   }
14466 
14467   return Op;
14468 }
14469 
14470 //===----------------------------------------------------------------------===//
14471 // Inline Assembly Support
14472 //===----------------------------------------------------------------------===//
14473 
14474 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14475                                                       KnownBits &Known,
14476                                                       const APInt &DemandedElts,
14477                                                       const SelectionDAG &DAG,
14478                                                       unsigned Depth) const {
14479   Known.resetAll();
14480   switch (Op.getOpcode()) {
14481   default: break;
14482   case PPCISD::LBRX: {
14483     // lhbrx is known to have the top bits cleared out.
14484     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14485       Known.Zero = 0xFFFF0000;
14486     break;
14487   }
14488   case ISD::INTRINSIC_WO_CHAIN: {
14489     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14490     default: break;
14491     case Intrinsic::ppc_altivec_vcmpbfp_p:
14492     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14493     case Intrinsic::ppc_altivec_vcmpequb_p:
14494     case Intrinsic::ppc_altivec_vcmpequh_p:
14495     case Intrinsic::ppc_altivec_vcmpequw_p:
14496     case Intrinsic::ppc_altivec_vcmpequd_p:
14497     case Intrinsic::ppc_altivec_vcmpgefp_p:
14498     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14499     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14500     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14501     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14502     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14503     case Intrinsic::ppc_altivec_vcmpgtub_p:
14504     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14505     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14506     case Intrinsic::ppc_altivec_vcmpgtud_p:
14507       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14508       break;
14509     }
14510   }
14511   }
14512 }
14513 
14514 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14515   switch (Subtarget.getCPUDirective()) {
14516   default: break;
14517   case PPC::DIR_970:
14518   case PPC::DIR_PWR4:
14519   case PPC::DIR_PWR5:
14520   case PPC::DIR_PWR5X:
14521   case PPC::DIR_PWR6:
14522   case PPC::DIR_PWR6X:
14523   case PPC::DIR_PWR7:
14524   case PPC::DIR_PWR8:
14525   case PPC::DIR_PWR9:
14526   case PPC::DIR_PWR_FUTURE: {
14527     if (!ML)
14528       break;
14529 
14530     if (!DisableInnermostLoopAlign32) {
14531       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14532       // so that we can decrease cache misses and branch-prediction misses.
14533       // Actual alignment of the loop will depend on the hotness check and other
14534       // logic in alignBlocks.
14535       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14536         return Align(32);
14537     }
14538 
14539     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14540 
14541     // For small loops (between 5 and 8 instructions), align to a 32-byte
14542     // boundary so that the entire loop fits in one instruction-cache line.
14543     uint64_t LoopSize = 0;
14544     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14545       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14546         LoopSize += TII->getInstSizeInBytes(*J);
14547         if (LoopSize > 32)
14548           break;
14549       }
14550 
14551     if (LoopSize > 16 && LoopSize <= 32)
14552       return Align(32);
14553 
14554     break;
14555   }
14556   }
14557 
14558   return TargetLowering::getPrefLoopAlignment(ML);
14559 }
14560 
14561 /// getConstraintType - Given a constraint, return the type of
14562 /// constraint it is for this target.
14563 PPCTargetLowering::ConstraintType
14564 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14565   if (Constraint.size() == 1) {
14566     switch (Constraint[0]) {
14567     default: break;
14568     case 'b':
14569     case 'r':
14570     case 'f':
14571     case 'd':
14572     case 'v':
14573     case 'y':
14574       return C_RegisterClass;
14575     case 'Z':
14576       // FIXME: While Z does indicate a memory constraint, it specifically
14577       // indicates an r+r address (used in conjunction with the 'y' modifier
14578       // in the replacement string). Currently, we're forcing the base
14579       // register to be r0 in the asm printer (which is interpreted as zero)
14580       // and forming the complete address in the second register. This is
14581       // suboptimal.
14582       return C_Memory;
14583     }
14584   } else if (Constraint == "wc") { // individual CR bits.
14585     return C_RegisterClass;
14586   } else if (Constraint == "wa" || Constraint == "wd" ||
14587              Constraint == "wf" || Constraint == "ws" ||
14588              Constraint == "wi" || Constraint == "ww") {
14589     return C_RegisterClass; // VSX registers.
14590   }
14591   return TargetLowering::getConstraintType(Constraint);
14592 }
14593 
14594 /// Examine constraint type and operand type and determine a weight value.
14595 /// This object must already have been set up with the operand type
14596 /// and the current alternative constraint selected.
14597 TargetLowering::ConstraintWeight
14598 PPCTargetLowering::getSingleConstraintMatchWeight(
14599     AsmOperandInfo &info, const char *constraint) const {
14600   ConstraintWeight weight = CW_Invalid;
14601   Value *CallOperandVal = info.CallOperandVal;
14602     // If we don't have a value, we can't do a match,
14603     // but allow it at the lowest weight.
14604   if (!CallOperandVal)
14605     return CW_Default;
14606   Type *type = CallOperandVal->getType();
14607 
14608   // Look at the constraint type.
14609   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14610     return CW_Register; // an individual CR bit.
14611   else if ((StringRef(constraint) == "wa" ||
14612             StringRef(constraint) == "wd" ||
14613             StringRef(constraint) == "wf") &&
14614            type->isVectorTy())
14615     return CW_Register;
14616   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14617     return CW_Register; // just hold 64-bit integers data.
14618   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14619     return CW_Register;
14620   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14621     return CW_Register;
14622 
14623   switch (*constraint) {
14624   default:
14625     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14626     break;
14627   case 'b':
14628     if (type->isIntegerTy())
14629       weight = CW_Register;
14630     break;
14631   case 'f':
14632     if (type->isFloatTy())
14633       weight = CW_Register;
14634     break;
14635   case 'd':
14636     if (type->isDoubleTy())
14637       weight = CW_Register;
14638     break;
14639   case 'v':
14640     if (type->isVectorTy())
14641       weight = CW_Register;
14642     break;
14643   case 'y':
14644     weight = CW_Register;
14645     break;
14646   case 'Z':
14647     weight = CW_Memory;
14648     break;
14649   }
14650   return weight;
14651 }
14652 
14653 std::pair<unsigned, const TargetRegisterClass *>
14654 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14655                                                 StringRef Constraint,
14656                                                 MVT VT) const {
14657   if (Constraint.size() == 1) {
14658     // GCC RS6000 Constraint Letters
14659     switch (Constraint[0]) {
14660     case 'b':   // R1-R31
14661       if (VT == MVT::i64 && Subtarget.isPPC64())
14662         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14663       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14664     case 'r':   // R0-R31
14665       if (VT == MVT::i64 && Subtarget.isPPC64())
14666         return std::make_pair(0U, &PPC::G8RCRegClass);
14667       return std::make_pair(0U, &PPC::GPRCRegClass);
14668     // 'd' and 'f' constraints are both defined to be "the floating point
14669     // registers", where one is for 32-bit and the other for 64-bit. We don't
14670     // really care overly much here so just give them all the same reg classes.
14671     case 'd':
14672     case 'f':
14673       if (Subtarget.hasSPE()) {
14674         if (VT == MVT::f32 || VT == MVT::i32)
14675           return std::make_pair(0U, &PPC::GPRCRegClass);
14676         if (VT == MVT::f64 || VT == MVT::i64)
14677           return std::make_pair(0U, &PPC::SPERCRegClass);
14678       } else {
14679         if (VT == MVT::f32 || VT == MVT::i32)
14680           return std::make_pair(0U, &PPC::F4RCRegClass);
14681         if (VT == MVT::f64 || VT == MVT::i64)
14682           return std::make_pair(0U, &PPC::F8RCRegClass);
14683         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14684           return std::make_pair(0U, &PPC::QFRCRegClass);
14685         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14686           return std::make_pair(0U, &PPC::QSRCRegClass);
14687       }
14688       break;
14689     case 'v':
14690       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14691         return std::make_pair(0U, &PPC::QFRCRegClass);
14692       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14693         return std::make_pair(0U, &PPC::QSRCRegClass);
14694       if (Subtarget.hasAltivec())
14695         return std::make_pair(0U, &PPC::VRRCRegClass);
14696       break;
14697     case 'y':   // crrc
14698       return std::make_pair(0U, &PPC::CRRCRegClass);
14699     }
14700   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14701     // An individual CR bit.
14702     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14703   } else if ((Constraint == "wa" || Constraint == "wd" ||
14704              Constraint == "wf" || Constraint == "wi") &&
14705              Subtarget.hasVSX()) {
14706     return std::make_pair(0U, &PPC::VSRCRegClass);
14707   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14708     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14709       return std::make_pair(0U, &PPC::VSSRCRegClass);
14710     else
14711       return std::make_pair(0U, &PPC::VSFRCRegClass);
14712   }
14713 
14714   // If we name a VSX register, we can't defer to the base class because it
14715   // will not recognize the correct register (their names will be VSL{0-31}
14716   // and V{0-31} so they won't match). So we match them here.
14717   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14718     int VSNum = atoi(Constraint.data() + 3);
14719     assert(VSNum >= 0 && VSNum <= 63 &&
14720            "Attempted to access a vsr out of range");
14721     if (VSNum < 32)
14722       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14723     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14724   }
14725   std::pair<unsigned, const TargetRegisterClass *> R =
14726       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14727 
14728   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14729   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14730   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14731   // register.
14732   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14733   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14734   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14735       PPC::GPRCRegClass.contains(R.first))
14736     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14737                             PPC::sub_32, &PPC::G8RCRegClass),
14738                           &PPC::G8RCRegClass);
14739 
14740   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14741   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14742     R.first = PPC::CR0;
14743     R.second = &PPC::CRRCRegClass;
14744   }
14745 
14746   return R;
14747 }
14748 
14749 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14750 /// vector.  If it is invalid, don't add anything to Ops.
14751 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14752                                                      std::string &Constraint,
14753                                                      std::vector<SDValue>&Ops,
14754                                                      SelectionDAG &DAG) const {
14755   SDValue Result;
14756 
14757   // Only support length 1 constraints.
14758   if (Constraint.length() > 1) return;
14759 
14760   char Letter = Constraint[0];
14761   switch (Letter) {
14762   default: break;
14763   case 'I':
14764   case 'J':
14765   case 'K':
14766   case 'L':
14767   case 'M':
14768   case 'N':
14769   case 'O':
14770   case 'P': {
14771     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14772     if (!CST) return; // Must be an immediate to match.
14773     SDLoc dl(Op);
14774     int64_t Value = CST->getSExtValue();
14775     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14776                          // numbers are printed as such.
14777     switch (Letter) {
14778     default: llvm_unreachable("Unknown constraint letter!");
14779     case 'I':  // "I" is a signed 16-bit constant.
14780       if (isInt<16>(Value))
14781         Result = DAG.getTargetConstant(Value, dl, TCVT);
14782       break;
14783     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14784       if (isShiftedUInt<16, 16>(Value))
14785         Result = DAG.getTargetConstant(Value, dl, TCVT);
14786       break;
14787     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14788       if (isShiftedInt<16, 16>(Value))
14789         Result = DAG.getTargetConstant(Value, dl, TCVT);
14790       break;
14791     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14792       if (isUInt<16>(Value))
14793         Result = DAG.getTargetConstant(Value, dl, TCVT);
14794       break;
14795     case 'M':  // "M" is a constant that is greater than 31.
14796       if (Value > 31)
14797         Result = DAG.getTargetConstant(Value, dl, TCVT);
14798       break;
14799     case 'N':  // "N" is a positive constant that is an exact power of two.
14800       if (Value > 0 && isPowerOf2_64(Value))
14801         Result = DAG.getTargetConstant(Value, dl, TCVT);
14802       break;
14803     case 'O':  // "O" is the constant zero.
14804       if (Value == 0)
14805         Result = DAG.getTargetConstant(Value, dl, TCVT);
14806       break;
14807     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14808       if (isInt<16>(-Value))
14809         Result = DAG.getTargetConstant(Value, dl, TCVT);
14810       break;
14811     }
14812     break;
14813   }
14814   }
14815 
14816   if (Result.getNode()) {
14817     Ops.push_back(Result);
14818     return;
14819   }
14820 
14821   // Handle standard constraint letters.
14822   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14823 }
14824 
14825 // isLegalAddressingMode - Return true if the addressing mode represented
14826 // by AM is legal for this target, for a load/store of the specified type.
14827 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14828                                               const AddrMode &AM, Type *Ty,
14829                                               unsigned AS, Instruction *I) const {
14830   // PPC does not allow r+i addressing modes for vectors!
14831   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14832     return false;
14833 
14834   // PPC allows a sign-extended 16-bit immediate field.
14835   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14836     return false;
14837 
14838   // No global is ever allowed as a base.
14839   if (AM.BaseGV)
14840     return false;
14841 
14842   // PPC only support r+r,
14843   switch (AM.Scale) {
14844   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14845     break;
14846   case 1:
14847     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14848       return false;
14849     // Otherwise we have r+r or r+i.
14850     break;
14851   case 2:
14852     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14853       return false;
14854     // Allow 2*r as r+r.
14855     break;
14856   default:
14857     // No other scales are supported.
14858     return false;
14859   }
14860 
14861   return true;
14862 }
14863 
14864 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14865                                            SelectionDAG &DAG) const {
14866   MachineFunction &MF = DAG.getMachineFunction();
14867   MachineFrameInfo &MFI = MF.getFrameInfo();
14868   MFI.setReturnAddressIsTaken(true);
14869 
14870   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14871     return SDValue();
14872 
14873   SDLoc dl(Op);
14874   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14875 
14876   // Make sure the function does not optimize away the store of the RA to
14877   // the stack.
14878   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14879   FuncInfo->setLRStoreRequired();
14880   bool isPPC64 = Subtarget.isPPC64();
14881   auto PtrVT = getPointerTy(MF.getDataLayout());
14882 
14883   if (Depth > 0) {
14884     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14885     SDValue Offset =
14886         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14887                         isPPC64 ? MVT::i64 : MVT::i32);
14888     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14889                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14890                        MachinePointerInfo());
14891   }
14892 
14893   // Just load the return address off the stack.
14894   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14895   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14896                      MachinePointerInfo());
14897 }
14898 
14899 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14900                                           SelectionDAG &DAG) const {
14901   SDLoc dl(Op);
14902   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14903 
14904   MachineFunction &MF = DAG.getMachineFunction();
14905   MachineFrameInfo &MFI = MF.getFrameInfo();
14906   MFI.setFrameAddressIsTaken(true);
14907 
14908   EVT PtrVT = getPointerTy(MF.getDataLayout());
14909   bool isPPC64 = PtrVT == MVT::i64;
14910 
14911   // Naked functions never have a frame pointer, and so we use r1. For all
14912   // other functions, this decision must be delayed until during PEI.
14913   unsigned FrameReg;
14914   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14915     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14916   else
14917     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14918 
14919   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14920                                          PtrVT);
14921   while (Depth--)
14922     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14923                             FrameAddr, MachinePointerInfo());
14924   return FrameAddr;
14925 }
14926 
14927 // FIXME? Maybe this could be a TableGen attribute on some registers and
14928 // this table could be generated automatically from RegInfo.
14929 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
14930                                               const MachineFunction &MF) const {
14931   bool isPPC64 = Subtarget.isPPC64();
14932   bool IsDarwinABI = Subtarget.isDarwinABI();
14933 
14934   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
14935   if (!is64Bit && VT != LLT::scalar(32))
14936     report_fatal_error("Invalid register global variable type");
14937 
14938   Register Reg = StringSwitch<Register>(RegName)
14939                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14940                    .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2)
14941                    .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() :
14942                                   (is64Bit ? PPC::X13 : PPC::R13))
14943                    .Default(Register());
14944 
14945   if (Reg)
14946     return Reg;
14947   report_fatal_error("Invalid register name global variable");
14948 }
14949 
14950 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14951   // 32-bit SVR4 ABI access everything as got-indirect.
14952   if (Subtarget.is32BitELFABI())
14953     return true;
14954 
14955   // AIX accesses everything indirectly through the TOC, which is similar to
14956   // the GOT.
14957   if (Subtarget.isAIXABI())
14958     return true;
14959 
14960   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14961   // If it is small or large code model, module locals are accessed
14962   // indirectly by loading their address from .toc/.got.
14963   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14964     return true;
14965 
14966   // JumpTable and BlockAddress are accessed as got-indirect.
14967   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14968     return true;
14969 
14970   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14971     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14972 
14973   return false;
14974 }
14975 
14976 bool
14977 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14978   // The PowerPC target isn't yet aware of offsets.
14979   return false;
14980 }
14981 
14982 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14983                                            const CallInst &I,
14984                                            MachineFunction &MF,
14985                                            unsigned Intrinsic) const {
14986   switch (Intrinsic) {
14987   case Intrinsic::ppc_qpx_qvlfd:
14988   case Intrinsic::ppc_qpx_qvlfs:
14989   case Intrinsic::ppc_qpx_qvlfcd:
14990   case Intrinsic::ppc_qpx_qvlfcs:
14991   case Intrinsic::ppc_qpx_qvlfiwa:
14992   case Intrinsic::ppc_qpx_qvlfiwz:
14993   case Intrinsic::ppc_altivec_lvx:
14994   case Intrinsic::ppc_altivec_lvxl:
14995   case Intrinsic::ppc_altivec_lvebx:
14996   case Intrinsic::ppc_altivec_lvehx:
14997   case Intrinsic::ppc_altivec_lvewx:
14998   case Intrinsic::ppc_vsx_lxvd2x:
14999   case Intrinsic::ppc_vsx_lxvw4x: {
15000     EVT VT;
15001     switch (Intrinsic) {
15002     case Intrinsic::ppc_altivec_lvebx:
15003       VT = MVT::i8;
15004       break;
15005     case Intrinsic::ppc_altivec_lvehx:
15006       VT = MVT::i16;
15007       break;
15008     case Intrinsic::ppc_altivec_lvewx:
15009       VT = MVT::i32;
15010       break;
15011     case Intrinsic::ppc_vsx_lxvd2x:
15012       VT = MVT::v2f64;
15013       break;
15014     case Intrinsic::ppc_qpx_qvlfd:
15015       VT = MVT::v4f64;
15016       break;
15017     case Intrinsic::ppc_qpx_qvlfs:
15018       VT = MVT::v4f32;
15019       break;
15020     case Intrinsic::ppc_qpx_qvlfcd:
15021       VT = MVT::v2f64;
15022       break;
15023     case Intrinsic::ppc_qpx_qvlfcs:
15024       VT = MVT::v2f32;
15025       break;
15026     default:
15027       VT = MVT::v4i32;
15028       break;
15029     }
15030 
15031     Info.opc = ISD::INTRINSIC_W_CHAIN;
15032     Info.memVT = VT;
15033     Info.ptrVal = I.getArgOperand(0);
15034     Info.offset = -VT.getStoreSize()+1;
15035     Info.size = 2*VT.getStoreSize()-1;
15036     Info.align = Align::None();
15037     Info.flags = MachineMemOperand::MOLoad;
15038     return true;
15039   }
15040   case Intrinsic::ppc_qpx_qvlfda:
15041   case Intrinsic::ppc_qpx_qvlfsa:
15042   case Intrinsic::ppc_qpx_qvlfcda:
15043   case Intrinsic::ppc_qpx_qvlfcsa:
15044   case Intrinsic::ppc_qpx_qvlfiwaa:
15045   case Intrinsic::ppc_qpx_qvlfiwza: {
15046     EVT VT;
15047     switch (Intrinsic) {
15048     case Intrinsic::ppc_qpx_qvlfda:
15049       VT = MVT::v4f64;
15050       break;
15051     case Intrinsic::ppc_qpx_qvlfsa:
15052       VT = MVT::v4f32;
15053       break;
15054     case Intrinsic::ppc_qpx_qvlfcda:
15055       VT = MVT::v2f64;
15056       break;
15057     case Intrinsic::ppc_qpx_qvlfcsa:
15058       VT = MVT::v2f32;
15059       break;
15060     default:
15061       VT = MVT::v4i32;
15062       break;
15063     }
15064 
15065     Info.opc = ISD::INTRINSIC_W_CHAIN;
15066     Info.memVT = VT;
15067     Info.ptrVal = I.getArgOperand(0);
15068     Info.offset = 0;
15069     Info.size = VT.getStoreSize();
15070     Info.align = Align::None();
15071     Info.flags = MachineMemOperand::MOLoad;
15072     return true;
15073   }
15074   case Intrinsic::ppc_qpx_qvstfd:
15075   case Intrinsic::ppc_qpx_qvstfs:
15076   case Intrinsic::ppc_qpx_qvstfcd:
15077   case Intrinsic::ppc_qpx_qvstfcs:
15078   case Intrinsic::ppc_qpx_qvstfiw:
15079   case Intrinsic::ppc_altivec_stvx:
15080   case Intrinsic::ppc_altivec_stvxl:
15081   case Intrinsic::ppc_altivec_stvebx:
15082   case Intrinsic::ppc_altivec_stvehx:
15083   case Intrinsic::ppc_altivec_stvewx:
15084   case Intrinsic::ppc_vsx_stxvd2x:
15085   case Intrinsic::ppc_vsx_stxvw4x: {
15086     EVT VT;
15087     switch (Intrinsic) {
15088     case Intrinsic::ppc_altivec_stvebx:
15089       VT = MVT::i8;
15090       break;
15091     case Intrinsic::ppc_altivec_stvehx:
15092       VT = MVT::i16;
15093       break;
15094     case Intrinsic::ppc_altivec_stvewx:
15095       VT = MVT::i32;
15096       break;
15097     case Intrinsic::ppc_vsx_stxvd2x:
15098       VT = MVT::v2f64;
15099       break;
15100     case Intrinsic::ppc_qpx_qvstfd:
15101       VT = MVT::v4f64;
15102       break;
15103     case Intrinsic::ppc_qpx_qvstfs:
15104       VT = MVT::v4f32;
15105       break;
15106     case Intrinsic::ppc_qpx_qvstfcd:
15107       VT = MVT::v2f64;
15108       break;
15109     case Intrinsic::ppc_qpx_qvstfcs:
15110       VT = MVT::v2f32;
15111       break;
15112     default:
15113       VT = MVT::v4i32;
15114       break;
15115     }
15116 
15117     Info.opc = ISD::INTRINSIC_VOID;
15118     Info.memVT = VT;
15119     Info.ptrVal = I.getArgOperand(1);
15120     Info.offset = -VT.getStoreSize()+1;
15121     Info.size = 2*VT.getStoreSize()-1;
15122     Info.align = Align::None();
15123     Info.flags = MachineMemOperand::MOStore;
15124     return true;
15125   }
15126   case Intrinsic::ppc_qpx_qvstfda:
15127   case Intrinsic::ppc_qpx_qvstfsa:
15128   case Intrinsic::ppc_qpx_qvstfcda:
15129   case Intrinsic::ppc_qpx_qvstfcsa:
15130   case Intrinsic::ppc_qpx_qvstfiwa: {
15131     EVT VT;
15132     switch (Intrinsic) {
15133     case Intrinsic::ppc_qpx_qvstfda:
15134       VT = MVT::v4f64;
15135       break;
15136     case Intrinsic::ppc_qpx_qvstfsa:
15137       VT = MVT::v4f32;
15138       break;
15139     case Intrinsic::ppc_qpx_qvstfcda:
15140       VT = MVT::v2f64;
15141       break;
15142     case Intrinsic::ppc_qpx_qvstfcsa:
15143       VT = MVT::v2f32;
15144       break;
15145     default:
15146       VT = MVT::v4i32;
15147       break;
15148     }
15149 
15150     Info.opc = ISD::INTRINSIC_VOID;
15151     Info.memVT = VT;
15152     Info.ptrVal = I.getArgOperand(1);
15153     Info.offset = 0;
15154     Info.size = VT.getStoreSize();
15155     Info.align = Align::None();
15156     Info.flags = MachineMemOperand::MOStore;
15157     return true;
15158   }
15159   default:
15160     break;
15161   }
15162 
15163   return false;
15164 }
15165 
15166 /// getOptimalMemOpType - Returns the target specific optimal type for load
15167 /// and store operations as a result of memset, memcpy, and memmove
15168 /// lowering. If DstAlign is zero that means it's safe to destination
15169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
15170 /// means there isn't a need to check it against alignment requirement,
15171 /// probably because the source does not need to be loaded. If 'IsMemset' is
15172 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
15173 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
15174 /// source is constant so it does not need to be loaded.
15175 /// It returns EVT::Other if the type should be determined using generic
15176 /// target-independent logic.
15177 EVT PPCTargetLowering::getOptimalMemOpType(
15178     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
15179     bool ZeroMemset, bool MemcpyStrSrc,
15180     const AttributeList &FuncAttributes) const {
15181   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15182     // When expanding a memset, require at least two QPX instructions to cover
15183     // the cost of loading the value to be stored from the constant pool.
15184     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
15185        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
15186         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15187       return MVT::v4f64;
15188     }
15189 
15190     // We should use Altivec/VSX loads and stores when available. For unaligned
15191     // addresses, unaligned VSX loads are only fast starting with the P8.
15192     if (Subtarget.hasAltivec() && Size >= 16 &&
15193         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
15194          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15195       return MVT::v4i32;
15196   }
15197 
15198   if (Subtarget.isPPC64()) {
15199     return MVT::i64;
15200   }
15201 
15202   return MVT::i32;
15203 }
15204 
15205 /// Returns true if it is beneficial to convert a load of a constant
15206 /// to just the constant itself.
15207 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15208                                                           Type *Ty) const {
15209   assert(Ty->isIntegerTy());
15210 
15211   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15212   return !(BitSize == 0 || BitSize > 64);
15213 }
15214 
15215 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15216   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15217     return false;
15218   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15219   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15220   return NumBits1 == 64 && NumBits2 == 32;
15221 }
15222 
15223 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15224   if (!VT1.isInteger() || !VT2.isInteger())
15225     return false;
15226   unsigned NumBits1 = VT1.getSizeInBits();
15227   unsigned NumBits2 = VT2.getSizeInBits();
15228   return NumBits1 == 64 && NumBits2 == 32;
15229 }
15230 
15231 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15232   // Generally speaking, zexts are not free, but they are free when they can be
15233   // folded with other operations.
15234   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15235     EVT MemVT = LD->getMemoryVT();
15236     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15237          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15238         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15239          LD->getExtensionType() == ISD::ZEXTLOAD))
15240       return true;
15241   }
15242 
15243   // FIXME: Add other cases...
15244   //  - 32-bit shifts with a zext to i64
15245   //  - zext after ctlz, bswap, etc.
15246   //  - zext after and by a constant mask
15247 
15248   return TargetLowering::isZExtFree(Val, VT2);
15249 }
15250 
15251 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15252   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15253          "invalid fpext types");
15254   // Extending to float128 is not free.
15255   if (DestVT == MVT::f128)
15256     return false;
15257   return true;
15258 }
15259 
15260 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15261   return isInt<16>(Imm) || isUInt<16>(Imm);
15262 }
15263 
15264 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15265   return isInt<16>(Imm) || isUInt<16>(Imm);
15266 }
15267 
15268 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15269                                                        unsigned,
15270                                                        unsigned,
15271                                                        MachineMemOperand::Flags,
15272                                                        bool *Fast) const {
15273   if (DisablePPCUnaligned)
15274     return false;
15275 
15276   // PowerPC supports unaligned memory access for simple non-vector types.
15277   // Although accessing unaligned addresses is not as efficient as accessing
15278   // aligned addresses, it is generally more efficient than manual expansion,
15279   // and generally only traps for software emulation when crossing page
15280   // boundaries.
15281 
15282   if (!VT.isSimple())
15283     return false;
15284 
15285   if (VT.isFloatingPoint() && !VT.isVector() &&
15286       !Subtarget.allowsUnalignedFPAccess())
15287     return false;
15288 
15289   if (VT.getSimpleVT().isVector()) {
15290     if (Subtarget.hasVSX()) {
15291       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15292           VT != MVT::v4f32 && VT != MVT::v4i32)
15293         return false;
15294     } else {
15295       return false;
15296     }
15297   }
15298 
15299   if (VT == MVT::ppcf128)
15300     return false;
15301 
15302   if (Subtarget.isTargetOpenBSD()) {
15303     // Traditional PowerPC does not support unaligned memory access
15304     // for floating-point and the OpenBSD kernel does not emulate
15305     // all possible floating-point load and store instructions.
15306     if (VT == MVT::f32 || VT == MVT::f64)
15307       return false;
15308   }
15309 
15310   if (Fast)
15311     *Fast = true;
15312 
15313   return true;
15314 }
15315 
15316 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15317                                                    EVT VT) const {
15318   VT = VT.getScalarType();
15319 
15320   if (!VT.isSimple())
15321     return false;
15322 
15323   switch (VT.getSimpleVT().SimpleTy) {
15324   case MVT::f32:
15325   case MVT::f64:
15326     return true;
15327   case MVT::f128:
15328     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15329   default:
15330     break;
15331   }
15332 
15333   return false;
15334 }
15335 
15336 const MCPhysReg *
15337 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15338   // LR is a callee-save register, but we must treat it as clobbered by any call
15339   // site. Hence we include LR in the scratch registers, which are in turn added
15340   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15341   // to CTR, which is used by any indirect call.
15342   static const MCPhysReg ScratchRegs[] = {
15343     PPC::X12, PPC::LR8, PPC::CTR8, 0
15344   };
15345 
15346   return ScratchRegs;
15347 }
15348 
15349 unsigned PPCTargetLowering::getExceptionPointerRegister(
15350     const Constant *PersonalityFn) const {
15351   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15352 }
15353 
15354 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15355     const Constant *PersonalityFn) const {
15356   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15357 }
15358 
15359 bool
15360 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15361                      EVT VT , unsigned DefinedValues) const {
15362   if (VT == MVT::v2i64)
15363     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15364 
15365   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15366     return true;
15367 
15368   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15369 }
15370 
15371 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15372   if (DisableILPPref || Subtarget.enableMachineScheduler())
15373     return TargetLowering::getSchedulingPreference(N);
15374 
15375   return Sched::ILP;
15376 }
15377 
15378 // Create a fast isel object.
15379 FastISel *
15380 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15381                                   const TargetLibraryInfo *LibInfo) const {
15382   return PPC::createFastISel(FuncInfo, LibInfo);
15383 }
15384 
15385 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15386   if (Subtarget.isDarwinABI()) return;
15387   if (!Subtarget.isPPC64()) return;
15388 
15389   // Update IsSplitCSR in PPCFunctionInfo
15390   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15391   PFI->setIsSplitCSR(true);
15392 }
15393 
15394 void PPCTargetLowering::insertCopiesSplitCSR(
15395   MachineBasicBlock *Entry,
15396   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15397   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15398   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15399   if (!IStart)
15400     return;
15401 
15402   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15403   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15404   MachineBasicBlock::iterator MBBI = Entry->begin();
15405   for (const MCPhysReg *I = IStart; *I; ++I) {
15406     const TargetRegisterClass *RC = nullptr;
15407     if (PPC::G8RCRegClass.contains(*I))
15408       RC = &PPC::G8RCRegClass;
15409     else if (PPC::F8RCRegClass.contains(*I))
15410       RC = &PPC::F8RCRegClass;
15411     else if (PPC::CRRCRegClass.contains(*I))
15412       RC = &PPC::CRRCRegClass;
15413     else if (PPC::VRRCRegClass.contains(*I))
15414       RC = &PPC::VRRCRegClass;
15415     else
15416       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15417 
15418     Register NewVR = MRI->createVirtualRegister(RC);
15419     // Create copy from CSR to a virtual register.
15420     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15421     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15422     // nounwind. If we want to generalize this later, we may need to emit
15423     // CFI pseudo-instructions.
15424     assert(Entry->getParent()->getFunction().hasFnAttribute(
15425              Attribute::NoUnwind) &&
15426            "Function should be nounwind in insertCopiesSplitCSR!");
15427     Entry->addLiveIn(*I);
15428     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15429       .addReg(*I);
15430 
15431     // Insert the copy-back instructions right before the terminator.
15432     for (auto *Exit : Exits)
15433       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15434               TII->get(TargetOpcode::COPY), *I)
15435         .addReg(NewVR);
15436   }
15437 }
15438 
15439 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15440 bool PPCTargetLowering::useLoadStackGuardNode() const {
15441   if (!Subtarget.isTargetLinux())
15442     return TargetLowering::useLoadStackGuardNode();
15443   return true;
15444 }
15445 
15446 // Override to disable global variable loading on Linux.
15447 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15448   if (!Subtarget.isTargetLinux())
15449     return TargetLowering::insertSSPDeclarations(M);
15450 }
15451 
15452 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15453                                      bool ForCodeSize) const {
15454   if (!VT.isSimple() || !Subtarget.hasVSX())
15455     return false;
15456 
15457   switch(VT.getSimpleVT().SimpleTy) {
15458   default:
15459     // For FP types that are currently not supported by PPC backend, return
15460     // false. Examples: f16, f80.
15461     return false;
15462   case MVT::f32:
15463   case MVT::f64:
15464   case MVT::ppcf128:
15465     return Imm.isPosZero();
15466   }
15467 }
15468 
15469 // For vector shift operation op, fold
15470 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15471 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15472                                   SelectionDAG &DAG) {
15473   SDValue N0 = N->getOperand(0);
15474   SDValue N1 = N->getOperand(1);
15475   EVT VT = N0.getValueType();
15476   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15477   unsigned Opcode = N->getOpcode();
15478   unsigned TargetOpcode;
15479 
15480   switch (Opcode) {
15481   default:
15482     llvm_unreachable("Unexpected shift operation");
15483   case ISD::SHL:
15484     TargetOpcode = PPCISD::SHL;
15485     break;
15486   case ISD::SRL:
15487     TargetOpcode = PPCISD::SRL;
15488     break;
15489   case ISD::SRA:
15490     TargetOpcode = PPCISD::SRA;
15491     break;
15492   }
15493 
15494   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15495       N1->getOpcode() == ISD::AND)
15496     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15497       if (Mask->getZExtValue() == OpSizeInBits - 1)
15498         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15499 
15500   return SDValue();
15501 }
15502 
15503 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15504   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15505     return Value;
15506 
15507   SDValue N0 = N->getOperand(0);
15508   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15509   if (!Subtarget.isISA3_0() ||
15510       N0.getOpcode() != ISD::SIGN_EXTEND ||
15511       N0.getOperand(0).getValueType() != MVT::i32 ||
15512       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15513     return SDValue();
15514 
15515   // We can't save an operation here if the value is already extended, and
15516   // the existing shift is easier to combine.
15517   SDValue ExtsSrc = N0.getOperand(0);
15518   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15519       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15520     return SDValue();
15521 
15522   SDLoc DL(N0);
15523   SDValue ShiftBy = SDValue(CN1, 0);
15524   // We want the shift amount to be i32 on the extswli, but the shift could
15525   // have an i64.
15526   if (ShiftBy.getValueType() == MVT::i64)
15527     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15528 
15529   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15530                          ShiftBy);
15531 }
15532 
15533 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15534   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15535     return Value;
15536 
15537   return SDValue();
15538 }
15539 
15540 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15541   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15542     return Value;
15543 
15544   return SDValue();
15545 }
15546 
15547 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15548 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15549 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15550 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15551 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15552                                  const PPCSubtarget &Subtarget) {
15553   if (!Subtarget.isPPC64())
15554     return SDValue();
15555 
15556   SDValue LHS = N->getOperand(0);
15557   SDValue RHS = N->getOperand(1);
15558 
15559   auto isZextOfCompareWithConstant = [](SDValue Op) {
15560     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15561         Op.getValueType() != MVT::i64)
15562       return false;
15563 
15564     SDValue Cmp = Op.getOperand(0);
15565     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15566         Cmp.getOperand(0).getValueType() != MVT::i64)
15567       return false;
15568 
15569     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15570       int64_t NegConstant = 0 - Constant->getSExtValue();
15571       // Due to the limitations of the addi instruction,
15572       // -C is required to be [-32768, 32767].
15573       return isInt<16>(NegConstant);
15574     }
15575 
15576     return false;
15577   };
15578 
15579   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15580   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15581 
15582   // If there is a pattern, canonicalize a zext operand to the RHS.
15583   if (LHSHasPattern && !RHSHasPattern)
15584     std::swap(LHS, RHS);
15585   else if (!LHSHasPattern && !RHSHasPattern)
15586     return SDValue();
15587 
15588   SDLoc DL(N);
15589   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15590   SDValue Cmp = RHS.getOperand(0);
15591   SDValue Z = Cmp.getOperand(0);
15592   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15593 
15594   assert(Constant && "Constant Should not be a null pointer.");
15595   int64_t NegConstant = 0 - Constant->getSExtValue();
15596 
15597   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15598   default: break;
15599   case ISD::SETNE: {
15600     //                                 when C == 0
15601     //                             --> addze X, (addic Z, -1).carry
15602     //                            /
15603     // add X, (zext(setne Z, C))--
15604     //                            \    when -32768 <= -C <= 32767 && C != 0
15605     //                             --> addze X, (addic (addi Z, -C), -1).carry
15606     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15607                               DAG.getConstant(NegConstant, DL, MVT::i64));
15608     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15609     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15610                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15611     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15612                        SDValue(Addc.getNode(), 1));
15613     }
15614   case ISD::SETEQ: {
15615     //                                 when C == 0
15616     //                             --> addze X, (subfic Z, 0).carry
15617     //                            /
15618     // add X, (zext(sete  Z, C))--
15619     //                            \    when -32768 <= -C <= 32767 && C != 0
15620     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15621     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15622                               DAG.getConstant(NegConstant, DL, MVT::i64));
15623     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15624     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15625                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15626     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15627                        SDValue(Subc.getNode(), 1));
15628     }
15629   }
15630 
15631   return SDValue();
15632 }
15633 
15634 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15635   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15636     return Value;
15637 
15638   return SDValue();
15639 }
15640 
15641 // Detect TRUNCATE operations on bitcasts of float128 values.
15642 // What we are looking for here is the situtation where we extract a subset
15643 // of bits from a 128 bit float.
15644 // This can be of two forms:
15645 // 1) BITCAST of f128 feeding TRUNCATE
15646 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15647 // The reason this is required is because we do not have a legal i128 type
15648 // and so we want to prevent having to store the f128 and then reload part
15649 // of it.
15650 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15651                                            DAGCombinerInfo &DCI) const {
15652   // If we are using CRBits then try that first.
15653   if (Subtarget.useCRBits()) {
15654     // Check if CRBits did anything and return that if it did.
15655     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15656       return CRTruncValue;
15657   }
15658 
15659   SDLoc dl(N);
15660   SDValue Op0 = N->getOperand(0);
15661 
15662   // Looking for a truncate of i128 to i64.
15663   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15664     return SDValue();
15665 
15666   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15667 
15668   // SRL feeding TRUNCATE.
15669   if (Op0.getOpcode() == ISD::SRL) {
15670     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15671     // The right shift has to be by 64 bits.
15672     if (!ConstNode || ConstNode->getZExtValue() != 64)
15673       return SDValue();
15674 
15675     // Switch the element number to extract.
15676     EltToExtract = EltToExtract ? 0 : 1;
15677     // Update Op0 past the SRL.
15678     Op0 = Op0.getOperand(0);
15679   }
15680 
15681   // BITCAST feeding a TRUNCATE possibly via SRL.
15682   if (Op0.getOpcode() == ISD::BITCAST &&
15683       Op0.getValueType() == MVT::i128 &&
15684       Op0.getOperand(0).getValueType() == MVT::f128) {
15685     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15686     return DCI.DAG.getNode(
15687         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15688         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15689   }
15690   return SDValue();
15691 }
15692 
15693 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15694   SelectionDAG &DAG = DCI.DAG;
15695 
15696   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15697   if (!ConstOpOrElement)
15698     return SDValue();
15699 
15700   // An imul is usually smaller than the alternative sequence for legal type.
15701   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15702       isOperationLegal(ISD::MUL, N->getValueType(0)))
15703     return SDValue();
15704 
15705   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15706     switch (this->Subtarget.getCPUDirective()) {
15707     default:
15708       // TODO: enhance the condition for subtarget before pwr8
15709       return false;
15710     case PPC::DIR_PWR8:
15711       //  type        mul     add    shl
15712       // scalar        4       1      1
15713       // vector        7       2      2
15714       return true;
15715     case PPC::DIR_PWR9:
15716     case PPC::DIR_PWR_FUTURE:
15717       //  type        mul     add    shl
15718       // scalar        5       2      2
15719       // vector        7       2      2
15720 
15721       // The cycle RATIO of related operations are showed as a table above.
15722       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15723       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15724       // are 4, it is always profitable; but for 3 instrs patterns
15725       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15726       // So we should only do it for vector type.
15727       return IsAddOne && IsNeg ? VT.isVector() : true;
15728     }
15729   };
15730 
15731   EVT VT = N->getValueType(0);
15732   SDLoc DL(N);
15733 
15734   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15735   bool IsNeg = MulAmt.isNegative();
15736   APInt MulAmtAbs = MulAmt.abs();
15737 
15738   if ((MulAmtAbs - 1).isPowerOf2()) {
15739     // (mul x, 2^N + 1) => (add (shl x, N), x)
15740     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15741 
15742     if (!IsProfitable(IsNeg, true, VT))
15743       return SDValue();
15744 
15745     SDValue Op0 = N->getOperand(0);
15746     SDValue Op1 =
15747         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15748                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15749     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15750 
15751     if (!IsNeg)
15752       return Res;
15753 
15754     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15755   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15756     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15757     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15758 
15759     if (!IsProfitable(IsNeg, false, VT))
15760       return SDValue();
15761 
15762     SDValue Op0 = N->getOperand(0);
15763     SDValue Op1 =
15764         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15765                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15766 
15767     if (!IsNeg)
15768       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15769     else
15770       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15771 
15772   } else {
15773     return SDValue();
15774   }
15775 }
15776 
15777 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15778   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15779   if (!Subtarget.is64BitELFABI())
15780     return false;
15781 
15782   // If not a tail call then no need to proceed.
15783   if (!CI->isTailCall())
15784     return false;
15785 
15786   // If sibling calls have been disabled and tail-calls aren't guaranteed
15787   // there is no reason to duplicate.
15788   auto &TM = getTargetMachine();
15789   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15790     return false;
15791 
15792   // Can't tail call a function called indirectly, or if it has variadic args.
15793   const Function *Callee = CI->getCalledFunction();
15794   if (!Callee || Callee->isVarArg())
15795     return false;
15796 
15797   // Make sure the callee and caller calling conventions are eligible for tco.
15798   const Function *Caller = CI->getParent()->getParent();
15799   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15800                                            CI->getCallingConv()))
15801       return false;
15802 
15803   // If the function is local then we have a good chance at tail-calling it
15804   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15805 }
15806 
15807 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15808   if (!Subtarget.hasVSX())
15809     return false;
15810   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15811     return true;
15812   return VT == MVT::f32 || VT == MVT::f64 ||
15813     VT == MVT::v4f32 || VT == MVT::v2f64;
15814 }
15815 
15816 bool PPCTargetLowering::
15817 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15818   const Value *Mask = AndI.getOperand(1);
15819   // If the mask is suitable for andi. or andis. we should sink the and.
15820   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15821     // Can't handle constants wider than 64-bits.
15822     if (CI->getBitWidth() > 64)
15823       return false;
15824     int64_t ConstVal = CI->getZExtValue();
15825     return isUInt<16>(ConstVal) ||
15826       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15827   }
15828 
15829   // For non-constant masks, we can always use the record-form and.
15830   return true;
15831 }
15832 
15833 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15834 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15835 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15836 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15837 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15838 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15839   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15840   assert(Subtarget.hasP9Altivec() &&
15841          "Only combine this when P9 altivec supported!");
15842   EVT VT = N->getValueType(0);
15843   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15844     return SDValue();
15845 
15846   SelectionDAG &DAG = DCI.DAG;
15847   SDLoc dl(N);
15848   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15849     // Even for signed integers, if it's known to be positive (as signed
15850     // integer) due to zero-extended inputs.
15851     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15852     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15853     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15854          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15855         (SubOpcd1 == ISD::ZERO_EXTEND ||
15856          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15857       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15858                          N->getOperand(0)->getOperand(0),
15859                          N->getOperand(0)->getOperand(1),
15860                          DAG.getTargetConstant(0, dl, MVT::i32));
15861     }
15862 
15863     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15864     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15865         N->getOperand(0).hasOneUse()) {
15866       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15867                          N->getOperand(0)->getOperand(0),
15868                          N->getOperand(0)->getOperand(1),
15869                          DAG.getTargetConstant(1, dl, MVT::i32));
15870     }
15871   }
15872 
15873   return SDValue();
15874 }
15875 
15876 // For type v4i32/v8ii16/v16i8, transform
15877 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15878 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15879 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15880 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15881 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15882                                           DAGCombinerInfo &DCI) const {
15883   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15884   assert(Subtarget.hasP9Altivec() &&
15885          "Only combine this when P9 altivec supported!");
15886 
15887   SelectionDAG &DAG = DCI.DAG;
15888   SDLoc dl(N);
15889   SDValue Cond = N->getOperand(0);
15890   SDValue TrueOpnd = N->getOperand(1);
15891   SDValue FalseOpnd = N->getOperand(2);
15892   EVT VT = N->getOperand(1).getValueType();
15893 
15894   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15895       FalseOpnd.getOpcode() != ISD::SUB)
15896     return SDValue();
15897 
15898   // ABSD only available for type v4i32/v8i16/v16i8
15899   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15900     return SDValue();
15901 
15902   // At least to save one more dependent computation
15903   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15904     return SDValue();
15905 
15906   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15907 
15908   // Can only handle unsigned comparison here
15909   switch (CC) {
15910   default:
15911     return SDValue();
15912   case ISD::SETUGT:
15913   case ISD::SETUGE:
15914     break;
15915   case ISD::SETULT:
15916   case ISD::SETULE:
15917     std::swap(TrueOpnd, FalseOpnd);
15918     break;
15919   }
15920 
15921   SDValue CmpOpnd1 = Cond.getOperand(0);
15922   SDValue CmpOpnd2 = Cond.getOperand(1);
15923 
15924   // SETCC CmpOpnd1 CmpOpnd2 cond
15925   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15926   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15927   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15928       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15929       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15930       FalseOpnd.getOperand(1) == CmpOpnd1) {
15931     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15932                        CmpOpnd1, CmpOpnd2,
15933                        DAG.getTargetConstant(0, dl, MVT::i32));
15934   }
15935 
15936   return SDValue();
15937 }
15938