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   // Use _setjmp/_longjmp instead of setjmp/longjmp.
141   setUseUnderscoreSetJmp(true);
142   setUseUnderscoreLongJmp(true);
143 
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
175 
176   // PowerPC has pre-inc load and store's.
177   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
178   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
179   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
180   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
181   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
182   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
183   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
184   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
185   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
186   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
187   if (!Subtarget.hasSPE()) {
188     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
189     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
190     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
191     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
192   }
193 
194   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
195   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
196   for (MVT VT : ScalarIntVTs) {
197     setOperationAction(ISD::ADDC, VT, Legal);
198     setOperationAction(ISD::ADDE, VT, Legal);
199     setOperationAction(ISD::SUBC, VT, Legal);
200     setOperationAction(ISD::SUBE, VT, Legal);
201   }
202 
203   if (Subtarget.useCRBits()) {
204     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
205 
206     if (isPPC64 || Subtarget.hasFPCVT()) {
207       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
208       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
209                          isPPC64 ? MVT::i64 : MVT::i32);
210       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
211       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
212                         isPPC64 ? MVT::i64 : MVT::i32);
213     } else {
214       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
215       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
216     }
217 
218     // PowerPC does not support direct load/store of condition registers.
219     setOperationAction(ISD::LOAD, MVT::i1, Custom);
220     setOperationAction(ISD::STORE, MVT::i1, Custom);
221 
222     // FIXME: Remove this once the ANDI glue bug is fixed:
223     if (ANDIGlueBug)
224       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
225 
226     for (MVT VT : MVT::integer_valuetypes()) {
227       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
228       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
229       setTruncStoreAction(VT, MVT::i1, Expand);
230     }
231 
232     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
233   }
234 
235   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
236   // PPC (the libcall is not available).
237   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
238   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
239 
240   // We do not currently implement these libm ops for PowerPC.
241   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
242   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
243   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
244   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
245   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
246   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
247 
248   // PowerPC has no SREM/UREM instructions unless we are on P9
249   // On P9 we may use a hardware instruction to compute the remainder.
250   // The instructions are not legalized directly because in the cases where the
251   // result of both the remainder and the division is required it is more
252   // efficient to compute the remainder from the result of the division rather
253   // than use the remainder instruction.
254   if (Subtarget.isISA3_0()) {
255     setOperationAction(ISD::SREM, MVT::i32, Custom);
256     setOperationAction(ISD::UREM, MVT::i32, Custom);
257     setOperationAction(ISD::SREM, MVT::i64, Custom);
258     setOperationAction(ISD::UREM, MVT::i64, Custom);
259   } else {
260     setOperationAction(ISD::SREM, MVT::i32, Expand);
261     setOperationAction(ISD::UREM, MVT::i32, Expand);
262     setOperationAction(ISD::SREM, MVT::i64, Expand);
263     setOperationAction(ISD::UREM, MVT::i64, Expand);
264   }
265 
266   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
267   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
268   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
269   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
270   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
271   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
272   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
273   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
274   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
275 
276   // We don't support sin/cos/sqrt/fmod/pow
277   setOperationAction(ISD::FSIN , MVT::f64, Expand);
278   setOperationAction(ISD::FCOS , MVT::f64, Expand);
279   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
280   setOperationAction(ISD::FREM , MVT::f64, Expand);
281   setOperationAction(ISD::FPOW , MVT::f64, Expand);
282   setOperationAction(ISD::FSIN , MVT::f32, Expand);
283   setOperationAction(ISD::FCOS , MVT::f32, Expand);
284   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
285   setOperationAction(ISD::FREM , MVT::f32, Expand);
286   setOperationAction(ISD::FPOW , MVT::f32, Expand);
287   if (Subtarget.hasSPE()) {
288     setOperationAction(ISD::FMA  , MVT::f64, Expand);
289     setOperationAction(ISD::FMA  , MVT::f32, Expand);
290   } else {
291     setOperationAction(ISD::FMA  , MVT::f64, Legal);
292     setOperationAction(ISD::FMA  , MVT::f32, Legal);
293   }
294 
295   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
296 
297   // If we're enabling GP optimizations, use hardware square root
298   if (!Subtarget.hasFSQRT() &&
299       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
300         Subtarget.hasFRE()))
301     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
302 
303   if (!Subtarget.hasFSQRT() &&
304       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
305         Subtarget.hasFRES()))
306     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
307 
308   if (Subtarget.hasFCPSGN()) {
309     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
310     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
311   } else {
312     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
313     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
314   }
315 
316   if (Subtarget.hasFPRND()) {
317     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
318     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
319     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
320     setOperationAction(ISD::FROUND, MVT::f64, Legal);
321 
322     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
323     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
324     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
325     setOperationAction(ISD::FROUND, MVT::f32, Legal);
326   }
327 
328   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
329   // to speed up scalar BSWAP64.
330   // CTPOP or CTTZ were introduced in P8/P9 respectively
331   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
332   if (Subtarget.hasP9Vector())
333     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
334   else
335     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
336   if (Subtarget.isISA3_0()) {
337     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
338     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
339   } else {
340     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
341     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
342   }
343 
344   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
345     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
346     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
347   } else {
348     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
349     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
350   }
351 
352   // PowerPC does not have ROTR
353   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
354   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
355 
356   if (!Subtarget.useCRBits()) {
357     // PowerPC does not have Select
358     setOperationAction(ISD::SELECT, MVT::i32, Expand);
359     setOperationAction(ISD::SELECT, MVT::i64, Expand);
360     setOperationAction(ISD::SELECT, MVT::f32, Expand);
361     setOperationAction(ISD::SELECT, MVT::f64, Expand);
362   }
363 
364   // PowerPC wants to turn select_cc of FP into fsel when possible.
365   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
366   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
367 
368   // PowerPC wants to optimize integer setcc a bit
369   if (!Subtarget.useCRBits())
370     setOperationAction(ISD::SETCC, MVT::i32, Custom);
371 
372   // PowerPC does not have BRCOND which requires SetCC
373   if (!Subtarget.useCRBits())
374     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
375 
376   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
377 
378   if (Subtarget.hasSPE()) {
379     // SPE has built-in conversions
380     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
383   } else {
384     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
385     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
386 
387     // PowerPC does not have [U|S]INT_TO_FP
388     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
389     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
390   }
391 
392   if (Subtarget.hasDirectMove() && isPPC64) {
393     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
394     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
395     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
396     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
397   } else {
398     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
399     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
400     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
401     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
402   }
403 
404   // We cannot sextinreg(i1).  Expand to shifts.
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
406 
407   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
408   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
409   // support continuation, user-level threading, and etc.. As a result, no
410   // other SjLj exception interfaces are implemented and please don't build
411   // your own exception handling based on them.
412   // LLVM/Clang supports zero-cost DWARF exception handling.
413   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
414   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
415 
416   // We want to legalize GlobalAddress and ConstantPool nodes into the
417   // appropriate instructions to materialize the address.
418   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
419   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
420   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
421   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
422   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
423   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
424   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
425   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
426   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
427   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
428 
429   // TRAP is legal.
430   setOperationAction(ISD::TRAP, MVT::Other, Legal);
431 
432   // TRAMPOLINE is custom lowered.
433   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
434   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
435 
436   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
437   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
438 
439   if (Subtarget.is64BitELFABI()) {
440     // VAARG always uses double-word chunks, so promote anything smaller.
441     setOperationAction(ISD::VAARG, MVT::i1, Promote);
442     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
443     setOperationAction(ISD::VAARG, MVT::i8, Promote);
444     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
445     setOperationAction(ISD::VAARG, MVT::i16, Promote);
446     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
447     setOperationAction(ISD::VAARG, MVT::i32, Promote);
448     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
449     setOperationAction(ISD::VAARG, MVT::Other, Expand);
450   } else if (Subtarget.is32BitELFABI()) {
451     // VAARG is custom lowered with the 32-bit SVR4 ABI.
452     setOperationAction(ISD::VAARG, MVT::Other, Custom);
453     setOperationAction(ISD::VAARG, MVT::i64, Custom);
454   } else
455     setOperationAction(ISD::VAARG, MVT::Other, Expand);
456 
457   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
458   if (Subtarget.is32BitELFABI())
459     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
460   else
461     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
462 
463   // Use the default implementation.
464   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
465   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
466   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
467   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
468   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
469   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
470   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
471   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
472   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
473 
474   // We want to custom lower some of our intrinsics.
475   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
476 
477   // To handle counter-based loop conditions.
478   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
479 
480   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
481   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
482   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
483   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485   // Comparisons that require checking two conditions.
486   if (Subtarget.hasSPE()) {
487     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
488     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
489     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
490     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
491   }
492   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
493   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
494   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
495   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
496   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
497   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
498   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
499   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
500   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
501   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
502   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
503   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
504 
505   if (Subtarget.has64BitSupport()) {
506     // They also have instructions for converting between i64 and fp.
507     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
508     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
509     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
510     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
511     // This is just the low 32 bits of a (signed) fp->i64 conversion.
512     // We cannot do this with Promote because i64 is not a legal type.
513     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
514 
515     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
516       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
517   } else {
518     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
519     if (Subtarget.hasSPE())
520       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
521     else
522       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
523   }
524 
525   // With the instructions enabled under FPCVT, we can do everything.
526   if (Subtarget.hasFPCVT()) {
527     if (Subtarget.has64BitSupport()) {
528       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
529       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
530       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
531       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
532     }
533 
534     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
535     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
536     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
537     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
538   }
539 
540   if (Subtarget.use64BitRegs()) {
541     // 64-bit PowerPC implementations can support i64 types directly
542     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
543     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
544     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
545     // 64-bit PowerPC wants to expand i128 shifts itself.
546     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
547     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
548     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
549   } else {
550     // 32-bit PowerPC wants to expand i64 shifts itself.
551     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
552     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
553     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
554   }
555 
556   if (Subtarget.hasVSX()) {
557     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
558     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
559     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
560     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
561   }
562 
563   if (Subtarget.hasAltivec()) {
564     // First set operation action for all vector types to expand. Then we
565     // will selectively turn on ones that can be effectively codegen'd.
566     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
567       // add/sub are legal for all supported vector VT's.
568       setOperationAction(ISD::ADD, VT, Legal);
569       setOperationAction(ISD::SUB, VT, Legal);
570 
571       // For v2i64, these are only valid with P8Vector. This is corrected after
572       // the loop.
573       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
574         setOperationAction(ISD::SMAX, VT, Legal);
575         setOperationAction(ISD::SMIN, VT, Legal);
576         setOperationAction(ISD::UMAX, VT, Legal);
577         setOperationAction(ISD::UMIN, VT, Legal);
578       }
579       else {
580         setOperationAction(ISD::SMAX, VT, Expand);
581         setOperationAction(ISD::SMIN, VT, Expand);
582         setOperationAction(ISD::UMAX, VT, Expand);
583         setOperationAction(ISD::UMIN, VT, Expand);
584       }
585 
586       if (Subtarget.hasVSX()) {
587         setOperationAction(ISD::FMAXNUM, VT, Legal);
588         setOperationAction(ISD::FMINNUM, VT, Legal);
589       }
590 
591       // Vector instructions introduced in P8
592       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
593         setOperationAction(ISD::CTPOP, VT, Legal);
594         setOperationAction(ISD::CTLZ, VT, Legal);
595       }
596       else {
597         setOperationAction(ISD::CTPOP, VT, Expand);
598         setOperationAction(ISD::CTLZ, VT, Expand);
599       }
600 
601       // Vector instructions introduced in P9
602       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
603         setOperationAction(ISD::CTTZ, VT, Legal);
604       else
605         setOperationAction(ISD::CTTZ, VT, Expand);
606 
607       // We promote all shuffles to v16i8.
608       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
609       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
610 
611       // We promote all non-typed operations to v4i32.
612       setOperationAction(ISD::AND   , VT, Promote);
613       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
614       setOperationAction(ISD::OR    , VT, Promote);
615       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
616       setOperationAction(ISD::XOR   , VT, Promote);
617       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
618       setOperationAction(ISD::LOAD  , VT, Promote);
619       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
620       setOperationAction(ISD::SELECT, VT, Promote);
621       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
622       setOperationAction(ISD::VSELECT, VT, Legal);
623       setOperationAction(ISD::SELECT_CC, VT, Promote);
624       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
625       setOperationAction(ISD::STORE, VT, Promote);
626       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
627 
628       // No other operations are legal.
629       setOperationAction(ISD::MUL , VT, Expand);
630       setOperationAction(ISD::SDIV, VT, Expand);
631       setOperationAction(ISD::SREM, VT, Expand);
632       setOperationAction(ISD::UDIV, VT, Expand);
633       setOperationAction(ISD::UREM, VT, Expand);
634       setOperationAction(ISD::FDIV, VT, Expand);
635       setOperationAction(ISD::FREM, VT, Expand);
636       setOperationAction(ISD::FNEG, VT, Expand);
637       setOperationAction(ISD::FSQRT, VT, Expand);
638       setOperationAction(ISD::FLOG, VT, Expand);
639       setOperationAction(ISD::FLOG10, VT, Expand);
640       setOperationAction(ISD::FLOG2, VT, Expand);
641       setOperationAction(ISD::FEXP, VT, Expand);
642       setOperationAction(ISD::FEXP2, VT, Expand);
643       setOperationAction(ISD::FSIN, VT, Expand);
644       setOperationAction(ISD::FCOS, VT, Expand);
645       setOperationAction(ISD::FABS, VT, Expand);
646       setOperationAction(ISD::FFLOOR, VT, Expand);
647       setOperationAction(ISD::FCEIL,  VT, Expand);
648       setOperationAction(ISD::FTRUNC, VT, Expand);
649       setOperationAction(ISD::FRINT,  VT, Expand);
650       setOperationAction(ISD::FNEARBYINT, VT, Expand);
651       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
652       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
653       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
654       setOperationAction(ISD::MULHU, VT, Expand);
655       setOperationAction(ISD::MULHS, VT, Expand);
656       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
657       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
658       setOperationAction(ISD::UDIVREM, VT, Expand);
659       setOperationAction(ISD::SDIVREM, VT, Expand);
660       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
661       setOperationAction(ISD::FPOW, VT, Expand);
662       setOperationAction(ISD::BSWAP, VT, Expand);
663       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
664       setOperationAction(ISD::ROTL, VT, Expand);
665       setOperationAction(ISD::ROTR, VT, Expand);
666 
667       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
668         setTruncStoreAction(VT, InnerVT, Expand);
669         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
670         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
671         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
672       }
673     }
674     if (!Subtarget.hasP8Vector()) {
675       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
676       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
677       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
678       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
679     }
680 
681     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
682       setOperationAction(ISD::ABS, VT, Custom);
683 
684     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
685     // with merges, splats, etc.
686     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
687 
688     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
689     // are cheap, so handle them before they get expanded to scalar.
690     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
691     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
692     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
693     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
694     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
695 
696     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
697     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
698     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
699     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
700     setOperationAction(ISD::SELECT, MVT::v4i32,
701                        Subtarget.useCRBits() ? Legal : Expand);
702     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
703     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
704     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
705     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
706     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
707     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
708     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
709     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
710     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
711 
712     // Without hasP8Altivec set, v2i64 SMAX isn't available.
713     // But ABS custom lowering requires SMAX support.
714     if (!Subtarget.hasP8Altivec())
715       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
716 
717     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
718     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
719     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
720     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
721 
722     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
723     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
724 
725     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
726       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
727       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
728     }
729 
730     if (Subtarget.hasP8Altivec())
731       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
732     else
733       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
734 
735     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
736     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
737 
738     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
739     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
740 
741     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
742     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
743     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
744     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
745 
746     // Altivec does not contain unordered floating-point compare instructions
747     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
748     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
749     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
750     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
751 
752     if (Subtarget.hasVSX()) {
753       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
754       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
755       if (Subtarget.hasP8Vector()) {
756         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
757         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
758       }
759       if (Subtarget.hasDirectMove() && isPPC64) {
760         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
761         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
762         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
763         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
764         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
765         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
766         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
767         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
768       }
769       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
770 
771       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
772       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
773       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
774       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
775       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
776 
777       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
778 
779       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
780       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
781 
782       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
783       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
784 
785       // Share the Altivec comparison restrictions.
786       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
787       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
788       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
789       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
790 
791       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
792       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
793 
794       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
795 
796       if (Subtarget.hasP8Vector())
797         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
798 
799       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
800 
801       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
802       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
803       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
804 
805       if (Subtarget.hasP8Altivec()) {
806         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
807         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
808         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
809 
810         // 128 bit shifts can be accomplished via 3 instructions for SHL and
811         // SRL, but not for SRA because of the instructions available:
812         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
813         // doing
814         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
815         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
816         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
817 
818         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
819       }
820       else {
821         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
822         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
823         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
824 
825         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
826 
827         // VSX v2i64 only supports non-arithmetic operations.
828         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
829         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
830       }
831 
832       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
833       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
834       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
835       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
836 
837       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
838 
839       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
840       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
841       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
842       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
843 
844       // Custom handling for partial vectors of integers converted to
845       // floating point. We already have optimal handling for v2i32 through
846       // the DAG combine, so those aren't necessary.
847       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
848       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
849       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
850       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
851       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
852       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
853       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
854       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
855 
856       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
857       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
858       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
859       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
860       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
861       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
862 
863       if (Subtarget.hasDirectMove())
864         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
865       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
866 
867       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
868     }
869 
870     if (Subtarget.hasP8Altivec()) {
871       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
872       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
873     }
874 
875     if (Subtarget.hasP9Vector()) {
876       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
877       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
878 
879       // 128 bit shifts can be accomplished via 3 instructions for SHL and
880       // SRL, but not for SRA because of the instructions available:
881       // VS{RL} and VS{RL}O.
882       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
883       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
884       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
885 
886       if (EnableQuadPrecision) {
887         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
888         setOperationAction(ISD::FADD, MVT::f128, Legal);
889         setOperationAction(ISD::FSUB, MVT::f128, Legal);
890         setOperationAction(ISD::FDIV, MVT::f128, Legal);
891         setOperationAction(ISD::FMUL, MVT::f128, Legal);
892         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
893         // No extending loads to f128 on PPC.
894         for (MVT FPT : MVT::fp_valuetypes())
895           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
896         setOperationAction(ISD::FMA, MVT::f128, Legal);
897         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
898         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
899         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
900         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
901         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
902         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
903 
904         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
905         setOperationAction(ISD::FRINT, MVT::f128, Legal);
906         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
907         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
908         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
909         setOperationAction(ISD::FROUND, MVT::f128, Legal);
910 
911         setOperationAction(ISD::SELECT, MVT::f128, Expand);
912         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
913         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
914         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
915         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
916         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
917         // No implementation for these ops for PowerPC.
918         setOperationAction(ISD::FSIN , MVT::f128, Expand);
919         setOperationAction(ISD::FCOS , MVT::f128, Expand);
920         setOperationAction(ISD::FPOW, MVT::f128, Expand);
921         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
922         setOperationAction(ISD::FREM, MVT::f128, Expand);
923       }
924       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
925 
926     }
927 
928     if (Subtarget.hasP9Altivec()) {
929       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
930       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
931 
932       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
933       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
934       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
935       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
936       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
937       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
938       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
939     }
940   }
941 
942   if (Subtarget.hasQPX()) {
943     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
944     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
945     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
946     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
947 
948     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
949     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
950 
951     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
952     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
953 
954     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
955     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
956 
957     if (!Subtarget.useCRBits())
958       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
959     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
960 
961     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
962     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
963     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
964     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
965     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
966     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
967     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
968 
969     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
970     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
971 
972     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
973     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
974 
975     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
976     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
977     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
978     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
979     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
980     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
981     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
982     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
983     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
984     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
985 
986     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
987     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
988 
989     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
990     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
991 
992     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
993 
994     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
995     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
996     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
997     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
998 
999     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1000     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1001 
1002     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1003     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1004 
1005     if (!Subtarget.useCRBits())
1006       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1007     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1008 
1009     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1010     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1011     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1012     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1013     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1014     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1015     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1016 
1017     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1018     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1019 
1020     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1021     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1022     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1023     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1024     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1025     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1026     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1027     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1028     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1029     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1030 
1031     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1032     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1033 
1034     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1035     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1036 
1037     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1038 
1039     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1040     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1041     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1042 
1043     if (!Subtarget.useCRBits())
1044       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1045     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1046 
1047     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1048     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1049 
1050     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1051     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1052     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1053     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1054     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1055     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1056     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1057 
1058     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1059     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1060 
1061     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1062 
1063     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1064     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1065     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1066     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1067 
1068     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1069     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1070     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1071     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1072 
1073     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1074     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1075 
1076     // These need to set FE_INEXACT, and so cannot be vectorized here.
1077     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1078     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1079 
1080     if (TM.Options.UnsafeFPMath) {
1081       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1082       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1083 
1084       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1085       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1086     } else {
1087       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1088       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1089 
1090       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1091       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1092     }
1093   }
1094 
1095   if (Subtarget.has64BitSupport())
1096     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1097 
1098   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1099 
1100   if (!isPPC64) {
1101     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1102     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1103   }
1104 
1105   setBooleanContents(ZeroOrOneBooleanContent);
1106 
1107   if (Subtarget.hasAltivec()) {
1108     // Altivec instructions set fields to all zeros or all ones.
1109     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1110   }
1111 
1112   if (!isPPC64) {
1113     // These libcalls are not available in 32-bit.
1114     setLibcallName(RTLIB::SHL_I128, nullptr);
1115     setLibcallName(RTLIB::SRL_I128, nullptr);
1116     setLibcallName(RTLIB::SRA_I128, nullptr);
1117   }
1118 
1119   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1120 
1121   // We have target-specific dag combine patterns for the following nodes:
1122   setTargetDAGCombine(ISD::ADD);
1123   setTargetDAGCombine(ISD::SHL);
1124   setTargetDAGCombine(ISD::SRA);
1125   setTargetDAGCombine(ISD::SRL);
1126   setTargetDAGCombine(ISD::MUL);
1127   setTargetDAGCombine(ISD::SINT_TO_FP);
1128   setTargetDAGCombine(ISD::BUILD_VECTOR);
1129   if (Subtarget.hasFPCVT())
1130     setTargetDAGCombine(ISD::UINT_TO_FP);
1131   setTargetDAGCombine(ISD::LOAD);
1132   setTargetDAGCombine(ISD::STORE);
1133   setTargetDAGCombine(ISD::BR_CC);
1134   if (Subtarget.useCRBits())
1135     setTargetDAGCombine(ISD::BRCOND);
1136   setTargetDAGCombine(ISD::BSWAP);
1137   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1138   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1139   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1140 
1141   setTargetDAGCombine(ISD::SIGN_EXTEND);
1142   setTargetDAGCombine(ISD::ZERO_EXTEND);
1143   setTargetDAGCombine(ISD::ANY_EXTEND);
1144 
1145   setTargetDAGCombine(ISD::TRUNCATE);
1146   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1147 
1148 
1149   if (Subtarget.useCRBits()) {
1150     setTargetDAGCombine(ISD::TRUNCATE);
1151     setTargetDAGCombine(ISD::SETCC);
1152     setTargetDAGCombine(ISD::SELECT_CC);
1153   }
1154 
1155   // Use reciprocal estimates.
1156   if (TM.Options.UnsafeFPMath) {
1157     setTargetDAGCombine(ISD::FDIV);
1158     setTargetDAGCombine(ISD::FSQRT);
1159   }
1160 
1161   if (Subtarget.hasP9Altivec()) {
1162     setTargetDAGCombine(ISD::ABS);
1163     setTargetDAGCombine(ISD::VSELECT);
1164   }
1165 
1166   // Darwin long double math library functions have $LDBL128 appended.
1167   if (Subtarget.isDarwin()) {
1168     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1169     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1170     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1171     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1172     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1173     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1174     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1175     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1176     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1177     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1178   }
1179 
1180   if (EnableQuadPrecision) {
1181     setLibcallName(RTLIB::LOG_F128, "logf128");
1182     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1183     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1184     setLibcallName(RTLIB::EXP_F128, "expf128");
1185     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1186     setLibcallName(RTLIB::SIN_F128, "sinf128");
1187     setLibcallName(RTLIB::COS_F128, "cosf128");
1188     setLibcallName(RTLIB::POW_F128, "powf128");
1189     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1190     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1191     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1192     setLibcallName(RTLIB::REM_F128, "fmodf128");
1193   }
1194 
1195   // With 32 condition bits, we don't need to sink (and duplicate) compares
1196   // aggressively in CodeGenPrep.
1197   if (Subtarget.useCRBits()) {
1198     setHasMultipleConditionRegisters();
1199     setJumpIsExpensive();
1200   }
1201 
1202   setMinFunctionAlignment(Align(4));
1203   if (Subtarget.isDarwin())
1204     setPrefFunctionAlignment(Align(16));
1205 
1206   switch (Subtarget.getCPUDirective()) {
1207   default: break;
1208   case PPC::DIR_970:
1209   case PPC::DIR_A2:
1210   case PPC::DIR_E500:
1211   case PPC::DIR_E500mc:
1212   case PPC::DIR_E5500:
1213   case PPC::DIR_PWR4:
1214   case PPC::DIR_PWR5:
1215   case PPC::DIR_PWR5X:
1216   case PPC::DIR_PWR6:
1217   case PPC::DIR_PWR6X:
1218   case PPC::DIR_PWR7:
1219   case PPC::DIR_PWR8:
1220   case PPC::DIR_PWR9:
1221   case PPC::DIR_PWR_FUTURE:
1222     setPrefLoopAlignment(Align(16));
1223     setPrefFunctionAlignment(Align(16));
1224     break;
1225   }
1226 
1227   if (Subtarget.enableMachineScheduler())
1228     setSchedulingPreference(Sched::Source);
1229   else
1230     setSchedulingPreference(Sched::Hybrid);
1231 
1232   computeRegisterProperties(STI.getRegisterInfo());
1233 
1234   // The Freescale cores do better with aggressive inlining of memcpy and
1235   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1236   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1237       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1238     MaxStoresPerMemset = 32;
1239     MaxStoresPerMemsetOptSize = 16;
1240     MaxStoresPerMemcpy = 32;
1241     MaxStoresPerMemcpyOptSize = 8;
1242     MaxStoresPerMemmove = 32;
1243     MaxStoresPerMemmoveOptSize = 8;
1244   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1245     // The A2 also benefits from (very) aggressive inlining of memcpy and
1246     // friends. The overhead of a the function call, even when warm, can be
1247     // over one hundred cycles.
1248     MaxStoresPerMemset = 128;
1249     MaxStoresPerMemcpy = 128;
1250     MaxStoresPerMemmove = 128;
1251     MaxLoadsPerMemcmp = 128;
1252   } else {
1253     MaxLoadsPerMemcmp = 8;
1254     MaxLoadsPerMemcmpOptSize = 4;
1255   }
1256 }
1257 
1258 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1259 /// the desired ByVal argument alignment.
1260 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1261                              unsigned MaxMaxAlign) {
1262   if (MaxAlign == MaxMaxAlign)
1263     return;
1264   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1265     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1266       MaxAlign = 32;
1267     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1268       MaxAlign = 16;
1269   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1270     unsigned EltAlign = 0;
1271     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1272     if (EltAlign > MaxAlign)
1273       MaxAlign = EltAlign;
1274   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1275     for (auto *EltTy : STy->elements()) {
1276       unsigned EltAlign = 0;
1277       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1278       if (EltAlign > MaxAlign)
1279         MaxAlign = EltAlign;
1280       if (MaxAlign == MaxMaxAlign)
1281         break;
1282     }
1283   }
1284 }
1285 
1286 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1287 /// function arguments in the caller parameter area.
1288 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1289                                                   const DataLayout &DL) const {
1290   // Darwin passes everything on 4 byte boundary.
1291   if (Subtarget.isDarwin())
1292     return 4;
1293 
1294   // 16byte and wider vectors are passed on 16byte boundary.
1295   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1296   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1297   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1298     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1299   return Align;
1300 }
1301 
1302 bool PPCTargetLowering::useSoftFloat() const {
1303   return Subtarget.useSoftFloat();
1304 }
1305 
1306 bool PPCTargetLowering::hasSPE() const {
1307   return Subtarget.hasSPE();
1308 }
1309 
1310 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1311   return VT.isScalarInteger();
1312 }
1313 
1314 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1315   switch ((PPCISD::NodeType)Opcode) {
1316   case PPCISD::FIRST_NUMBER:    break;
1317   case PPCISD::FSEL:            return "PPCISD::FSEL";
1318   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1319   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1320   case PPCISD::FCFID:           return "PPCISD::FCFID";
1321   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1322   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1323   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1324   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1325   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1326   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1327   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1328   case PPCISD::FP_TO_UINT_IN_VSR:
1329                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1330   case PPCISD::FP_TO_SINT_IN_VSR:
1331                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1332   case PPCISD::FRE:             return "PPCISD::FRE";
1333   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1334   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1335   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1336   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1337   case PPCISD::VPERM:           return "PPCISD::VPERM";
1338   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1339   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1340   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1341   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1342   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1343   case PPCISD::CMPB:            return "PPCISD::CMPB";
1344   case PPCISD::Hi:              return "PPCISD::Hi";
1345   case PPCISD::Lo:              return "PPCISD::Lo";
1346   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1347   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1348   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1349   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1350   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1351   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1352   case PPCISD::SRL:             return "PPCISD::SRL";
1353   case PPCISD::SRA:             return "PPCISD::SRA";
1354   case PPCISD::SHL:             return "PPCISD::SHL";
1355   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1356   case PPCISD::CALL:            return "PPCISD::CALL";
1357   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1358   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1359   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1360   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1361   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1362   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1363   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1364   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1365   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1366   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1367   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1368   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1369   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1370   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1371   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1372   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1373   case PPCISD::VCMP:            return "PPCISD::VCMP";
1374   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1375   case PPCISD::LBRX:            return "PPCISD::LBRX";
1376   case PPCISD::STBRX:           return "PPCISD::STBRX";
1377   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1378   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1379   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1380   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1381   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1382   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1383   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1384   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1385   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1386   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1387   case PPCISD::ST_VSR_SCAL_INT:
1388                                 return "PPCISD::ST_VSR_SCAL_INT";
1389   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1390   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1391   case PPCISD::BDZ:             return "PPCISD::BDZ";
1392   case PPCISD::MFFS:            return "PPCISD::MFFS";
1393   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1394   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1395   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1396   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1397   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1398   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1399   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1400   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1401   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1402   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1403   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1404   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1405   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1406   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1407   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1408   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1409   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1410   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1411   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1412   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1413   case PPCISD::SC:              return "PPCISD::SC";
1414   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1415   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1416   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1417   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1418   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1419   case PPCISD::VABSD:           return "PPCISD::VABSD";
1420   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1421   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1422   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1423   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1424   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1425   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1426   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1427   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1428   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1429   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1430   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1431   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1432   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1433   }
1434   return nullptr;
1435 }
1436 
1437 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1438                                           EVT VT) const {
1439   if (!VT.isVector())
1440     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1441 
1442   if (Subtarget.hasQPX())
1443     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1444 
1445   return VT.changeVectorElementTypeToInteger();
1446 }
1447 
1448 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1449   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1450   return true;
1451 }
1452 
1453 //===----------------------------------------------------------------------===//
1454 // Node matching predicates, for use by the tblgen matching code.
1455 //===----------------------------------------------------------------------===//
1456 
1457 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1458 static bool isFloatingPointZero(SDValue Op) {
1459   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1460     return CFP->getValueAPF().isZero();
1461   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1462     // Maybe this has already been legalized into the constant pool?
1463     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1464       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1465         return CFP->getValueAPF().isZero();
1466   }
1467   return false;
1468 }
1469 
1470 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1471 /// true if Op is undef or if it matches the specified value.
1472 static bool isConstantOrUndef(int Op, int Val) {
1473   return Op < 0 || Op == Val;
1474 }
1475 
1476 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1477 /// VPKUHUM instruction.
1478 /// The ShuffleKind distinguishes between big-endian operations with
1479 /// two different inputs (0), either-endian operations with two identical
1480 /// inputs (1), and little-endian operations with two different inputs (2).
1481 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1482 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1483                                SelectionDAG &DAG) {
1484   bool IsLE = DAG.getDataLayout().isLittleEndian();
1485   if (ShuffleKind == 0) {
1486     if (IsLE)
1487       return false;
1488     for (unsigned i = 0; i != 16; ++i)
1489       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1490         return false;
1491   } else if (ShuffleKind == 2) {
1492     if (!IsLE)
1493       return false;
1494     for (unsigned i = 0; i != 16; ++i)
1495       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1496         return false;
1497   } else if (ShuffleKind == 1) {
1498     unsigned j = IsLE ? 0 : 1;
1499     for (unsigned i = 0; i != 8; ++i)
1500       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1501           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1502         return false;
1503   }
1504   return true;
1505 }
1506 
1507 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1508 /// VPKUWUM instruction.
1509 /// The ShuffleKind distinguishes between big-endian operations with
1510 /// two different inputs (0), either-endian operations with two identical
1511 /// inputs (1), and little-endian operations with two different inputs (2).
1512 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1513 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1514                                SelectionDAG &DAG) {
1515   bool IsLE = DAG.getDataLayout().isLittleEndian();
1516   if (ShuffleKind == 0) {
1517     if (IsLE)
1518       return false;
1519     for (unsigned i = 0; i != 16; i += 2)
1520       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1521           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1522         return false;
1523   } else if (ShuffleKind == 2) {
1524     if (!IsLE)
1525       return false;
1526     for (unsigned i = 0; i != 16; i += 2)
1527       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1528           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1529         return false;
1530   } else if (ShuffleKind == 1) {
1531     unsigned j = IsLE ? 0 : 2;
1532     for (unsigned i = 0; i != 8; i += 2)
1533       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1534           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1535           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1536           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1537         return false;
1538   }
1539   return true;
1540 }
1541 
1542 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1543 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1544 /// current subtarget.
1545 ///
1546 /// The ShuffleKind distinguishes between big-endian operations with
1547 /// two different inputs (0), either-endian operations with two identical
1548 /// inputs (1), and little-endian operations with two different inputs (2).
1549 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1550 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1551                                SelectionDAG &DAG) {
1552   const PPCSubtarget& Subtarget =
1553       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1554   if (!Subtarget.hasP8Vector())
1555     return false;
1556 
1557   bool IsLE = DAG.getDataLayout().isLittleEndian();
1558   if (ShuffleKind == 0) {
1559     if (IsLE)
1560       return false;
1561     for (unsigned i = 0; i != 16; i += 4)
1562       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1563           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1564           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1565           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1566         return false;
1567   } else if (ShuffleKind == 2) {
1568     if (!IsLE)
1569       return false;
1570     for (unsigned i = 0; i != 16; i += 4)
1571       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1572           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1573           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1574           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1575         return false;
1576   } else if (ShuffleKind == 1) {
1577     unsigned j = IsLE ? 0 : 4;
1578     for (unsigned i = 0; i != 8; i += 4)
1579       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1580           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1581           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1582           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1583           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1584           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1585           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1586           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1587         return false;
1588   }
1589   return true;
1590 }
1591 
1592 /// isVMerge - Common function, used to match vmrg* shuffles.
1593 ///
1594 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1595                      unsigned LHSStart, unsigned RHSStart) {
1596   if (N->getValueType(0) != MVT::v16i8)
1597     return false;
1598   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1599          "Unsupported merge size!");
1600 
1601   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1602     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1603       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1604                              LHSStart+j+i*UnitSize) ||
1605           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1606                              RHSStart+j+i*UnitSize))
1607         return false;
1608     }
1609   return true;
1610 }
1611 
1612 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1613 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1614 /// The ShuffleKind distinguishes between big-endian merges with two
1615 /// different inputs (0), either-endian merges with two identical inputs (1),
1616 /// and little-endian merges with two different inputs (2).  For the latter,
1617 /// the input operands are swapped (see PPCInstrAltivec.td).
1618 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1619                              unsigned ShuffleKind, SelectionDAG &DAG) {
1620   if (DAG.getDataLayout().isLittleEndian()) {
1621     if (ShuffleKind == 1) // unary
1622       return isVMerge(N, UnitSize, 0, 0);
1623     else if (ShuffleKind == 2) // swapped
1624       return isVMerge(N, UnitSize, 0, 16);
1625     else
1626       return false;
1627   } else {
1628     if (ShuffleKind == 1) // unary
1629       return isVMerge(N, UnitSize, 8, 8);
1630     else if (ShuffleKind == 0) // normal
1631       return isVMerge(N, UnitSize, 8, 24);
1632     else
1633       return false;
1634   }
1635 }
1636 
1637 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1638 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1639 /// The ShuffleKind distinguishes between big-endian merges with two
1640 /// different inputs (0), either-endian merges with two identical inputs (1),
1641 /// and little-endian merges with two different inputs (2).  For the latter,
1642 /// the input operands are swapped (see PPCInstrAltivec.td).
1643 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1644                              unsigned ShuffleKind, SelectionDAG &DAG) {
1645   if (DAG.getDataLayout().isLittleEndian()) {
1646     if (ShuffleKind == 1) // unary
1647       return isVMerge(N, UnitSize, 8, 8);
1648     else if (ShuffleKind == 2) // swapped
1649       return isVMerge(N, UnitSize, 8, 24);
1650     else
1651       return false;
1652   } else {
1653     if (ShuffleKind == 1) // unary
1654       return isVMerge(N, UnitSize, 0, 0);
1655     else if (ShuffleKind == 0) // normal
1656       return isVMerge(N, UnitSize, 0, 16);
1657     else
1658       return false;
1659   }
1660 }
1661 
1662 /**
1663  * Common function used to match vmrgew and vmrgow shuffles
1664  *
1665  * The indexOffset determines whether to look for even or odd words in
1666  * the shuffle mask. This is based on the of the endianness of the target
1667  * machine.
1668  *   - Little Endian:
1669  *     - Use offset of 0 to check for odd elements
1670  *     - Use offset of 4 to check for even elements
1671  *   - Big Endian:
1672  *     - Use offset of 0 to check for even elements
1673  *     - Use offset of 4 to check for odd elements
1674  * A detailed description of the vector element ordering for little endian and
1675  * big endian can be found at
1676  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1677  * Targeting your applications - what little endian and big endian IBM XL C/C++
1678  * compiler differences mean to you
1679  *
1680  * The mask to the shuffle vector instruction specifies the indices of the
1681  * elements from the two input vectors to place in the result. The elements are
1682  * numbered in array-access order, starting with the first vector. These vectors
1683  * are always of type v16i8, thus each vector will contain 16 elements of size
1684  * 8. More info on the shuffle vector can be found in the
1685  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1686  * Language Reference.
1687  *
1688  * The RHSStartValue indicates whether the same input vectors are used (unary)
1689  * or two different input vectors are used, based on the following:
1690  *   - If the instruction uses the same vector for both inputs, the range of the
1691  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1692  *     be 0.
1693  *   - If the instruction has two different vectors then the range of the
1694  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1695  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1696  *     to 31 specify elements in the second vector).
1697  *
1698  * \param[in] N The shuffle vector SD Node to analyze
1699  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1700  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1701  * vector to the shuffle_vector instruction
1702  * \return true iff this shuffle vector represents an even or odd word merge
1703  */
1704 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1705                      unsigned RHSStartValue) {
1706   if (N->getValueType(0) != MVT::v16i8)
1707     return false;
1708 
1709   for (unsigned i = 0; i < 2; ++i)
1710     for (unsigned j = 0; j < 4; ++j)
1711       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1712                              i*RHSStartValue+j+IndexOffset) ||
1713           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1714                              i*RHSStartValue+j+IndexOffset+8))
1715         return false;
1716   return true;
1717 }
1718 
1719 /**
1720  * Determine if the specified shuffle mask is suitable for the vmrgew or
1721  * vmrgow instructions.
1722  *
1723  * \param[in] N The shuffle vector SD Node to analyze
1724  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1725  * \param[in] ShuffleKind Identify the type of merge:
1726  *   - 0 = big-endian merge with two different inputs;
1727  *   - 1 = either-endian merge with two identical inputs;
1728  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1729  *     little-endian merges).
1730  * \param[in] DAG The current SelectionDAG
1731  * \return true iff this shuffle mask
1732  */
1733 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1734                               unsigned ShuffleKind, SelectionDAG &DAG) {
1735   if (DAG.getDataLayout().isLittleEndian()) {
1736     unsigned indexOffset = CheckEven ? 4 : 0;
1737     if (ShuffleKind == 1) // Unary
1738       return isVMerge(N, indexOffset, 0);
1739     else if (ShuffleKind == 2) // swapped
1740       return isVMerge(N, indexOffset, 16);
1741     else
1742       return false;
1743   }
1744   else {
1745     unsigned indexOffset = CheckEven ? 0 : 4;
1746     if (ShuffleKind == 1) // Unary
1747       return isVMerge(N, indexOffset, 0);
1748     else if (ShuffleKind == 0) // Normal
1749       return isVMerge(N, indexOffset, 16);
1750     else
1751       return false;
1752   }
1753   return false;
1754 }
1755 
1756 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1757 /// amount, otherwise return -1.
1758 /// The ShuffleKind distinguishes between big-endian operations with two
1759 /// different inputs (0), either-endian operations with two identical inputs
1760 /// (1), and little-endian operations with two different inputs (2).  For the
1761 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1762 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1763                              SelectionDAG &DAG) {
1764   if (N->getValueType(0) != MVT::v16i8)
1765     return -1;
1766 
1767   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1768 
1769   // Find the first non-undef value in the shuffle mask.
1770   unsigned i;
1771   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1772     /*search*/;
1773 
1774   if (i == 16) return -1;  // all undef.
1775 
1776   // Otherwise, check to see if the rest of the elements are consecutively
1777   // numbered from this value.
1778   unsigned ShiftAmt = SVOp->getMaskElt(i);
1779   if (ShiftAmt < i) return -1;
1780 
1781   ShiftAmt -= i;
1782   bool isLE = DAG.getDataLayout().isLittleEndian();
1783 
1784   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1785     // Check the rest of the elements to see if they are consecutive.
1786     for (++i; i != 16; ++i)
1787       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1788         return -1;
1789   } else if (ShuffleKind == 1) {
1790     // Check the rest of the elements to see if they are consecutive.
1791     for (++i; i != 16; ++i)
1792       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1793         return -1;
1794   } else
1795     return -1;
1796 
1797   if (isLE)
1798     ShiftAmt = 16 - ShiftAmt;
1799 
1800   return ShiftAmt;
1801 }
1802 
1803 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1804 /// specifies a splat of a single element that is suitable for input to
1805 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1806 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1807   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1808          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1809 
1810   // The consecutive indices need to specify an element, not part of two
1811   // different elements.  So abandon ship early if this isn't the case.
1812   if (N->getMaskElt(0) % EltSize != 0)
1813     return false;
1814 
1815   // This is a splat operation if each element of the permute is the same, and
1816   // if the value doesn't reference the second vector.
1817   unsigned ElementBase = N->getMaskElt(0);
1818 
1819   // FIXME: Handle UNDEF elements too!
1820   if (ElementBase >= 16)
1821     return false;
1822 
1823   // Check that the indices are consecutive, in the case of a multi-byte element
1824   // splatted with a v16i8 mask.
1825   for (unsigned i = 1; i != EltSize; ++i)
1826     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1827       return false;
1828 
1829   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1830     if (N->getMaskElt(i) < 0) continue;
1831     for (unsigned j = 0; j != EltSize; ++j)
1832       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1833         return false;
1834   }
1835   return true;
1836 }
1837 
1838 /// Check that the mask is shuffling N byte elements. Within each N byte
1839 /// element of the mask, the indices could be either in increasing or
1840 /// decreasing order as long as they are consecutive.
1841 /// \param[in] N the shuffle vector SD Node to analyze
1842 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1843 /// Word/DoubleWord/QuadWord).
1844 /// \param[in] StepLen the delta indices number among the N byte element, if
1845 /// the mask is in increasing/decreasing order then it is 1/-1.
1846 /// \return true iff the mask is shuffling N byte elements.
1847 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1848                                    int StepLen) {
1849   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1850          "Unexpected element width.");
1851   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1852 
1853   unsigned NumOfElem = 16 / Width;
1854   unsigned MaskVal[16]; //  Width is never greater than 16
1855   for (unsigned i = 0; i < NumOfElem; ++i) {
1856     MaskVal[0] = N->getMaskElt(i * Width);
1857     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1858       return false;
1859     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1860       return false;
1861     }
1862 
1863     for (unsigned int j = 1; j < Width; ++j) {
1864       MaskVal[j] = N->getMaskElt(i * Width + j);
1865       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1866         return false;
1867       }
1868     }
1869   }
1870 
1871   return true;
1872 }
1873 
1874 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1875                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1876   if (!isNByteElemShuffleMask(N, 4, 1))
1877     return false;
1878 
1879   // Now we look at mask elements 0,4,8,12
1880   unsigned M0 = N->getMaskElt(0) / 4;
1881   unsigned M1 = N->getMaskElt(4) / 4;
1882   unsigned M2 = N->getMaskElt(8) / 4;
1883   unsigned M3 = N->getMaskElt(12) / 4;
1884   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1885   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1886 
1887   // Below, let H and L be arbitrary elements of the shuffle mask
1888   // where H is in the range [4,7] and L is in the range [0,3].
1889   // H, 1, 2, 3 or L, 5, 6, 7
1890   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1891       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1892     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1893     InsertAtByte = IsLE ? 12 : 0;
1894     Swap = M0 < 4;
1895     return true;
1896   }
1897   // 0, H, 2, 3 or 4, L, 6, 7
1898   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1899       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1900     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1901     InsertAtByte = IsLE ? 8 : 4;
1902     Swap = M1 < 4;
1903     return true;
1904   }
1905   // 0, 1, H, 3 or 4, 5, L, 7
1906   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1907       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1908     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1909     InsertAtByte = IsLE ? 4 : 8;
1910     Swap = M2 < 4;
1911     return true;
1912   }
1913   // 0, 1, 2, H or 4, 5, 6, L
1914   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1915       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1916     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1917     InsertAtByte = IsLE ? 0 : 12;
1918     Swap = M3 < 4;
1919     return true;
1920   }
1921 
1922   // If both vector operands for the shuffle are the same vector, the mask will
1923   // contain only elements from the first one and the second one will be undef.
1924   if (N->getOperand(1).isUndef()) {
1925     ShiftElts = 0;
1926     Swap = true;
1927     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1928     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1929       InsertAtByte = IsLE ? 12 : 0;
1930       return true;
1931     }
1932     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1933       InsertAtByte = IsLE ? 8 : 4;
1934       return true;
1935     }
1936     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1937       InsertAtByte = IsLE ? 4 : 8;
1938       return true;
1939     }
1940     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1941       InsertAtByte = IsLE ? 0 : 12;
1942       return true;
1943     }
1944   }
1945 
1946   return false;
1947 }
1948 
1949 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1950                                bool &Swap, bool IsLE) {
1951   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1952   // Ensure each byte index of the word is consecutive.
1953   if (!isNByteElemShuffleMask(N, 4, 1))
1954     return false;
1955 
1956   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1957   unsigned M0 = N->getMaskElt(0) / 4;
1958   unsigned M1 = N->getMaskElt(4) / 4;
1959   unsigned M2 = N->getMaskElt(8) / 4;
1960   unsigned M3 = N->getMaskElt(12) / 4;
1961 
1962   // If both vector operands for the shuffle are the same vector, the mask will
1963   // contain only elements from the first one and the second one will be undef.
1964   if (N->getOperand(1).isUndef()) {
1965     assert(M0 < 4 && "Indexing into an undef vector?");
1966     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1967       return false;
1968 
1969     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1970     Swap = false;
1971     return true;
1972   }
1973 
1974   // Ensure each word index of the ShuffleVector Mask is consecutive.
1975   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1976     return false;
1977 
1978   if (IsLE) {
1979     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1980       // Input vectors don't need to be swapped if the leading element
1981       // of the result is one of the 3 left elements of the second vector
1982       // (or if there is no shift to be done at all).
1983       Swap = false;
1984       ShiftElts = (8 - M0) % 8;
1985     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1986       // Input vectors need to be swapped if the leading element
1987       // of the result is one of the 3 left elements of the first vector
1988       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1989       Swap = true;
1990       ShiftElts = (4 - M0) % 4;
1991     }
1992 
1993     return true;
1994   } else {                                          // BE
1995     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1996       // Input vectors don't need to be swapped if the leading element
1997       // of the result is one of the 4 elements of the first vector.
1998       Swap = false;
1999       ShiftElts = M0;
2000     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2001       // Input vectors need to be swapped if the leading element
2002       // of the result is one of the 4 elements of the right vector.
2003       Swap = true;
2004       ShiftElts = M0 - 4;
2005     }
2006 
2007     return true;
2008   }
2009 }
2010 
2011 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2012   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2013 
2014   if (!isNByteElemShuffleMask(N, Width, -1))
2015     return false;
2016 
2017   for (int i = 0; i < 16; i += Width)
2018     if (N->getMaskElt(i) != i + Width - 1)
2019       return false;
2020 
2021   return true;
2022 }
2023 
2024 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2025   return isXXBRShuffleMaskHelper(N, 2);
2026 }
2027 
2028 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2029   return isXXBRShuffleMaskHelper(N, 4);
2030 }
2031 
2032 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2033   return isXXBRShuffleMaskHelper(N, 8);
2034 }
2035 
2036 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2037   return isXXBRShuffleMaskHelper(N, 16);
2038 }
2039 
2040 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2041 /// if the inputs to the instruction should be swapped and set \p DM to the
2042 /// value for the immediate.
2043 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2044 /// AND element 0 of the result comes from the first input (LE) or second input
2045 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2046 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2047 /// mask.
2048 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2049                                bool &Swap, bool IsLE) {
2050   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2051 
2052   // Ensure each byte index of the double word is consecutive.
2053   if (!isNByteElemShuffleMask(N, 8, 1))
2054     return false;
2055 
2056   unsigned M0 = N->getMaskElt(0) / 8;
2057   unsigned M1 = N->getMaskElt(8) / 8;
2058   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2059 
2060   // If both vector operands for the shuffle are the same vector, the mask will
2061   // contain only elements from the first one and the second one will be undef.
2062   if (N->getOperand(1).isUndef()) {
2063     if ((M0 | M1) < 2) {
2064       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2065       Swap = false;
2066       return true;
2067     } else
2068       return false;
2069   }
2070 
2071   if (IsLE) {
2072     if (M0 > 1 && M1 < 2) {
2073       Swap = false;
2074     } else if (M0 < 2 && M1 > 1) {
2075       M0 = (M0 + 2) % 4;
2076       M1 = (M1 + 2) % 4;
2077       Swap = true;
2078     } else
2079       return false;
2080 
2081     // Note: if control flow comes here that means Swap is already set above
2082     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2083     return true;
2084   } else { // BE
2085     if (M0 < 2 && M1 > 1) {
2086       Swap = false;
2087     } else if (M0 > 1 && M1 < 2) {
2088       M0 = (M0 + 2) % 4;
2089       M1 = (M1 + 2) % 4;
2090       Swap = true;
2091     } else
2092       return false;
2093 
2094     // Note: if control flow comes here that means Swap is already set above
2095     DM = (M0 << 1) + (M1 & 1);
2096     return true;
2097   }
2098 }
2099 
2100 
2101 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2102 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2103 /// elements are counted from the left of the vector register).
2104 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2105                                          SelectionDAG &DAG) {
2106   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2107   assert(isSplatShuffleMask(SVOp, EltSize));
2108   if (DAG.getDataLayout().isLittleEndian())
2109     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2110   else
2111     return SVOp->getMaskElt(0) / EltSize;
2112 }
2113 
2114 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2115 /// by using a vspltis[bhw] instruction of the specified element size, return
2116 /// the constant being splatted.  The ByteSize field indicates the number of
2117 /// bytes of each element [124] -> [bhw].
2118 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2119   SDValue OpVal(nullptr, 0);
2120 
2121   // If ByteSize of the splat is bigger than the element size of the
2122   // build_vector, then we have a case where we are checking for a splat where
2123   // multiple elements of the buildvector are folded together into a single
2124   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2125   unsigned EltSize = 16/N->getNumOperands();
2126   if (EltSize < ByteSize) {
2127     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2128     SDValue UniquedVals[4];
2129     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2130 
2131     // See if all of the elements in the buildvector agree across.
2132     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2133       if (N->getOperand(i).isUndef()) continue;
2134       // If the element isn't a constant, bail fully out.
2135       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2136 
2137       if (!UniquedVals[i&(Multiple-1)].getNode())
2138         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2139       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2140         return SDValue();  // no match.
2141     }
2142 
2143     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2144     // either constant or undef values that are identical for each chunk.  See
2145     // if these chunks can form into a larger vspltis*.
2146 
2147     // Check to see if all of the leading entries are either 0 or -1.  If
2148     // neither, then this won't fit into the immediate field.
2149     bool LeadingZero = true;
2150     bool LeadingOnes = true;
2151     for (unsigned i = 0; i != Multiple-1; ++i) {
2152       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2153 
2154       LeadingZero &= isNullConstant(UniquedVals[i]);
2155       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2156     }
2157     // Finally, check the least significant entry.
2158     if (LeadingZero) {
2159       if (!UniquedVals[Multiple-1].getNode())
2160         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2161       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2162       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2163         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2164     }
2165     if (LeadingOnes) {
2166       if (!UniquedVals[Multiple-1].getNode())
2167         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2168       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2169       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2170         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2171     }
2172 
2173     return SDValue();
2174   }
2175 
2176   // Check to see if this buildvec has a single non-undef value in its elements.
2177   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2178     if (N->getOperand(i).isUndef()) continue;
2179     if (!OpVal.getNode())
2180       OpVal = N->getOperand(i);
2181     else if (OpVal != N->getOperand(i))
2182       return SDValue();
2183   }
2184 
2185   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2186 
2187   unsigned ValSizeInBytes = EltSize;
2188   uint64_t Value = 0;
2189   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2190     Value = CN->getZExtValue();
2191   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2192     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2193     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2194   }
2195 
2196   // If the splat value is larger than the element value, then we can never do
2197   // this splat.  The only case that we could fit the replicated bits into our
2198   // immediate field for would be zero, and we prefer to use vxor for it.
2199   if (ValSizeInBytes < ByteSize) return SDValue();
2200 
2201   // If the element value is larger than the splat value, check if it consists
2202   // of a repeated bit pattern of size ByteSize.
2203   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2204     return SDValue();
2205 
2206   // Properly sign extend the value.
2207   int MaskVal = SignExtend32(Value, ByteSize * 8);
2208 
2209   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2210   if (MaskVal == 0) return SDValue();
2211 
2212   // Finally, if this value fits in a 5 bit sext field, return it
2213   if (SignExtend32<5>(MaskVal) == MaskVal)
2214     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2215   return SDValue();
2216 }
2217 
2218 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2219 /// amount, otherwise return -1.
2220 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2221   EVT VT = N->getValueType(0);
2222   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2223     return -1;
2224 
2225   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2226 
2227   // Find the first non-undef value in the shuffle mask.
2228   unsigned i;
2229   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2230     /*search*/;
2231 
2232   if (i == 4) return -1;  // all undef.
2233 
2234   // Otherwise, check to see if the rest of the elements are consecutively
2235   // numbered from this value.
2236   unsigned ShiftAmt = SVOp->getMaskElt(i);
2237   if (ShiftAmt < i) return -1;
2238   ShiftAmt -= i;
2239 
2240   // Check the rest of the elements to see if they are consecutive.
2241   for (++i; i != 4; ++i)
2242     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2243       return -1;
2244 
2245   return ShiftAmt;
2246 }
2247 
2248 //===----------------------------------------------------------------------===//
2249 //  Addressing Mode Selection
2250 //===----------------------------------------------------------------------===//
2251 
2252 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2253 /// or 64-bit immediate, and if the value can be accurately represented as a
2254 /// sign extension from a 16-bit value.  If so, this returns true and the
2255 /// immediate.
2256 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2257   if (!isa<ConstantSDNode>(N))
2258     return false;
2259 
2260   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2261   if (N->getValueType(0) == MVT::i32)
2262     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2263   else
2264     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2265 }
2266 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2267   return isIntS16Immediate(Op.getNode(), Imm);
2268 }
2269 
2270 
2271 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2272 /// be represented as an indexed [r+r] operation.
2273 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2274                                                SDValue &Index,
2275                                                SelectionDAG &DAG) const {
2276   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2277       UI != E; ++UI) {
2278     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2279       if (Memop->getMemoryVT() == MVT::f64) {
2280           Base = N.getOperand(0);
2281           Index = N.getOperand(1);
2282           return true;
2283       }
2284     }
2285   }
2286   return false;
2287 }
2288 
2289 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2290 /// can be represented as an indexed [r+r] operation.  Returns false if it
2291 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2292 /// non-zero and N can be represented by a base register plus a signed 16-bit
2293 /// displacement, make a more precise judgement by checking (displacement % \p
2294 /// EncodingAlignment).
2295 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2296                                             SDValue &Index, SelectionDAG &DAG,
2297                                             unsigned EncodingAlignment) const {
2298   int16_t imm = 0;
2299   if (N.getOpcode() == ISD::ADD) {
2300     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2301     // SPE load/store can only handle 8-bit offsets.
2302     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2303         return true;
2304     if (isIntS16Immediate(N.getOperand(1), imm) &&
2305         (!EncodingAlignment || !(imm % EncodingAlignment)))
2306       return false; // r+i
2307     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2308       return false;    // r+i
2309 
2310     Base = N.getOperand(0);
2311     Index = N.getOperand(1);
2312     return true;
2313   } else if (N.getOpcode() == ISD::OR) {
2314     if (isIntS16Immediate(N.getOperand(1), imm) &&
2315         (!EncodingAlignment || !(imm % EncodingAlignment)))
2316       return false; // r+i can fold it if we can.
2317 
2318     // If this is an or of disjoint bitfields, we can codegen this as an add
2319     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2320     // disjoint.
2321     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2322 
2323     if (LHSKnown.Zero.getBoolValue()) {
2324       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2325       // If all of the bits are known zero on the LHS or RHS, the add won't
2326       // carry.
2327       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2328         Base = N.getOperand(0);
2329         Index = N.getOperand(1);
2330         return true;
2331       }
2332     }
2333   }
2334 
2335   return false;
2336 }
2337 
2338 // If we happen to be doing an i64 load or store into a stack slot that has
2339 // less than a 4-byte alignment, then the frame-index elimination may need to
2340 // use an indexed load or store instruction (because the offset may not be a
2341 // multiple of 4). The extra register needed to hold the offset comes from the
2342 // register scavenger, and it is possible that the scavenger will need to use
2343 // an emergency spill slot. As a result, we need to make sure that a spill slot
2344 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2345 // stack slot.
2346 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2347   // FIXME: This does not handle the LWA case.
2348   if (VT != MVT::i64)
2349     return;
2350 
2351   // NOTE: We'll exclude negative FIs here, which come from argument
2352   // lowering, because there are no known test cases triggering this problem
2353   // using packed structures (or similar). We can remove this exclusion if
2354   // we find such a test case. The reason why this is so test-case driven is
2355   // because this entire 'fixup' is only to prevent crashes (from the
2356   // register scavenger) on not-really-valid inputs. For example, if we have:
2357   //   %a = alloca i1
2358   //   %b = bitcast i1* %a to i64*
2359   //   store i64* a, i64 b
2360   // then the store should really be marked as 'align 1', but is not. If it
2361   // were marked as 'align 1' then the indexed form would have been
2362   // instruction-selected initially, and the problem this 'fixup' is preventing
2363   // won't happen regardless.
2364   if (FrameIdx < 0)
2365     return;
2366 
2367   MachineFunction &MF = DAG.getMachineFunction();
2368   MachineFrameInfo &MFI = MF.getFrameInfo();
2369 
2370   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2371   if (Align >= 4)
2372     return;
2373 
2374   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2375   FuncInfo->setHasNonRISpills();
2376 }
2377 
2378 /// Returns true if the address N can be represented by a base register plus
2379 /// a signed 16-bit displacement [r+imm], and if it is not better
2380 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2381 /// displacements that are multiples of that value.
2382 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2383                                             SDValue &Base,
2384                                             SelectionDAG &DAG,
2385                                             unsigned EncodingAlignment) const {
2386   // FIXME dl should come from parent load or store, not from address
2387   SDLoc dl(N);
2388   // If this can be more profitably realized as r+r, fail.
2389   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2390     return false;
2391 
2392   if (N.getOpcode() == ISD::ADD) {
2393     int16_t imm = 0;
2394     if (isIntS16Immediate(N.getOperand(1), imm) &&
2395         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2396       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2397       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2398         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2399         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2400       } else {
2401         Base = N.getOperand(0);
2402       }
2403       return true; // [r+i]
2404     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2405       // Match LOAD (ADD (X, Lo(G))).
2406       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2407              && "Cannot handle constant offsets yet!");
2408       Disp = N.getOperand(1).getOperand(0);  // The global address.
2409       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2410              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2411              Disp.getOpcode() == ISD::TargetConstantPool ||
2412              Disp.getOpcode() == ISD::TargetJumpTable);
2413       Base = N.getOperand(0);
2414       return true;  // [&g+r]
2415     }
2416   } else if (N.getOpcode() == ISD::OR) {
2417     int16_t imm = 0;
2418     if (isIntS16Immediate(N.getOperand(1), imm) &&
2419         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2420       // If this is an or of disjoint bitfields, we can codegen this as an add
2421       // (for better address arithmetic) if the LHS and RHS of the OR are
2422       // provably disjoint.
2423       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2424 
2425       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2426         // If all of the bits are known zero on the LHS or RHS, the add won't
2427         // carry.
2428         if (FrameIndexSDNode *FI =
2429               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2430           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2431           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2432         } else {
2433           Base = N.getOperand(0);
2434         }
2435         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2436         return true;
2437       }
2438     }
2439   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2440     // Loading from a constant address.
2441 
2442     // If this address fits entirely in a 16-bit sext immediate field, codegen
2443     // this as "d, 0"
2444     int16_t Imm;
2445     if (isIntS16Immediate(CN, Imm) &&
2446         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2447       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2448       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2449                              CN->getValueType(0));
2450       return true;
2451     }
2452 
2453     // Handle 32-bit sext immediates with LIS + addr mode.
2454     if ((CN->getValueType(0) == MVT::i32 ||
2455          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2456         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2457       int Addr = (int)CN->getZExtValue();
2458 
2459       // Otherwise, break this down into an LIS + disp.
2460       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2461 
2462       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2463                                    MVT::i32);
2464       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2465       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2466       return true;
2467     }
2468   }
2469 
2470   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2471   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2472     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2473     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2474   } else
2475     Base = N;
2476   return true;      // [r+0]
2477 }
2478 
2479 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2480 /// represented as an indexed [r+r] operation.
2481 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2482                                                 SDValue &Index,
2483                                                 SelectionDAG &DAG) const {
2484   // Check to see if we can easily represent this as an [r+r] address.  This
2485   // will fail if it thinks that the address is more profitably represented as
2486   // reg+imm, e.g. where imm = 0.
2487   if (SelectAddressRegReg(N, Base, Index, DAG))
2488     return true;
2489 
2490   // If the address is the result of an add, we will utilize the fact that the
2491   // address calculation includes an implicit add.  However, we can reduce
2492   // register pressure if we do not materialize a constant just for use as the
2493   // index register.  We only get rid of the add if it is not an add of a
2494   // value and a 16-bit signed constant and both have a single use.
2495   int16_t imm = 0;
2496   if (N.getOpcode() == ISD::ADD &&
2497       (!isIntS16Immediate(N.getOperand(1), imm) ||
2498        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2499     Base = N.getOperand(0);
2500     Index = N.getOperand(1);
2501     return true;
2502   }
2503 
2504   // Otherwise, do it the hard way, using R0 as the base register.
2505   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2506                          N.getValueType());
2507   Index = N;
2508   return true;
2509 }
2510 
2511 /// Returns true if we should use a direct load into vector instruction
2512 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2513 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2514 
2515   // If there are any other uses other than scalar to vector, then we should
2516   // keep it as a scalar load -> direct move pattern to prevent multiple
2517   // loads.
2518   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2519   if (!LD)
2520     return false;
2521 
2522   EVT MemVT = LD->getMemoryVT();
2523   if (!MemVT.isSimple())
2524     return false;
2525   switch(MemVT.getSimpleVT().SimpleTy) {
2526   case MVT::i64:
2527     break;
2528   case MVT::i32:
2529     if (!ST.hasP8Vector())
2530       return false;
2531     break;
2532   case MVT::i16:
2533   case MVT::i8:
2534     if (!ST.hasP9Vector())
2535       return false;
2536     break;
2537   default:
2538     return false;
2539   }
2540 
2541   SDValue LoadedVal(N, 0);
2542   if (!LoadedVal.hasOneUse())
2543     return false;
2544 
2545   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2546        UI != UE; ++UI)
2547     if (UI.getUse().get().getResNo() == 0 &&
2548         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2549       return false;
2550 
2551   return true;
2552 }
2553 
2554 /// getPreIndexedAddressParts - returns true by value, base pointer and
2555 /// offset pointer and addressing mode by reference if the node's address
2556 /// can be legally represented as pre-indexed load / store address.
2557 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2558                                                   SDValue &Offset,
2559                                                   ISD::MemIndexedMode &AM,
2560                                                   SelectionDAG &DAG) const {
2561   if (DisablePPCPreinc) return false;
2562 
2563   bool isLoad = true;
2564   SDValue Ptr;
2565   EVT VT;
2566   unsigned Alignment;
2567   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2568     Ptr = LD->getBasePtr();
2569     VT = LD->getMemoryVT();
2570     Alignment = LD->getAlignment();
2571   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2572     Ptr = ST->getBasePtr();
2573     VT  = ST->getMemoryVT();
2574     Alignment = ST->getAlignment();
2575     isLoad = false;
2576   } else
2577     return false;
2578 
2579   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2580   // instructions because we can fold these into a more efficient instruction
2581   // instead, (such as LXSD).
2582   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2583     return false;
2584   }
2585 
2586   // PowerPC doesn't have preinc load/store instructions for vectors (except
2587   // for QPX, which does have preinc r+r forms).
2588   if (VT.isVector()) {
2589     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2590       return false;
2591     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2592       AM = ISD::PRE_INC;
2593       return true;
2594     }
2595   }
2596 
2597   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2598     // Common code will reject creating a pre-inc form if the base pointer
2599     // is a frame index, or if N is a store and the base pointer is either
2600     // the same as or a predecessor of the value being stored.  Check for
2601     // those situations here, and try with swapped Base/Offset instead.
2602     bool Swap = false;
2603 
2604     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2605       Swap = true;
2606     else if (!isLoad) {
2607       SDValue Val = cast<StoreSDNode>(N)->getValue();
2608       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2609         Swap = true;
2610     }
2611 
2612     if (Swap)
2613       std::swap(Base, Offset);
2614 
2615     AM = ISD::PRE_INC;
2616     return true;
2617   }
2618 
2619   // LDU/STU can only handle immediates that are a multiple of 4.
2620   if (VT != MVT::i64) {
2621     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2622       return false;
2623   } else {
2624     // LDU/STU need an address with at least 4-byte alignment.
2625     if (Alignment < 4)
2626       return false;
2627 
2628     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2629       return false;
2630   }
2631 
2632   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2633     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2634     // sext i32 to i64 when addr mode is r+i.
2635     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2636         LD->getExtensionType() == ISD::SEXTLOAD &&
2637         isa<ConstantSDNode>(Offset))
2638       return false;
2639   }
2640 
2641   AM = ISD::PRE_INC;
2642   return true;
2643 }
2644 
2645 //===----------------------------------------------------------------------===//
2646 //  LowerOperation implementation
2647 //===----------------------------------------------------------------------===//
2648 
2649 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2650 /// and LoOpFlags to the target MO flags.
2651 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2652                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2653                                const GlobalValue *GV = nullptr) {
2654   HiOpFlags = PPCII::MO_HA;
2655   LoOpFlags = PPCII::MO_LO;
2656 
2657   // Don't use the pic base if not in PIC relocation model.
2658   if (IsPIC) {
2659     HiOpFlags |= PPCII::MO_PIC_FLAG;
2660     LoOpFlags |= PPCII::MO_PIC_FLAG;
2661   }
2662 
2663   // If this is a reference to a global value that requires a non-lazy-ptr, make
2664   // sure that instruction lowering adds it.
2665   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2666     HiOpFlags |= PPCII::MO_NLP_FLAG;
2667     LoOpFlags |= PPCII::MO_NLP_FLAG;
2668 
2669     if (GV->hasHiddenVisibility()) {
2670       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2671       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2672     }
2673   }
2674 }
2675 
2676 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2677                              SelectionDAG &DAG) {
2678   SDLoc DL(HiPart);
2679   EVT PtrVT = HiPart.getValueType();
2680   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2681 
2682   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2683   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2684 
2685   // With PIC, the first instruction is actually "GR+hi(&G)".
2686   if (isPIC)
2687     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2688                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2689 
2690   // Generate non-pic code that has direct accesses to the constant pool.
2691   // The address of the global is just (hi(&g)+lo(&g)).
2692   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2693 }
2694 
2695 static void setUsesTOCBasePtr(MachineFunction &MF) {
2696   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2697   FuncInfo->setUsesTOCBasePtr();
2698 }
2699 
2700 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2701   setUsesTOCBasePtr(DAG.getMachineFunction());
2702 }
2703 
2704 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2705                                        SDValue GA) const {
2706   const bool Is64Bit = Subtarget.isPPC64();
2707   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2708   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2709                         : Subtarget.isAIXABI()
2710                               ? DAG.getRegister(PPC::R2, VT)
2711                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2712   SDValue Ops[] = { GA, Reg };
2713   return DAG.getMemIntrinsicNode(
2714       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2715       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2716       MachineMemOperand::MOLoad);
2717 }
2718 
2719 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2720                                              SelectionDAG &DAG) const {
2721   EVT PtrVT = Op.getValueType();
2722   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2723   const Constant *C = CP->getConstVal();
2724 
2725   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2726   // The actual address of the GlobalValue is stored in the TOC.
2727   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2728     setUsesTOCBasePtr(DAG);
2729     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2730     return getTOCEntry(DAG, SDLoc(CP), GA);
2731   }
2732 
2733   unsigned MOHiFlag, MOLoFlag;
2734   bool IsPIC = isPositionIndependent();
2735   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2736 
2737   if (IsPIC && Subtarget.isSVR4ABI()) {
2738     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2739                                            PPCII::MO_PIC_FLAG);
2740     return getTOCEntry(DAG, SDLoc(CP), GA);
2741   }
2742 
2743   SDValue CPIHi =
2744     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2745   SDValue CPILo =
2746     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2747   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2748 }
2749 
2750 // For 64-bit PowerPC, prefer the more compact relative encodings.
2751 // This trades 32 bits per jump table entry for one or two instructions
2752 // on the jump site.
2753 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2754   if (isJumpTableRelative())
2755     return MachineJumpTableInfo::EK_LabelDifference32;
2756 
2757   return TargetLowering::getJumpTableEncoding();
2758 }
2759 
2760 bool PPCTargetLowering::isJumpTableRelative() const {
2761   if (UseAbsoluteJumpTables)
2762     return false;
2763   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2764     return true;
2765   return TargetLowering::isJumpTableRelative();
2766 }
2767 
2768 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2769                                                     SelectionDAG &DAG) const {
2770   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2771     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2772 
2773   switch (getTargetMachine().getCodeModel()) {
2774   case CodeModel::Small:
2775   case CodeModel::Medium:
2776     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2777   default:
2778     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2779                        getPointerTy(DAG.getDataLayout()));
2780   }
2781 }
2782 
2783 const MCExpr *
2784 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2785                                                 unsigned JTI,
2786                                                 MCContext &Ctx) const {
2787   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2788     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2789 
2790   switch (getTargetMachine().getCodeModel()) {
2791   case CodeModel::Small:
2792   case CodeModel::Medium:
2793     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2794   default:
2795     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2796   }
2797 }
2798 
2799 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2800   EVT PtrVT = Op.getValueType();
2801   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2802 
2803   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2804   // The actual address of the GlobalValue is stored in the TOC.
2805   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2806     setUsesTOCBasePtr(DAG);
2807     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2808     return getTOCEntry(DAG, SDLoc(JT), GA);
2809   }
2810 
2811   unsigned MOHiFlag, MOLoFlag;
2812   bool IsPIC = isPositionIndependent();
2813   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2814 
2815   if (IsPIC && Subtarget.isSVR4ABI()) {
2816     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2817                                         PPCII::MO_PIC_FLAG);
2818     return getTOCEntry(DAG, SDLoc(GA), GA);
2819   }
2820 
2821   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2822   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2823   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2824 }
2825 
2826 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2827                                              SelectionDAG &DAG) const {
2828   EVT PtrVT = Op.getValueType();
2829   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2830   const BlockAddress *BA = BASDN->getBlockAddress();
2831 
2832   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2833   // The actual BlockAddress is stored in the TOC.
2834   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2835     setUsesTOCBasePtr(DAG);
2836     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2837     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2838   }
2839 
2840   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2841   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2842     return getTOCEntry(
2843         DAG, SDLoc(BASDN),
2844         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2845 
2846   unsigned MOHiFlag, MOLoFlag;
2847   bool IsPIC = isPositionIndependent();
2848   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2849   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2850   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2851   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2852 }
2853 
2854 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2855                                               SelectionDAG &DAG) const {
2856   // FIXME: TLS addresses currently use medium model code sequences,
2857   // which is the most useful form.  Eventually support for small and
2858   // large models could be added if users need it, at the cost of
2859   // additional complexity.
2860   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2861   if (DAG.getTarget().useEmulatedTLS())
2862     return LowerToTLSEmulatedModel(GA, DAG);
2863 
2864   SDLoc dl(GA);
2865   const GlobalValue *GV = GA->getGlobal();
2866   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2867   bool is64bit = Subtarget.isPPC64();
2868   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2869   PICLevel::Level picLevel = M->getPICLevel();
2870 
2871   const TargetMachine &TM = getTargetMachine();
2872   TLSModel::Model Model = TM.getTLSModel(GV);
2873 
2874   if (Model == TLSModel::LocalExec) {
2875     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2876                                                PPCII::MO_TPREL_HA);
2877     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2878                                                PPCII::MO_TPREL_LO);
2879     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2880                              : DAG.getRegister(PPC::R2, MVT::i32);
2881 
2882     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2883     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2884   }
2885 
2886   if (Model == TLSModel::InitialExec) {
2887     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2888     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2889                                                 PPCII::MO_TLS);
2890     SDValue GOTPtr;
2891     if (is64bit) {
2892       setUsesTOCBasePtr(DAG);
2893       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2894       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2895                            PtrVT, GOTReg, TGA);
2896     } else {
2897       if (!TM.isPositionIndependent())
2898         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2899       else if (picLevel == PICLevel::SmallPIC)
2900         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2901       else
2902         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2903     }
2904     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2905                                    PtrVT, TGA, GOTPtr);
2906     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2907   }
2908 
2909   if (Model == TLSModel::GeneralDynamic) {
2910     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2911     SDValue GOTPtr;
2912     if (is64bit) {
2913       setUsesTOCBasePtr(DAG);
2914       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2915       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2916                                    GOTReg, TGA);
2917     } else {
2918       if (picLevel == PICLevel::SmallPIC)
2919         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2920       else
2921         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2922     }
2923     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2924                        GOTPtr, TGA, TGA);
2925   }
2926 
2927   if (Model == TLSModel::LocalDynamic) {
2928     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2929     SDValue GOTPtr;
2930     if (is64bit) {
2931       setUsesTOCBasePtr(DAG);
2932       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2933       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2934                            GOTReg, TGA);
2935     } else {
2936       if (picLevel == PICLevel::SmallPIC)
2937         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2938       else
2939         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2940     }
2941     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2942                                   PtrVT, GOTPtr, TGA, TGA);
2943     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2944                                       PtrVT, TLSAddr, TGA);
2945     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2946   }
2947 
2948   llvm_unreachable("Unknown TLS model!");
2949 }
2950 
2951 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2952                                               SelectionDAG &DAG) const {
2953   EVT PtrVT = Op.getValueType();
2954   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2955   SDLoc DL(GSDN);
2956   const GlobalValue *GV = GSDN->getGlobal();
2957 
2958   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2959   // The actual address of the GlobalValue is stored in the TOC.
2960   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2961     setUsesTOCBasePtr(DAG);
2962     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2963     return getTOCEntry(DAG, DL, GA);
2964   }
2965 
2966   unsigned MOHiFlag, MOLoFlag;
2967   bool IsPIC = isPositionIndependent();
2968   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2969 
2970   if (IsPIC && Subtarget.isSVR4ABI()) {
2971     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2972                                             GSDN->getOffset(),
2973                                             PPCII::MO_PIC_FLAG);
2974     return getTOCEntry(DAG, DL, GA);
2975   }
2976 
2977   SDValue GAHi =
2978     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2979   SDValue GALo =
2980     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2981 
2982   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2983 
2984   // If the global reference is actually to a non-lazy-pointer, we have to do an
2985   // extra load to get the address of the global.
2986   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2987     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2988   return Ptr;
2989 }
2990 
2991 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2992   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2993   SDLoc dl(Op);
2994 
2995   if (Op.getValueType() == MVT::v2i64) {
2996     // When the operands themselves are v2i64 values, we need to do something
2997     // special because VSX has no underlying comparison operations for these.
2998     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2999       // Equality can be handled by casting to the legal type for Altivec
3000       // comparisons, everything else needs to be expanded.
3001       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3002         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3003                  DAG.getSetCC(dl, MVT::v4i32,
3004                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3005                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3006                    CC));
3007       }
3008 
3009       return SDValue();
3010     }
3011 
3012     // We handle most of these in the usual way.
3013     return Op;
3014   }
3015 
3016   // If we're comparing for equality to zero, expose the fact that this is
3017   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3018   // fold the new nodes.
3019   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3020     return V;
3021 
3022   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3023     // Leave comparisons against 0 and -1 alone for now, since they're usually
3024     // optimized.  FIXME: revisit this when we can custom lower all setcc
3025     // optimizations.
3026     if (C->isAllOnesValue() || C->isNullValue())
3027       return SDValue();
3028   }
3029 
3030   // If we have an integer seteq/setne, turn it into a compare against zero
3031   // by xor'ing the rhs with the lhs, which is faster than setting a
3032   // condition register, reading it back out, and masking the correct bit.  The
3033   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3034   // the result to other bit-twiddling opportunities.
3035   EVT LHSVT = Op.getOperand(0).getValueType();
3036   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3037     EVT VT = Op.getValueType();
3038     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3039                                 Op.getOperand(1));
3040     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3041   }
3042   return SDValue();
3043 }
3044 
3045 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3046   SDNode *Node = Op.getNode();
3047   EVT VT = Node->getValueType(0);
3048   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3049   SDValue InChain = Node->getOperand(0);
3050   SDValue VAListPtr = Node->getOperand(1);
3051   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3052   SDLoc dl(Node);
3053 
3054   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3055 
3056   // gpr_index
3057   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3058                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3059   InChain = GprIndex.getValue(1);
3060 
3061   if (VT == MVT::i64) {
3062     // Check if GprIndex is even
3063     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3064                                  DAG.getConstant(1, dl, MVT::i32));
3065     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3066                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3067     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3068                                           DAG.getConstant(1, dl, MVT::i32));
3069     // Align GprIndex to be even if it isn't
3070     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3071                            GprIndex);
3072   }
3073 
3074   // fpr index is 1 byte after gpr
3075   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3076                                DAG.getConstant(1, dl, MVT::i32));
3077 
3078   // fpr
3079   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3080                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3081   InChain = FprIndex.getValue(1);
3082 
3083   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3084                                        DAG.getConstant(8, dl, MVT::i32));
3085 
3086   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3087                                         DAG.getConstant(4, dl, MVT::i32));
3088 
3089   // areas
3090   SDValue OverflowArea =
3091       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3092   InChain = OverflowArea.getValue(1);
3093 
3094   SDValue RegSaveArea =
3095       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3096   InChain = RegSaveArea.getValue(1);
3097 
3098   // select overflow_area if index > 8
3099   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3100                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3101 
3102   // adjustment constant gpr_index * 4/8
3103   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3104                                     VT.isInteger() ? GprIndex : FprIndex,
3105                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3106                                                     MVT::i32));
3107 
3108   // OurReg = RegSaveArea + RegConstant
3109   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3110                                RegConstant);
3111 
3112   // Floating types are 32 bytes into RegSaveArea
3113   if (VT.isFloatingPoint())
3114     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3115                          DAG.getConstant(32, dl, MVT::i32));
3116 
3117   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3118   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3119                                    VT.isInteger() ? GprIndex : FprIndex,
3120                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3121                                                    MVT::i32));
3122 
3123   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3124                               VT.isInteger() ? VAListPtr : FprPtr,
3125                               MachinePointerInfo(SV), MVT::i8);
3126 
3127   // determine if we should load from reg_save_area or overflow_area
3128   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3129 
3130   // increase overflow_area by 4/8 if gpr/fpr > 8
3131   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3132                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3133                                           dl, MVT::i32));
3134 
3135   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3136                              OverflowAreaPlusN);
3137 
3138   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3139                               MachinePointerInfo(), MVT::i32);
3140 
3141   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3142 }
3143 
3144 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3145   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3146 
3147   // We have to copy the entire va_list struct:
3148   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3149   return DAG.getMemcpy(Op.getOperand(0), Op,
3150                        Op.getOperand(1), Op.getOperand(2),
3151                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3152                        false, MachinePointerInfo(), MachinePointerInfo());
3153 }
3154 
3155 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3156                                                   SelectionDAG &DAG) const {
3157   return Op.getOperand(0);
3158 }
3159 
3160 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3161                                                 SelectionDAG &DAG) const {
3162   SDValue Chain = Op.getOperand(0);
3163   SDValue Trmp = Op.getOperand(1); // trampoline
3164   SDValue FPtr = Op.getOperand(2); // nested function
3165   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3166   SDLoc dl(Op);
3167 
3168   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3169   bool isPPC64 = (PtrVT == MVT::i64);
3170   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3171 
3172   TargetLowering::ArgListTy Args;
3173   TargetLowering::ArgListEntry Entry;
3174 
3175   Entry.Ty = IntPtrTy;
3176   Entry.Node = Trmp; Args.push_back(Entry);
3177 
3178   // TrampSize == (isPPC64 ? 48 : 40);
3179   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3180                                isPPC64 ? MVT::i64 : MVT::i32);
3181   Args.push_back(Entry);
3182 
3183   Entry.Node = FPtr; Args.push_back(Entry);
3184   Entry.Node = Nest; Args.push_back(Entry);
3185 
3186   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3187   TargetLowering::CallLoweringInfo CLI(DAG);
3188   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3189       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3190       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3191 
3192   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3193   return CallResult.second;
3194 }
3195 
3196 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3197   MachineFunction &MF = DAG.getMachineFunction();
3198   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3199   EVT PtrVT = getPointerTy(MF.getDataLayout());
3200 
3201   SDLoc dl(Op);
3202 
3203   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3204     // vastart just stores the address of the VarArgsFrameIndex slot into the
3205     // memory location argument.
3206     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3207     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3208     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3209                         MachinePointerInfo(SV));
3210   }
3211 
3212   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3213   // We suppose the given va_list is already allocated.
3214   //
3215   // typedef struct {
3216   //  char gpr;     /* index into the array of 8 GPRs
3217   //                 * stored in the register save area
3218   //                 * gpr=0 corresponds to r3,
3219   //                 * gpr=1 to r4, etc.
3220   //                 */
3221   //  char fpr;     /* index into the array of 8 FPRs
3222   //                 * stored in the register save area
3223   //                 * fpr=0 corresponds to f1,
3224   //                 * fpr=1 to f2, etc.
3225   //                 */
3226   //  char *overflow_arg_area;
3227   //                /* location on stack that holds
3228   //                 * the next overflow argument
3229   //                 */
3230   //  char *reg_save_area;
3231   //               /* where r3:r10 and f1:f8 (if saved)
3232   //                * are stored
3233   //                */
3234   // } va_list[1];
3235 
3236   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3237   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3238   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3239                                             PtrVT);
3240   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3241                                  PtrVT);
3242 
3243   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3244   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3245 
3246   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3247   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3248 
3249   uint64_t FPROffset = 1;
3250   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3251 
3252   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3253 
3254   // Store first byte : number of int regs
3255   SDValue firstStore =
3256       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3257                         MachinePointerInfo(SV), MVT::i8);
3258   uint64_t nextOffset = FPROffset;
3259   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3260                                   ConstFPROffset);
3261 
3262   // Store second byte : number of float regs
3263   SDValue secondStore =
3264       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3265                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3266   nextOffset += StackOffset;
3267   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3268 
3269   // Store second word : arguments given on stack
3270   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3271                                     MachinePointerInfo(SV, nextOffset));
3272   nextOffset += FrameOffset;
3273   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3274 
3275   // Store third word : arguments given in registers
3276   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3277                       MachinePointerInfo(SV, nextOffset));
3278 }
3279 
3280 /// FPR - The set of FP registers that should be allocated for arguments
3281 /// on Darwin and AIX.
3282 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3283                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3284                                 PPC::F11, PPC::F12, PPC::F13};
3285 
3286 /// QFPR - The set of QPX registers that should be allocated for arguments.
3287 static const MCPhysReg QFPR[] = {
3288     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3289     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3290 
3291 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3292 /// the stack.
3293 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3294                                        unsigned PtrByteSize) {
3295   unsigned ArgSize = ArgVT.getStoreSize();
3296   if (Flags.isByVal())
3297     ArgSize = Flags.getByValSize();
3298 
3299   // Round up to multiples of the pointer size, except for array members,
3300   // which are always packed.
3301   if (!Flags.isInConsecutiveRegs())
3302     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3303 
3304   return ArgSize;
3305 }
3306 
3307 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3308 /// on the stack.
3309 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3310                                             ISD::ArgFlagsTy Flags,
3311                                             unsigned PtrByteSize) {
3312   unsigned Align = PtrByteSize;
3313 
3314   // Altivec parameters are padded to a 16 byte boundary.
3315   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3316       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3317       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3318       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3319     Align = 16;
3320   // QPX vector types stored in double-precision are padded to a 32 byte
3321   // boundary.
3322   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3323     Align = 32;
3324 
3325   // ByVal parameters are aligned as requested.
3326   if (Flags.isByVal()) {
3327     unsigned BVAlign = Flags.getByValAlign();
3328     if (BVAlign > PtrByteSize) {
3329       if (BVAlign % PtrByteSize != 0)
3330           llvm_unreachable(
3331             "ByVal alignment is not a multiple of the pointer size");
3332 
3333       Align = BVAlign;
3334     }
3335   }
3336 
3337   // Array members are always packed to their original alignment.
3338   if (Flags.isInConsecutiveRegs()) {
3339     // If the array member was split into multiple registers, the first
3340     // needs to be aligned to the size of the full type.  (Except for
3341     // ppcf128, which is only aligned as its f64 components.)
3342     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3343       Align = OrigVT.getStoreSize();
3344     else
3345       Align = ArgVT.getStoreSize();
3346   }
3347 
3348   return Align;
3349 }
3350 
3351 /// CalculateStackSlotUsed - Return whether this argument will use its
3352 /// stack slot (instead of being passed in registers).  ArgOffset,
3353 /// AvailableFPRs, and AvailableVRs must hold the current argument
3354 /// position, and will be updated to account for this argument.
3355 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3356                                    ISD::ArgFlagsTy Flags,
3357                                    unsigned PtrByteSize,
3358                                    unsigned LinkageSize,
3359                                    unsigned ParamAreaSize,
3360                                    unsigned &ArgOffset,
3361                                    unsigned &AvailableFPRs,
3362                                    unsigned &AvailableVRs, bool HasQPX) {
3363   bool UseMemory = false;
3364 
3365   // Respect alignment of argument on the stack.
3366   unsigned Align =
3367     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3368   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3369   // If there's no space left in the argument save area, we must
3370   // use memory (this check also catches zero-sized arguments).
3371   if (ArgOffset >= LinkageSize + ParamAreaSize)
3372     UseMemory = true;
3373 
3374   // Allocate argument on the stack.
3375   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3376   if (Flags.isInConsecutiveRegsLast())
3377     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3378   // If we overran the argument save area, we must use memory
3379   // (this check catches arguments passed partially in memory)
3380   if (ArgOffset > LinkageSize + ParamAreaSize)
3381     UseMemory = true;
3382 
3383   // However, if the argument is actually passed in an FPR or a VR,
3384   // we don't use memory after all.
3385   if (!Flags.isByVal()) {
3386     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3387         // QPX registers overlap with the scalar FP registers.
3388         (HasQPX && (ArgVT == MVT::v4f32 ||
3389                     ArgVT == MVT::v4f64 ||
3390                     ArgVT == MVT::v4i1)))
3391       if (AvailableFPRs > 0) {
3392         --AvailableFPRs;
3393         return false;
3394       }
3395     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3396         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3397         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3398         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3399       if (AvailableVRs > 0) {
3400         --AvailableVRs;
3401         return false;
3402       }
3403   }
3404 
3405   return UseMemory;
3406 }
3407 
3408 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3409 /// ensure minimum alignment required for target.
3410 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3411                                      unsigned NumBytes) {
3412   unsigned TargetAlign = Lowering->getStackAlignment();
3413   unsigned AlignMask = TargetAlign - 1;
3414   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3415   return NumBytes;
3416 }
3417 
3418 SDValue PPCTargetLowering::LowerFormalArguments(
3419     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3420     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3421     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3422   if (Subtarget.isAIXABI())
3423     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3424                                     InVals);
3425   if (Subtarget.is64BitELFABI())
3426     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3427                                        InVals);
3428   if (Subtarget.is32BitELFABI())
3429     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3430                                        InVals);
3431 
3432   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3433                                      InVals);
3434 }
3435 
3436 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3437     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3438     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3439     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3440 
3441   // 32-bit SVR4 ABI Stack Frame Layout:
3442   //              +-----------------------------------+
3443   //        +-->  |            Back chain             |
3444   //        |     +-----------------------------------+
3445   //        |     | Floating-point register save area |
3446   //        |     +-----------------------------------+
3447   //        |     |    General register save area     |
3448   //        |     +-----------------------------------+
3449   //        |     |          CR save word             |
3450   //        |     +-----------------------------------+
3451   //        |     |         VRSAVE save word          |
3452   //        |     +-----------------------------------+
3453   //        |     |         Alignment padding         |
3454   //        |     +-----------------------------------+
3455   //        |     |     Vector register save area     |
3456   //        |     +-----------------------------------+
3457   //        |     |       Local variable space        |
3458   //        |     +-----------------------------------+
3459   //        |     |        Parameter list area        |
3460   //        |     +-----------------------------------+
3461   //        |     |           LR save word            |
3462   //        |     +-----------------------------------+
3463   // SP-->  +---  |            Back chain             |
3464   //              +-----------------------------------+
3465   //
3466   // Specifications:
3467   //   System V Application Binary Interface PowerPC Processor Supplement
3468   //   AltiVec Technology Programming Interface Manual
3469 
3470   MachineFunction &MF = DAG.getMachineFunction();
3471   MachineFrameInfo &MFI = MF.getFrameInfo();
3472   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3473 
3474   EVT PtrVT = getPointerTy(MF.getDataLayout());
3475   // Potential tail calls could cause overwriting of argument stack slots.
3476   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3477                        (CallConv == CallingConv::Fast));
3478   unsigned PtrByteSize = 4;
3479 
3480   // Assign locations to all of the incoming arguments.
3481   SmallVector<CCValAssign, 16> ArgLocs;
3482   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3483                  *DAG.getContext());
3484 
3485   // Reserve space for the linkage area on the stack.
3486   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3487   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3488   if (useSoftFloat())
3489     CCInfo.PreAnalyzeFormalArguments(Ins);
3490 
3491   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3492   CCInfo.clearWasPPCF128();
3493 
3494   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3495     CCValAssign &VA = ArgLocs[i];
3496 
3497     // Arguments stored in registers.
3498     if (VA.isRegLoc()) {
3499       const TargetRegisterClass *RC;
3500       EVT ValVT = VA.getValVT();
3501 
3502       switch (ValVT.getSimpleVT().SimpleTy) {
3503         default:
3504           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3505         case MVT::i1:
3506         case MVT::i32:
3507           RC = &PPC::GPRCRegClass;
3508           break;
3509         case MVT::f32:
3510           if (Subtarget.hasP8Vector())
3511             RC = &PPC::VSSRCRegClass;
3512           else if (Subtarget.hasSPE())
3513             RC = &PPC::GPRCRegClass;
3514           else
3515             RC = &PPC::F4RCRegClass;
3516           break;
3517         case MVT::f64:
3518           if (Subtarget.hasVSX())
3519             RC = &PPC::VSFRCRegClass;
3520           else if (Subtarget.hasSPE())
3521             // SPE passes doubles in GPR pairs.
3522             RC = &PPC::GPRCRegClass;
3523           else
3524             RC = &PPC::F8RCRegClass;
3525           break;
3526         case MVT::v16i8:
3527         case MVT::v8i16:
3528         case MVT::v4i32:
3529           RC = &PPC::VRRCRegClass;
3530           break;
3531         case MVT::v4f32:
3532           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3533           break;
3534         case MVT::v2f64:
3535         case MVT::v2i64:
3536           RC = &PPC::VRRCRegClass;
3537           break;
3538         case MVT::v4f64:
3539           RC = &PPC::QFRCRegClass;
3540           break;
3541         case MVT::v4i1:
3542           RC = &PPC::QBRCRegClass;
3543           break;
3544       }
3545 
3546       SDValue ArgValue;
3547       // Transform the arguments stored in physical registers into
3548       // virtual ones.
3549       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3550         assert(i + 1 < e && "No second half of double precision argument");
3551         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3552         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3553         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3554         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3555         if (!Subtarget.isLittleEndian())
3556           std::swap (ArgValueLo, ArgValueHi);
3557         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3558                                ArgValueHi);
3559       } else {
3560         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3561         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3562                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3563         if (ValVT == MVT::i1)
3564           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3565       }
3566 
3567       InVals.push_back(ArgValue);
3568     } else {
3569       // Argument stored in memory.
3570       assert(VA.isMemLoc());
3571 
3572       // Get the extended size of the argument type in stack
3573       unsigned ArgSize = VA.getLocVT().getStoreSize();
3574       // Get the actual size of the argument type
3575       unsigned ObjSize = VA.getValVT().getStoreSize();
3576       unsigned ArgOffset = VA.getLocMemOffset();
3577       // Stack objects in PPC32 are right justified.
3578       ArgOffset += ArgSize - ObjSize;
3579       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3580 
3581       // Create load nodes to retrieve arguments from the stack.
3582       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3583       InVals.push_back(
3584           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3585     }
3586   }
3587 
3588   // Assign locations to all of the incoming aggregate by value arguments.
3589   // Aggregates passed by value are stored in the local variable space of the
3590   // caller's stack frame, right above the parameter list area.
3591   SmallVector<CCValAssign, 16> ByValArgLocs;
3592   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3593                       ByValArgLocs, *DAG.getContext());
3594 
3595   // Reserve stack space for the allocations in CCInfo.
3596   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3597 
3598   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3599 
3600   // Area that is at least reserved in the caller of this function.
3601   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3602   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3603 
3604   // Set the size that is at least reserved in caller of this function.  Tail
3605   // call optimized function's reserved stack space needs to be aligned so that
3606   // taking the difference between two stack areas will result in an aligned
3607   // stack.
3608   MinReservedArea =
3609       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3610   FuncInfo->setMinReservedArea(MinReservedArea);
3611 
3612   SmallVector<SDValue, 8> MemOps;
3613 
3614   // If the function takes variable number of arguments, make a frame index for
3615   // the start of the first vararg value... for expansion of llvm.va_start.
3616   if (isVarArg) {
3617     static const MCPhysReg GPArgRegs[] = {
3618       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3619       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3620     };
3621     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3622 
3623     static const MCPhysReg FPArgRegs[] = {
3624       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3625       PPC::F8
3626     };
3627     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3628 
3629     if (useSoftFloat() || hasSPE())
3630        NumFPArgRegs = 0;
3631 
3632     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3633     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3634 
3635     // Make room for NumGPArgRegs and NumFPArgRegs.
3636     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3637                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3638 
3639     FuncInfo->setVarArgsStackOffset(
3640       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3641                             CCInfo.getNextStackOffset(), true));
3642 
3643     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3644     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3645 
3646     // The fixed integer arguments of a variadic function are stored to the
3647     // VarArgsFrameIndex on the stack so that they may be loaded by
3648     // dereferencing the result of va_next.
3649     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3650       // Get an existing live-in vreg, or add a new one.
3651       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3652       if (!VReg)
3653         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3654 
3655       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3656       SDValue Store =
3657           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3658       MemOps.push_back(Store);
3659       // Increment the address by four for the next argument to store
3660       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3661       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3662     }
3663 
3664     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3665     // is set.
3666     // The double arguments are stored to the VarArgsFrameIndex
3667     // on the stack.
3668     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3669       // Get an existing live-in vreg, or add a new one.
3670       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3671       if (!VReg)
3672         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3673 
3674       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3675       SDValue Store =
3676           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3677       MemOps.push_back(Store);
3678       // Increment the address by eight for the next argument to store
3679       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3680                                          PtrVT);
3681       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3682     }
3683   }
3684 
3685   if (!MemOps.empty())
3686     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3687 
3688   return Chain;
3689 }
3690 
3691 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3692 // value to MVT::i64 and then truncate to the correct register size.
3693 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3694                                              EVT ObjectVT, SelectionDAG &DAG,
3695                                              SDValue ArgVal,
3696                                              const SDLoc &dl) const {
3697   if (Flags.isSExt())
3698     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3699                          DAG.getValueType(ObjectVT));
3700   else if (Flags.isZExt())
3701     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3702                          DAG.getValueType(ObjectVT));
3703 
3704   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3705 }
3706 
3707 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3708     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3709     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3710     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3711   // TODO: add description of PPC stack frame format, or at least some docs.
3712   //
3713   bool isELFv2ABI = Subtarget.isELFv2ABI();
3714   bool isLittleEndian = Subtarget.isLittleEndian();
3715   MachineFunction &MF = DAG.getMachineFunction();
3716   MachineFrameInfo &MFI = MF.getFrameInfo();
3717   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3718 
3719   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3720          "fastcc not supported on varargs functions");
3721 
3722   EVT PtrVT = getPointerTy(MF.getDataLayout());
3723   // Potential tail calls could cause overwriting of argument stack slots.
3724   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3725                        (CallConv == CallingConv::Fast));
3726   unsigned PtrByteSize = 8;
3727   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3728 
3729   static const MCPhysReg GPR[] = {
3730     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3731     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3732   };
3733   static const MCPhysReg VR[] = {
3734     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3735     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3736   };
3737 
3738   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3739   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3740   const unsigned Num_VR_Regs  = array_lengthof(VR);
3741   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3742 
3743   // Do a first pass over the arguments to determine whether the ABI
3744   // guarantees that our caller has allocated the parameter save area
3745   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3746   // in the ELFv2 ABI, it is true if this is a vararg function or if
3747   // any parameter is located in a stack slot.
3748 
3749   bool HasParameterArea = !isELFv2ABI || isVarArg;
3750   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3751   unsigned NumBytes = LinkageSize;
3752   unsigned AvailableFPRs = Num_FPR_Regs;
3753   unsigned AvailableVRs = Num_VR_Regs;
3754   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3755     if (Ins[i].Flags.isNest())
3756       continue;
3757 
3758     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3759                                PtrByteSize, LinkageSize, ParamAreaSize,
3760                                NumBytes, AvailableFPRs, AvailableVRs,
3761                                Subtarget.hasQPX()))
3762       HasParameterArea = true;
3763   }
3764 
3765   // Add DAG nodes to load the arguments or copy them out of registers.  On
3766   // entry to a function on PPC, the arguments start after the linkage area,
3767   // although the first ones are often in registers.
3768 
3769   unsigned ArgOffset = LinkageSize;
3770   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3771   unsigned &QFPR_idx = FPR_idx;
3772   SmallVector<SDValue, 8> MemOps;
3773   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3774   unsigned CurArgIdx = 0;
3775   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3776     SDValue ArgVal;
3777     bool needsLoad = false;
3778     EVT ObjectVT = Ins[ArgNo].VT;
3779     EVT OrigVT = Ins[ArgNo].ArgVT;
3780     unsigned ObjSize = ObjectVT.getStoreSize();
3781     unsigned ArgSize = ObjSize;
3782     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3783     if (Ins[ArgNo].isOrigArg()) {
3784       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3785       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3786     }
3787     // We re-align the argument offset for each argument, except when using the
3788     // fast calling convention, when we need to make sure we do that only when
3789     // we'll actually use a stack slot.
3790     unsigned CurArgOffset, Align;
3791     auto ComputeArgOffset = [&]() {
3792       /* Respect alignment of argument on the stack.  */
3793       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3794       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3795       CurArgOffset = ArgOffset;
3796     };
3797 
3798     if (CallConv != CallingConv::Fast) {
3799       ComputeArgOffset();
3800 
3801       /* Compute GPR index associated with argument offset.  */
3802       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3803       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3804     }
3805 
3806     // FIXME the codegen can be much improved in some cases.
3807     // We do not have to keep everything in memory.
3808     if (Flags.isByVal()) {
3809       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3810 
3811       if (CallConv == CallingConv::Fast)
3812         ComputeArgOffset();
3813 
3814       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3815       ObjSize = Flags.getByValSize();
3816       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3817       // Empty aggregate parameters do not take up registers.  Examples:
3818       //   struct { } a;
3819       //   union  { } b;
3820       //   int c[0];
3821       // etc.  However, we have to provide a place-holder in InVals, so
3822       // pretend we have an 8-byte item at the current address for that
3823       // purpose.
3824       if (!ObjSize) {
3825         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3826         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3827         InVals.push_back(FIN);
3828         continue;
3829       }
3830 
3831       // Create a stack object covering all stack doublewords occupied
3832       // by the argument.  If the argument is (fully or partially) on
3833       // the stack, or if the argument is fully in registers but the
3834       // caller has allocated the parameter save anyway, we can refer
3835       // directly to the caller's stack frame.  Otherwise, create a
3836       // local copy in our own frame.
3837       int FI;
3838       if (HasParameterArea ||
3839           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3840         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3841       else
3842         FI = MFI.CreateStackObject(ArgSize, Align, false);
3843       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3844 
3845       // Handle aggregates smaller than 8 bytes.
3846       if (ObjSize < PtrByteSize) {
3847         // The value of the object is its address, which differs from the
3848         // address of the enclosing doubleword on big-endian systems.
3849         SDValue Arg = FIN;
3850         if (!isLittleEndian) {
3851           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3852           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3853         }
3854         InVals.push_back(Arg);
3855 
3856         if (GPR_idx != Num_GPR_Regs) {
3857           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3858           FuncInfo->addLiveInAttr(VReg, Flags);
3859           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3860           SDValue Store;
3861 
3862           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3863             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3864                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3865             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3866                                       MachinePointerInfo(&*FuncArg), ObjType);
3867           } else {
3868             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3869             // store the whole register as-is to the parameter save area
3870             // slot.
3871             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3872                                  MachinePointerInfo(&*FuncArg));
3873           }
3874 
3875           MemOps.push_back(Store);
3876         }
3877         // Whether we copied from a register or not, advance the offset
3878         // into the parameter save area by a full doubleword.
3879         ArgOffset += PtrByteSize;
3880         continue;
3881       }
3882 
3883       // The value of the object is its address, which is the address of
3884       // its first stack doubleword.
3885       InVals.push_back(FIN);
3886 
3887       // Store whatever pieces of the object are in registers to memory.
3888       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3889         if (GPR_idx == Num_GPR_Regs)
3890           break;
3891 
3892         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3893         FuncInfo->addLiveInAttr(VReg, Flags);
3894         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3895         SDValue Addr = FIN;
3896         if (j) {
3897           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3898           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3899         }
3900         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3901                                      MachinePointerInfo(&*FuncArg, j));
3902         MemOps.push_back(Store);
3903         ++GPR_idx;
3904       }
3905       ArgOffset += ArgSize;
3906       continue;
3907     }
3908 
3909     switch (ObjectVT.getSimpleVT().SimpleTy) {
3910     default: llvm_unreachable("Unhandled argument type!");
3911     case MVT::i1:
3912     case MVT::i32:
3913     case MVT::i64:
3914       if (Flags.isNest()) {
3915         // The 'nest' parameter, if any, is passed in R11.
3916         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3917         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3918 
3919         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3920           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3921 
3922         break;
3923       }
3924 
3925       // These can be scalar arguments or elements of an integer array type
3926       // passed directly.  Clang may use those instead of "byval" aggregate
3927       // types to avoid forcing arguments to memory unnecessarily.
3928       if (GPR_idx != Num_GPR_Regs) {
3929         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3930         FuncInfo->addLiveInAttr(VReg, Flags);
3931         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3932 
3933         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3934           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3935           // value to MVT::i64 and then truncate to the correct register size.
3936           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3937       } else {
3938         if (CallConv == CallingConv::Fast)
3939           ComputeArgOffset();
3940 
3941         needsLoad = true;
3942         ArgSize = PtrByteSize;
3943       }
3944       if (CallConv != CallingConv::Fast || needsLoad)
3945         ArgOffset += 8;
3946       break;
3947 
3948     case MVT::f32:
3949     case MVT::f64:
3950       // These can be scalar arguments or elements of a float array type
3951       // passed directly.  The latter are used to implement ELFv2 homogenous
3952       // float aggregates.
3953       if (FPR_idx != Num_FPR_Regs) {
3954         unsigned VReg;
3955 
3956         if (ObjectVT == MVT::f32)
3957           VReg = MF.addLiveIn(FPR[FPR_idx],
3958                               Subtarget.hasP8Vector()
3959                                   ? &PPC::VSSRCRegClass
3960                                   : &PPC::F4RCRegClass);
3961         else
3962           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3963                                                 ? &PPC::VSFRCRegClass
3964                                                 : &PPC::F8RCRegClass);
3965 
3966         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3967         ++FPR_idx;
3968       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3969         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3970         // once we support fp <-> gpr moves.
3971 
3972         // This can only ever happen in the presence of f32 array types,
3973         // since otherwise we never run out of FPRs before running out
3974         // of GPRs.
3975         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3976         FuncInfo->addLiveInAttr(VReg, Flags);
3977         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3978 
3979         if (ObjectVT == MVT::f32) {
3980           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3981             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3982                                  DAG.getConstant(32, dl, MVT::i32));
3983           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3984         }
3985 
3986         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3987       } else {
3988         if (CallConv == CallingConv::Fast)
3989           ComputeArgOffset();
3990 
3991         needsLoad = true;
3992       }
3993 
3994       // When passing an array of floats, the array occupies consecutive
3995       // space in the argument area; only round up to the next doubleword
3996       // at the end of the array.  Otherwise, each float takes 8 bytes.
3997       if (CallConv != CallingConv::Fast || needsLoad) {
3998         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3999         ArgOffset += ArgSize;
4000         if (Flags.isInConsecutiveRegsLast())
4001           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4002       }
4003       break;
4004     case MVT::v4f32:
4005     case MVT::v4i32:
4006     case MVT::v8i16:
4007     case MVT::v16i8:
4008     case MVT::v2f64:
4009     case MVT::v2i64:
4010     case MVT::v1i128:
4011     case MVT::f128:
4012       if (!Subtarget.hasQPX()) {
4013         // These can be scalar arguments or elements of a vector array type
4014         // passed directly.  The latter are used to implement ELFv2 homogenous
4015         // vector aggregates.
4016         if (VR_idx != Num_VR_Regs) {
4017           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4018           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4019           ++VR_idx;
4020         } else {
4021           if (CallConv == CallingConv::Fast)
4022             ComputeArgOffset();
4023           needsLoad = true;
4024         }
4025         if (CallConv != CallingConv::Fast || needsLoad)
4026           ArgOffset += 16;
4027         break;
4028       } // not QPX
4029 
4030       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4031              "Invalid QPX parameter type");
4032       LLVM_FALLTHROUGH;
4033 
4034     case MVT::v4f64:
4035     case MVT::v4i1:
4036       // QPX vectors are treated like their scalar floating-point subregisters
4037       // (except that they're larger).
4038       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4039       if (QFPR_idx != Num_QFPR_Regs) {
4040         const TargetRegisterClass *RC;
4041         switch (ObjectVT.getSimpleVT().SimpleTy) {
4042         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4043         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4044         default:         RC = &PPC::QBRCRegClass; break;
4045         }
4046 
4047         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4048         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4049         ++QFPR_idx;
4050       } else {
4051         if (CallConv == CallingConv::Fast)
4052           ComputeArgOffset();
4053         needsLoad = true;
4054       }
4055       if (CallConv != CallingConv::Fast || needsLoad)
4056         ArgOffset += Sz;
4057       break;
4058     }
4059 
4060     // We need to load the argument to a virtual register if we determined
4061     // above that we ran out of physical registers of the appropriate type.
4062     if (needsLoad) {
4063       if (ObjSize < ArgSize && !isLittleEndian)
4064         CurArgOffset += ArgSize - ObjSize;
4065       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4066       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4067       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4068     }
4069 
4070     InVals.push_back(ArgVal);
4071   }
4072 
4073   // Area that is at least reserved in the caller of this function.
4074   unsigned MinReservedArea;
4075   if (HasParameterArea)
4076     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4077   else
4078     MinReservedArea = LinkageSize;
4079 
4080   // Set the size that is at least reserved in caller of this function.  Tail
4081   // call optimized functions' reserved stack space needs to be aligned so that
4082   // taking the difference between two stack areas will result in an aligned
4083   // stack.
4084   MinReservedArea =
4085       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4086   FuncInfo->setMinReservedArea(MinReservedArea);
4087 
4088   // If the function takes variable number of arguments, make a frame index for
4089   // the start of the first vararg value... for expansion of llvm.va_start.
4090   if (isVarArg) {
4091     int Depth = ArgOffset;
4092 
4093     FuncInfo->setVarArgsFrameIndex(
4094       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4095     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4096 
4097     // If this function is vararg, store any remaining integer argument regs
4098     // to their spots on the stack so that they may be loaded by dereferencing
4099     // the result of va_next.
4100     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4101          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4102       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4103       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4104       SDValue Store =
4105           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4106       MemOps.push_back(Store);
4107       // Increment the address by four for the next argument to store
4108       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4109       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4110     }
4111   }
4112 
4113   if (!MemOps.empty())
4114     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4115 
4116   return Chain;
4117 }
4118 
4119 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4120     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4121     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4122     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4123   // TODO: add description of PPC stack frame format, or at least some docs.
4124   //
4125   MachineFunction &MF = DAG.getMachineFunction();
4126   MachineFrameInfo &MFI = MF.getFrameInfo();
4127   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4128 
4129   EVT PtrVT = getPointerTy(MF.getDataLayout());
4130   bool isPPC64 = PtrVT == MVT::i64;
4131   // Potential tail calls could cause overwriting of argument stack slots.
4132   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4133                        (CallConv == CallingConv::Fast));
4134   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4135   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4136   unsigned ArgOffset = LinkageSize;
4137   // Area that is at least reserved in caller of this function.
4138   unsigned MinReservedArea = ArgOffset;
4139 
4140   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4141     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4142     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4143   };
4144   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4145     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4146     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4147   };
4148   static const MCPhysReg VR[] = {
4149     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4150     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4151   };
4152 
4153   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4154   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4155   const unsigned Num_VR_Regs  = array_lengthof( VR);
4156 
4157   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4158 
4159   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4160 
4161   // In 32-bit non-varargs functions, the stack space for vectors is after the
4162   // stack space for non-vectors.  We do not use this space unless we have
4163   // too many vectors to fit in registers, something that only occurs in
4164   // constructed examples:), but we have to walk the arglist to figure
4165   // that out...for the pathological case, compute VecArgOffset as the
4166   // start of the vector parameter area.  Computing VecArgOffset is the
4167   // entire point of the following loop.
4168   unsigned VecArgOffset = ArgOffset;
4169   if (!isVarArg && !isPPC64) {
4170     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4171          ++ArgNo) {
4172       EVT ObjectVT = Ins[ArgNo].VT;
4173       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4174 
4175       if (Flags.isByVal()) {
4176         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4177         unsigned ObjSize = Flags.getByValSize();
4178         unsigned ArgSize =
4179                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4180         VecArgOffset += ArgSize;
4181         continue;
4182       }
4183 
4184       switch(ObjectVT.getSimpleVT().SimpleTy) {
4185       default: llvm_unreachable("Unhandled argument type!");
4186       case MVT::i1:
4187       case MVT::i32:
4188       case MVT::f32:
4189         VecArgOffset += 4;
4190         break;
4191       case MVT::i64:  // PPC64
4192       case MVT::f64:
4193         // FIXME: We are guaranteed to be !isPPC64 at this point.
4194         // Does MVT::i64 apply?
4195         VecArgOffset += 8;
4196         break;
4197       case MVT::v4f32:
4198       case MVT::v4i32:
4199       case MVT::v8i16:
4200       case MVT::v16i8:
4201         // Nothing to do, we're only looking at Nonvector args here.
4202         break;
4203       }
4204     }
4205   }
4206   // We've found where the vector parameter area in memory is.  Skip the
4207   // first 12 parameters; these don't use that memory.
4208   VecArgOffset = ((VecArgOffset+15)/16)*16;
4209   VecArgOffset += 12*16;
4210 
4211   // Add DAG nodes to load the arguments or copy them out of registers.  On
4212   // entry to a function on PPC, the arguments start after the linkage area,
4213   // although the first ones are often in registers.
4214 
4215   SmallVector<SDValue, 8> MemOps;
4216   unsigned nAltivecParamsAtEnd = 0;
4217   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4218   unsigned CurArgIdx = 0;
4219   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4220     SDValue ArgVal;
4221     bool needsLoad = false;
4222     EVT ObjectVT = Ins[ArgNo].VT;
4223     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4224     unsigned ArgSize = ObjSize;
4225     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4226     if (Ins[ArgNo].isOrigArg()) {
4227       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4228       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4229     }
4230     unsigned CurArgOffset = ArgOffset;
4231 
4232     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4233     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4234         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4235       if (isVarArg || isPPC64) {
4236         MinReservedArea = ((MinReservedArea+15)/16)*16;
4237         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4238                                                   Flags,
4239                                                   PtrByteSize);
4240       } else  nAltivecParamsAtEnd++;
4241     } else
4242       // Calculate min reserved area.
4243       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4244                                                 Flags,
4245                                                 PtrByteSize);
4246 
4247     // FIXME the codegen can be much improved in some cases.
4248     // We do not have to keep everything in memory.
4249     if (Flags.isByVal()) {
4250       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4251 
4252       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4253       ObjSize = Flags.getByValSize();
4254       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4255       // Objects of size 1 and 2 are right justified, everything else is
4256       // left justified.  This means the memory address is adjusted forwards.
4257       if (ObjSize==1 || ObjSize==2) {
4258         CurArgOffset = CurArgOffset + (4 - ObjSize);
4259       }
4260       // The value of the object is its address.
4261       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4262       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4263       InVals.push_back(FIN);
4264       if (ObjSize==1 || ObjSize==2) {
4265         if (GPR_idx != Num_GPR_Regs) {
4266           unsigned VReg;
4267           if (isPPC64)
4268             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4269           else
4270             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4271           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4272           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4273           SDValue Store =
4274               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4275                                 MachinePointerInfo(&*FuncArg), ObjType);
4276           MemOps.push_back(Store);
4277           ++GPR_idx;
4278         }
4279 
4280         ArgOffset += PtrByteSize;
4281 
4282         continue;
4283       }
4284       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4285         // Store whatever pieces of the object are in registers
4286         // to memory.  ArgOffset will be the address of the beginning
4287         // of the object.
4288         if (GPR_idx != Num_GPR_Regs) {
4289           unsigned VReg;
4290           if (isPPC64)
4291             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4292           else
4293             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4294           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4295           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4296           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4297           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4298                                        MachinePointerInfo(&*FuncArg, j));
4299           MemOps.push_back(Store);
4300           ++GPR_idx;
4301           ArgOffset += PtrByteSize;
4302         } else {
4303           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4304           break;
4305         }
4306       }
4307       continue;
4308     }
4309 
4310     switch (ObjectVT.getSimpleVT().SimpleTy) {
4311     default: llvm_unreachable("Unhandled argument type!");
4312     case MVT::i1:
4313     case MVT::i32:
4314       if (!isPPC64) {
4315         if (GPR_idx != Num_GPR_Regs) {
4316           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4317           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4318 
4319           if (ObjectVT == MVT::i1)
4320             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4321 
4322           ++GPR_idx;
4323         } else {
4324           needsLoad = true;
4325           ArgSize = PtrByteSize;
4326         }
4327         // All int arguments reserve stack space in the Darwin ABI.
4328         ArgOffset += PtrByteSize;
4329         break;
4330       }
4331       LLVM_FALLTHROUGH;
4332     case MVT::i64:  // PPC64
4333       if (GPR_idx != Num_GPR_Regs) {
4334         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4335         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4336 
4337         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4338           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4339           // value to MVT::i64 and then truncate to the correct register size.
4340           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4341 
4342         ++GPR_idx;
4343       } else {
4344         needsLoad = true;
4345         ArgSize = PtrByteSize;
4346       }
4347       // All int arguments reserve stack space in the Darwin ABI.
4348       ArgOffset += 8;
4349       break;
4350 
4351     case MVT::f32:
4352     case MVT::f64:
4353       // Every 4 bytes of argument space consumes one of the GPRs available for
4354       // argument passing.
4355       if (GPR_idx != Num_GPR_Regs) {
4356         ++GPR_idx;
4357         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4358           ++GPR_idx;
4359       }
4360       if (FPR_idx != Num_FPR_Regs) {
4361         unsigned VReg;
4362 
4363         if (ObjectVT == MVT::f32)
4364           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4365         else
4366           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4367 
4368         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4369         ++FPR_idx;
4370       } else {
4371         needsLoad = true;
4372       }
4373 
4374       // All FP arguments reserve stack space in the Darwin ABI.
4375       ArgOffset += isPPC64 ? 8 : ObjSize;
4376       break;
4377     case MVT::v4f32:
4378     case MVT::v4i32:
4379     case MVT::v8i16:
4380     case MVT::v16i8:
4381       // Note that vector arguments in registers don't reserve stack space,
4382       // except in varargs functions.
4383       if (VR_idx != Num_VR_Regs) {
4384         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4385         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4386         if (isVarArg) {
4387           while ((ArgOffset % 16) != 0) {
4388             ArgOffset += PtrByteSize;
4389             if (GPR_idx != Num_GPR_Regs)
4390               GPR_idx++;
4391           }
4392           ArgOffset += 16;
4393           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4394         }
4395         ++VR_idx;
4396       } else {
4397         if (!isVarArg && !isPPC64) {
4398           // Vectors go after all the nonvectors.
4399           CurArgOffset = VecArgOffset;
4400           VecArgOffset += 16;
4401         } else {
4402           // Vectors are aligned.
4403           ArgOffset = ((ArgOffset+15)/16)*16;
4404           CurArgOffset = ArgOffset;
4405           ArgOffset += 16;
4406         }
4407         needsLoad = true;
4408       }
4409       break;
4410     }
4411 
4412     // We need to load the argument to a virtual register if we determined above
4413     // that we ran out of physical registers of the appropriate type.
4414     if (needsLoad) {
4415       int FI = MFI.CreateFixedObject(ObjSize,
4416                                      CurArgOffset + (ArgSize - ObjSize),
4417                                      isImmutable);
4418       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4419       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4420     }
4421 
4422     InVals.push_back(ArgVal);
4423   }
4424 
4425   // Allow for Altivec parameters at the end, if needed.
4426   if (nAltivecParamsAtEnd) {
4427     MinReservedArea = ((MinReservedArea+15)/16)*16;
4428     MinReservedArea += 16*nAltivecParamsAtEnd;
4429   }
4430 
4431   // Area that is at least reserved in the caller of this function.
4432   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4433 
4434   // Set the size that is at least reserved in caller of this function.  Tail
4435   // call optimized functions' reserved stack space needs to be aligned so that
4436   // taking the difference between two stack areas will result in an aligned
4437   // stack.
4438   MinReservedArea =
4439       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4440   FuncInfo->setMinReservedArea(MinReservedArea);
4441 
4442   // If the function takes variable number of arguments, make a frame index for
4443   // the start of the first vararg value... for expansion of llvm.va_start.
4444   if (isVarArg) {
4445     int Depth = ArgOffset;
4446 
4447     FuncInfo->setVarArgsFrameIndex(
4448       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4449                             Depth, true));
4450     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4451 
4452     // If this function is vararg, store any remaining integer argument regs
4453     // to their spots on the stack so that they may be loaded by dereferencing
4454     // the result of va_next.
4455     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4456       unsigned VReg;
4457 
4458       if (isPPC64)
4459         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4460       else
4461         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4462 
4463       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4464       SDValue Store =
4465           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4466       MemOps.push_back(Store);
4467       // Increment the address by four for the next argument to store
4468       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4469       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4470     }
4471   }
4472 
4473   if (!MemOps.empty())
4474     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4475 
4476   return Chain;
4477 }
4478 
4479 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4480 /// adjusted to accommodate the arguments for the tailcall.
4481 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4482                                    unsigned ParamSize) {
4483 
4484   if (!isTailCall) return 0;
4485 
4486   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4487   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4488   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4489   // Remember only if the new adjustment is bigger.
4490   if (SPDiff < FI->getTailCallSPDelta())
4491     FI->setTailCallSPDelta(SPDiff);
4492 
4493   return SPDiff;
4494 }
4495 
4496 static bool isFunctionGlobalAddress(SDValue Callee);
4497 
4498 static bool
4499 callsShareTOCBase(const Function *Caller, SDValue Callee,
4500                     const TargetMachine &TM) {
4501    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4502    // don't have enough information to determine if the caller and calle share
4503    // the same  TOC base, so we have to pessimistically assume they don't for
4504    // correctness.
4505    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4506    if (!G)
4507      return false;
4508 
4509    const GlobalValue *GV = G->getGlobal();
4510   // The medium and large code models are expected to provide a sufficiently
4511   // large TOC to provide all data addressing needs of a module with a
4512   // single TOC. Since each module will be addressed with a single TOC then we
4513   // only need to check that caller and callee don't cross dso boundaries.
4514   if (CodeModel::Medium == TM.getCodeModel() ||
4515       CodeModel::Large == TM.getCodeModel())
4516     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4517 
4518   // Otherwise we need to ensure callee and caller are in the same section,
4519   // since the linker may allocate multiple TOCs, and we don't know which
4520   // sections will belong to the same TOC base.
4521 
4522   if (!GV->isStrongDefinitionForLinker())
4523     return false;
4524 
4525   // Any explicitly-specified sections and section prefixes must also match.
4526   // Also, if we're using -ffunction-sections, then each function is always in
4527   // a different section (the same is true for COMDAT functions).
4528   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4529       GV->getSection() != Caller->getSection())
4530     return false;
4531   if (const auto *F = dyn_cast<Function>(GV)) {
4532     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4533       return false;
4534   }
4535 
4536   // If the callee might be interposed, then we can't assume the ultimate call
4537   // target will be in the same section. Even in cases where we can assume that
4538   // interposition won't happen, in any case where the linker might insert a
4539   // stub to allow for interposition, we must generate code as though
4540   // interposition might occur. To understand why this matters, consider a
4541   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4542   // in the same section, but a is in a different module (i.e. has a different
4543   // TOC base pointer). If the linker allows for interposition between b and c,
4544   // then it will generate a stub for the call edge between b and c which will
4545   // save the TOC pointer into the designated stack slot allocated by b. If we
4546   // return true here, and therefore allow a tail call between b and c, that
4547   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4548   // pointer into the stack slot allocated by a (where the a -> b stub saved
4549   // a's TOC base pointer). If we're not considering a tail call, but rather,
4550   // whether a nop is needed after the call instruction in b, because the linker
4551   // will insert a stub, it might complain about a missing nop if we omit it
4552   // (although many don't complain in this case).
4553   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4554     return false;
4555 
4556   return true;
4557 }
4558 
4559 static bool
4560 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4561                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4562   assert(Subtarget.is64BitELFABI());
4563 
4564   const unsigned PtrByteSize = 8;
4565   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4566 
4567   static const MCPhysReg GPR[] = {
4568     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4569     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4570   };
4571   static const MCPhysReg VR[] = {
4572     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4573     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4574   };
4575 
4576   const unsigned NumGPRs = array_lengthof(GPR);
4577   const unsigned NumFPRs = 13;
4578   const unsigned NumVRs = array_lengthof(VR);
4579   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4580 
4581   unsigned NumBytes = LinkageSize;
4582   unsigned AvailableFPRs = NumFPRs;
4583   unsigned AvailableVRs = NumVRs;
4584 
4585   for (const ISD::OutputArg& Param : Outs) {
4586     if (Param.Flags.isNest()) continue;
4587 
4588     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4589                                PtrByteSize, LinkageSize, ParamAreaSize,
4590                                NumBytes, AvailableFPRs, AvailableVRs,
4591                                Subtarget.hasQPX()))
4592       return true;
4593   }
4594   return false;
4595 }
4596 
4597 static bool
4598 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4599   if (CS.arg_size() != CallerFn->arg_size())
4600     return false;
4601 
4602   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4603   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4604   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4605 
4606   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4607     const Value* CalleeArg = *CalleeArgIter;
4608     const Value* CallerArg = &(*CallerArgIter);
4609     if (CalleeArg == CallerArg)
4610       continue;
4611 
4612     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4613     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4614     //      }
4615     // 1st argument of callee is undef and has the same type as caller.
4616     if (CalleeArg->getType() == CallerArg->getType() &&
4617         isa<UndefValue>(CalleeArg))
4618       continue;
4619 
4620     return false;
4621   }
4622 
4623   return true;
4624 }
4625 
4626 // Returns true if TCO is possible between the callers and callees
4627 // calling conventions.
4628 static bool
4629 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4630                                     CallingConv::ID CalleeCC) {
4631   // Tail calls are possible with fastcc and ccc.
4632   auto isTailCallableCC  = [] (CallingConv::ID CC){
4633       return  CC == CallingConv::C || CC == CallingConv::Fast;
4634   };
4635   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4636     return false;
4637 
4638   // We can safely tail call both fastcc and ccc callees from a c calling
4639   // convention caller. If the caller is fastcc, we may have less stack space
4640   // than a non-fastcc caller with the same signature so disable tail-calls in
4641   // that case.
4642   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4643 }
4644 
4645 bool
4646 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4647                                     SDValue Callee,
4648                                     CallingConv::ID CalleeCC,
4649                                     ImmutableCallSite CS,
4650                                     bool isVarArg,
4651                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4652                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4653                                     SelectionDAG& DAG) const {
4654   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4655 
4656   if (DisableSCO && !TailCallOpt) return false;
4657 
4658   // Variadic argument functions are not supported.
4659   if (isVarArg) return false;
4660 
4661   auto &Caller = DAG.getMachineFunction().getFunction();
4662   // Check that the calling conventions are compatible for tco.
4663   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4664     return false;
4665 
4666   // Caller contains any byval parameter is not supported.
4667   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4668     return false;
4669 
4670   // Callee contains any byval parameter is not supported, too.
4671   // Note: This is a quick work around, because in some cases, e.g.
4672   // caller's stack size > callee's stack size, we are still able to apply
4673   // sibling call optimization. For example, gcc is able to do SCO for caller1
4674   // in the following example, but not for caller2.
4675   //   struct test {
4676   //     long int a;
4677   //     char ary[56];
4678   //   } gTest;
4679   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4680   //     b->a = v.a;
4681   //     return 0;
4682   //   }
4683   //   void caller1(struct test a, struct test c, struct test *b) {
4684   //     callee(gTest, b); }
4685   //   void caller2(struct test *b) { callee(gTest, b); }
4686   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4687     return false;
4688 
4689   // If callee and caller use different calling conventions, we cannot pass
4690   // parameters on stack since offsets for the parameter area may be different.
4691   if (Caller.getCallingConv() != CalleeCC &&
4692       needStackSlotPassParameters(Subtarget, Outs))
4693     return false;
4694 
4695   // No TCO/SCO on indirect call because Caller have to restore its TOC
4696   if (!isFunctionGlobalAddress(Callee) &&
4697       !isa<ExternalSymbolSDNode>(Callee))
4698     return false;
4699 
4700   // If the caller and callee potentially have different TOC bases then we
4701   // cannot tail call since we need to restore the TOC pointer after the call.
4702   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4703   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4704     return false;
4705 
4706   // TCO allows altering callee ABI, so we don't have to check further.
4707   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4708     return true;
4709 
4710   if (DisableSCO) return false;
4711 
4712   // If callee use the same argument list that caller is using, then we can
4713   // apply SCO on this case. If it is not, then we need to check if callee needs
4714   // stack for passing arguments.
4715   if (!hasSameArgumentList(&Caller, CS) &&
4716       needStackSlotPassParameters(Subtarget, Outs)) {
4717     return false;
4718   }
4719 
4720   return true;
4721 }
4722 
4723 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4724 /// for tail call optimization. Targets which want to do tail call
4725 /// optimization should implement this function.
4726 bool
4727 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4728                                                      CallingConv::ID CalleeCC,
4729                                                      bool isVarArg,
4730                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4731                                                      SelectionDAG& DAG) const {
4732   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4733     return false;
4734 
4735   // Variable argument functions are not supported.
4736   if (isVarArg)
4737     return false;
4738 
4739   MachineFunction &MF = DAG.getMachineFunction();
4740   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4741   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4742     // Functions containing by val parameters are not supported.
4743     for (unsigned i = 0; i != Ins.size(); i++) {
4744        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4745        if (Flags.isByVal()) return false;
4746     }
4747 
4748     // Non-PIC/GOT tail calls are supported.
4749     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4750       return true;
4751 
4752     // At the moment we can only do local tail calls (in same module, hidden
4753     // or protected) if we are generating PIC.
4754     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4755       return G->getGlobal()->hasHiddenVisibility()
4756           || G->getGlobal()->hasProtectedVisibility();
4757   }
4758 
4759   return false;
4760 }
4761 
4762 /// isCallCompatibleAddress - Return the immediate to use if the specified
4763 /// 32-bit value is representable in the immediate field of a BxA instruction.
4764 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4765   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4766   if (!C) return nullptr;
4767 
4768   int Addr = C->getZExtValue();
4769   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4770       SignExtend32<26>(Addr) != Addr)
4771     return nullptr;  // Top 6 bits have to be sext of immediate.
4772 
4773   return DAG
4774       .getConstant(
4775           (int)C->getZExtValue() >> 2, SDLoc(Op),
4776           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4777       .getNode();
4778 }
4779 
4780 namespace {
4781 
4782 struct TailCallArgumentInfo {
4783   SDValue Arg;
4784   SDValue FrameIdxOp;
4785   int FrameIdx = 0;
4786 
4787   TailCallArgumentInfo() = default;
4788 };
4789 
4790 } // end anonymous namespace
4791 
4792 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4793 static void StoreTailCallArgumentsToStackSlot(
4794     SelectionDAG &DAG, SDValue Chain,
4795     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4796     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4797   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4798     SDValue Arg = TailCallArgs[i].Arg;
4799     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4800     int FI = TailCallArgs[i].FrameIdx;
4801     // Store relative to framepointer.
4802     MemOpChains.push_back(DAG.getStore(
4803         Chain, dl, Arg, FIN,
4804         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4805   }
4806 }
4807 
4808 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4809 /// the appropriate stack slot for the tail call optimized function call.
4810 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4811                                              SDValue OldRetAddr, SDValue OldFP,
4812                                              int SPDiff, const SDLoc &dl) {
4813   if (SPDiff) {
4814     // Calculate the new stack slot for the return address.
4815     MachineFunction &MF = DAG.getMachineFunction();
4816     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4817     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4818     bool isPPC64 = Subtarget.isPPC64();
4819     int SlotSize = isPPC64 ? 8 : 4;
4820     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4821     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4822                                                          NewRetAddrLoc, true);
4823     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4824     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4825     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4826                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4827 
4828     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4829     // slot as the FP is never overwritten.
4830     if (Subtarget.isDarwinABI()) {
4831       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4832       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4833                                                          true);
4834       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4835       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4836                            MachinePointerInfo::getFixedStack(
4837                                DAG.getMachineFunction(), NewFPIdx));
4838     }
4839   }
4840   return Chain;
4841 }
4842 
4843 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4844 /// the position of the argument.
4845 static void
4846 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4847                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4848                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4849   int Offset = ArgOffset + SPDiff;
4850   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4851   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4852   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4853   SDValue FIN = DAG.getFrameIndex(FI, VT);
4854   TailCallArgumentInfo Info;
4855   Info.Arg = Arg;
4856   Info.FrameIdxOp = FIN;
4857   Info.FrameIdx = FI;
4858   TailCallArguments.push_back(Info);
4859 }
4860 
4861 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4862 /// stack slot. Returns the chain as result and the loaded frame pointers in
4863 /// LROpOut/FPOpout. Used when tail calling.
4864 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4865     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4866     SDValue &FPOpOut, const SDLoc &dl) const {
4867   if (SPDiff) {
4868     // Load the LR and FP stack slot for later adjusting.
4869     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4870     LROpOut = getReturnAddrFrameIndex(DAG);
4871     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4872     Chain = SDValue(LROpOut.getNode(), 1);
4873 
4874     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4875     // slot as the FP is never overwritten.
4876     if (Subtarget.isDarwinABI()) {
4877       FPOpOut = getFramePointerFrameIndex(DAG);
4878       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4879       Chain = SDValue(FPOpOut.getNode(), 1);
4880     }
4881   }
4882   return Chain;
4883 }
4884 
4885 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4886 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4887 /// specified by the specific parameter attribute. The copy will be passed as
4888 /// a byval function parameter.
4889 /// Sometimes what we are copying is the end of a larger object, the part that
4890 /// does not fit in registers.
4891 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4892                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4893                                          SelectionDAG &DAG, const SDLoc &dl) {
4894   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4895   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4896                        false, false, false, MachinePointerInfo(),
4897                        MachinePointerInfo());
4898 }
4899 
4900 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4901 /// tail calls.
4902 static void LowerMemOpCallTo(
4903     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4904     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4905     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4906     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4907   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4908   if (!isTailCall) {
4909     if (isVector) {
4910       SDValue StackPtr;
4911       if (isPPC64)
4912         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4913       else
4914         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4915       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4916                            DAG.getConstant(ArgOffset, dl, PtrVT));
4917     }
4918     MemOpChains.push_back(
4919         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4920     // Calculate and remember argument location.
4921   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4922                                   TailCallArguments);
4923 }
4924 
4925 static void
4926 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4927                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4928                 SDValue FPOp,
4929                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4930   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4931   // might overwrite each other in case of tail call optimization.
4932   SmallVector<SDValue, 8> MemOpChains2;
4933   // Do not flag preceding copytoreg stuff together with the following stuff.
4934   InFlag = SDValue();
4935   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4936                                     MemOpChains2, dl);
4937   if (!MemOpChains2.empty())
4938     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4939 
4940   // Store the return address to the appropriate stack slot.
4941   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4942 
4943   // Emit callseq_end just before tailcall node.
4944   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4945                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4946   InFlag = Chain.getValue(1);
4947 }
4948 
4949 // Is this global address that of a function that can be called by name? (as
4950 // opposed to something that must hold a descriptor for an indirect call).
4951 static bool isFunctionGlobalAddress(SDValue Callee) {
4952   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4953     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4954         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4955       return false;
4956 
4957     return G->getGlobal()->getValueType()->isFunctionTy();
4958   }
4959 
4960   return false;
4961 }
4962 
4963 SDValue PPCTargetLowering::LowerCallResult(
4964     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4965     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4966     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4967   SmallVector<CCValAssign, 16> RVLocs;
4968   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4969                     *DAG.getContext());
4970 
4971   CCRetInfo.AnalyzeCallResult(
4972       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4973                ? RetCC_PPC_Cold
4974                : RetCC_PPC);
4975 
4976   // Copy all of the result registers out of their specified physreg.
4977   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4978     CCValAssign &VA = RVLocs[i];
4979     assert(VA.isRegLoc() && "Can only return in registers!");
4980 
4981     SDValue Val;
4982 
4983     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4984       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4985                                       InFlag);
4986       Chain = Lo.getValue(1);
4987       InFlag = Lo.getValue(2);
4988       VA = RVLocs[++i]; // skip ahead to next loc
4989       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4990                                       InFlag);
4991       Chain = Hi.getValue(1);
4992       InFlag = Hi.getValue(2);
4993       if (!Subtarget.isLittleEndian())
4994         std::swap (Lo, Hi);
4995       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4996     } else {
4997       Val = DAG.getCopyFromReg(Chain, dl,
4998                                VA.getLocReg(), VA.getLocVT(), InFlag);
4999       Chain = Val.getValue(1);
5000       InFlag = Val.getValue(2);
5001     }
5002 
5003     switch (VA.getLocInfo()) {
5004     default: llvm_unreachable("Unknown loc info!");
5005     case CCValAssign::Full: break;
5006     case CCValAssign::AExt:
5007       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5008       break;
5009     case CCValAssign::ZExt:
5010       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5011                         DAG.getValueType(VA.getValVT()));
5012       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5013       break;
5014     case CCValAssign::SExt:
5015       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5016                         DAG.getValueType(VA.getValVT()));
5017       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5018       break;
5019     }
5020 
5021     InVals.push_back(Val);
5022   }
5023 
5024   return Chain;
5025 }
5026 
5027 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5028                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5029   // PatchPoint calls are not indirect.
5030   if (isPatchPoint)
5031     return false;
5032 
5033   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5034     return false;
5035 
5036   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5037   // becuase the immediate function pointer points to a descriptor instead of
5038   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5039   // pointer immediate points to the global entry point, while the BLA would
5040   // need to jump to the local entry point (see rL211174).
5041   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5042       isBLACompatibleAddress(Callee, DAG))
5043     return false;
5044 
5045   return true;
5046 }
5047 
5048 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint,
5049                               bool isTailCall, const Function &Caller,
5050                               const SDValue &Callee,
5051                               const PPCSubtarget &Subtarget,
5052                               const TargetMachine &TM) {
5053   if (isTailCall)
5054     return PPCISD::TC_RETURN;
5055 
5056   // This is a call through a function pointer.
5057   if (isIndirectCall) {
5058     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5059     // indirect calls. The save of the caller's TOC pointer to the stack will be
5060     // inserted into the DAG as part of call lowering. The restore of the TOC
5061     // pointer is modeled by using a pseudo instruction for the call opcode that
5062     // represents the 2 instruction sequence of an indirect branch and link,
5063     // immediately followed by a load of the TOC pointer from the the stack save
5064     // slot into gpr2.
5065     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5066       return PPCISD::BCTRL_LOAD_TOC;
5067 
5068     // An indirect call that does not need a TOC restore.
5069     return PPCISD::BCTRL;
5070   }
5071 
5072   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5073   // immediately following the call instruction if the caller and callee may
5074   // have different TOC bases. At link time if the linker determines the calls
5075   // may not share a TOC base, the call is redirected to a trampoline inserted
5076   // by the linker. The trampoline will (among other things) save the callers
5077   // TOC pointer at an ABI designated offset in the linkage area and the linker
5078   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5079   // into gpr2.
5080   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5081     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5082                                                   : PPCISD::CALL_NOP;
5083 
5084   return PPCISD::CALL;
5085 }
5086 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5087                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5088   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5089     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5090       return SDValue(Dest, 0);
5091 
5092   // Returns true if the callee is local, and false otherwise.
5093   auto isLocalCallee = [&]() {
5094     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5095     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5096 
5097     return DAG.getTarget().shouldAssumeDSOLocal(*Mod,
5098                                                 G ? G->getGlobal() : nullptr);
5099   };
5100 
5101   bool UsePlt = Subtarget.is32BitELFABI() && !isLocalCallee();
5102 
5103   if (isFunctionGlobalAddress(Callee)) {
5104     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5105     if (!Subtarget.isAIXABI())
5106       return DAG.getTargetGlobalAddress(G->getGlobal(), dl,
5107                                         Callee.getValueType(), 0,
5108                                         UsePlt ? PPCII::MO_PLT : 0);
5109 
5110     // On AIX, direct function calls reference the symbol for the function's
5111     // entry point, which is named by prepending a "." before the function's
5112     // C-linkage name.
5113     auto &Context = DAG.getMachineFunction().getMMI().getContext();
5114 
5115     const GlobalObject *GO = cast<GlobalObject>(G->getGlobal());
5116     MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5117         Context.getOrCreateSymbol(Twine(".") + Twine(GO->getName())));
5118 
5119     if (GO && GO->isDeclaration() && !S->hasContainingCsect()) {
5120       // On AIX, an undefined symbol needs to be associated with a
5121       // MCSectionXCOFF to get the correct storage mapping class.
5122       // In this case, XCOFF::XMC_PR.
5123       const XCOFF::StorageClass SC =
5124           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5125       MCSectionXCOFF *Sec =
5126           Context.getXCOFFSection(S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5127                                   SC, SectionKind::getMetadata());
5128       S->setContainingCsect(Sec);
5129     }
5130 
5131     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5132     return DAG.getMCSymbol(S, PtrVT);
5133   }
5134 
5135   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
5136     return DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
5137                                        UsePlt ? PPCII::MO_PLT : 0);
5138 
5139   // No transformation needed.
5140   assert(Callee.getNode() && "What no callee?");
5141   return Callee;
5142 }
5143 
5144 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5145   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5146          "Expected a CALLSEQ_STARTSDNode.");
5147 
5148   // The last operand is the chain, except when the node has glue. If the node
5149   // has glue, then the last operand is the glue, and the chain is the second
5150   // last operand.
5151   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5152   if (LastValue.getValueType() != MVT::Glue)
5153     return LastValue;
5154 
5155   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5156 }
5157 
5158 // Creates the node that moves a functions address into the count register
5159 // to prepare for an indirect call instruction.
5160 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5161                                 SDValue &Glue, SDValue &Chain,
5162                                 const SDLoc &dl) {
5163   SDValue MTCTROps[] = {Chain, Callee, Glue};
5164   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5165   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5166                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5167   // The glue is the second value produced.
5168   Glue = Chain.getValue(1);
5169 }
5170 
5171 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5172                                           SDValue &Glue, SDValue &Chain,
5173                                           SDValue CallSeqStart,
5174                                           ImmutableCallSite CS, const SDLoc &dl,
5175                                           bool hasNest,
5176                                           const PPCSubtarget &Subtarget) {
5177   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5178   // entry point, but to the function descriptor (the function entry point
5179   // address is part of the function descriptor though).
5180   // The function descriptor is a three doubleword structure with the
5181   // following fields: function entry point, TOC base address and
5182   // environment pointer.
5183   // Thus for a call through a function pointer, the following actions need
5184   // to be performed:
5185   //   1. Save the TOC of the caller in the TOC save area of its stack
5186   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5187   //   2. Load the address of the function entry point from the function
5188   //      descriptor.
5189   //   3. Load the TOC of the callee from the function descriptor into r2.
5190   //   4. Load the environment pointer from the function descriptor into
5191   //      r11.
5192   //   5. Branch to the function entry point address.
5193   //   6. On return of the callee, the TOC of the caller needs to be
5194   //      restored (this is done in FinishCall()).
5195   //
5196   // The loads are scheduled at the beginning of the call sequence, and the
5197   // register copies are flagged together to ensure that no other
5198   // operations can be scheduled in between. E.g. without flagging the
5199   // copies together, a TOC access in the caller could be scheduled between
5200   // the assignment of the callee TOC and the branch to the callee, which leads
5201   // to incorrect code.
5202 
5203   // Start by loading the function address from the descriptor.
5204   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5205   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5206                       ? (MachineMemOperand::MODereferenceable |
5207                          MachineMemOperand::MOInvariant)
5208                       : MachineMemOperand::MONone;
5209 
5210   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5211 
5212   // One load for the functions entry point address.
5213   SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5214                                     /* Alignment = */ 8, MMOFlags);
5215 
5216   // One for loading the TOC anchor for the module that contains the called
5217   // function.
5218   SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5219   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5220   SDValue TOCPtr =
5221       DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5222                   /* Alignment = */ 8, MMOFlags);
5223 
5224   // One for loading the environment pointer.
5225   SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5226   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5227   SDValue LoadEnvPtr =
5228       DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5229                   /* Alignment = */ 8, MMOFlags);
5230 
5231   // Then copy the newly loaded TOC anchor to the TOC pointer.
5232   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, Glue);
5233   Chain = TOCVal.getValue(0);
5234   Glue = TOCVal.getValue(1);
5235 
5236   // If the function call has an explicit 'nest' parameter, it takes the
5237   // place of the environment pointer.
5238   if (!hasNest) {
5239     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, Glue);
5240     Chain = EnvVal.getValue(0);
5241     Glue = EnvVal.getValue(1);
5242   }
5243 
5244   // The rest of the indirect call sequence is the same as the non-descriptor
5245   // DAG.
5246   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5247 }
5248 
5249 static void
5250 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv,
5251                   const SDLoc &dl, bool isTailCall, bool isVarArg,
5252                   bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5253                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5254                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5255                   const PPCSubtarget &Subtarget, bool isIndirect) {
5256   const bool IsPPC64 = Subtarget.isPPC64();
5257   // MVT for a general purpose register.
5258   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5259 
5260   // First operand is always the chain.
5261   Ops.push_back(Chain);
5262 
5263   // If it's a direct call pass the callee as the second operand.
5264   if (!isIndirect)
5265     Ops.push_back(Callee);
5266   else {
5267     assert(!isPatchPoint && "Patch point call are not indirect.");
5268     if (Subtarget.isAIXABI())
5269       report_fatal_error("Indirect call on AIX is not implemented.");
5270 
5271     // For 64-bit ELF we have saved the TOC pointer to the linkage area on the
5272     // stack (this would have  been done in `LowerCall_64SVR4`). The call
5273     // instruction is a pseudo instruction that represents both the indirect
5274     // branch and a load that restores the TOC pointer from the linkage area.
5275     // The operand for the TOC restore is an add of the TOC save offset to the
5276     // stack pointer. This must be the second operand: after the chain input but
5277     // before any other variadic arguments.
5278     if (Subtarget.is64BitELFABI()) {
5279       SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5280       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5281       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5282       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5283       Ops.push_back(AddTOC);
5284     }
5285 
5286     // Add the register used for the environment pointer.
5287     if (Subtarget.usesFunctionDescriptors() && !hasNest)
5288       Ops.push_back(DAG.getRegister(PPC::X11, MVT::i64));
5289 
5290     // Add CTR register as callee so a bctr can be emitted later.
5291     if (isTailCall)
5292       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5293   }
5294 
5295   // If this is a tail call add stack pointer delta.
5296   if (isTailCall)
5297     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5298 
5299   // Add argument registers to the end of the list so that they are known live
5300   // into the call.
5301   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5302     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5303                                   RegsToPass[i].second.getValueType()));
5304 
5305   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5306   // no way to mark dependencies as implicit here.
5307   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5308   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint)
5309     Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::X2 : PPC::R2, RegVT));
5310 
5311   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5312   if (isVarArg && Subtarget.is32BitELFABI())
5313     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5314 
5315   // Add a register mask operand representing the call-preserved registers.
5316   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5317   const uint32_t *Mask =
5318       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5319   assert(Mask && "Missing call preserved mask for calling convention");
5320   Ops.push_back(DAG.getRegisterMask(Mask));
5321 
5322   // If the glue is valid, it is the last operand.
5323   if (Glue.getNode())
5324     Ops.push_back(Glue);
5325 }
5326 
5327 SDValue PPCTargetLowering::FinishCall(
5328     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5329     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5330     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5331     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5332     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5333     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5334 
5335   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5336     setUsesTOCBasePtr(DAG);
5337 
5338   const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint);
5339   unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall,
5340                                    DAG.getMachineFunction().getFunction(),
5341                                    Callee, Subtarget, DAG.getTarget());
5342 
5343   if (!isIndirect)
5344     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5345   else if (Subtarget.usesFunctionDescriptors())
5346     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5347                                   dl, hasNest, Subtarget);
5348   else
5349     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5350 
5351   // Build the operand list for the call instruction.
5352   SmallVector<SDValue, 8> Ops;
5353   buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5354                     hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff,
5355                     Subtarget, isIndirect);
5356 
5357   // Emit tail call.
5358   if (isTailCall) {
5359     assert(((Callee.getOpcode() == ISD::Register &&
5360              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5361             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5362             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5363             isa<ConstantSDNode>(Callee)) &&
5364            "Expecting a global address, external symbol, absolute value or "
5365            "register");
5366     assert(CallOpc == PPCISD::TC_RETURN &&
5367            "Unexpected call opcode for a tail call.");
5368     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5369     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5370   }
5371 
5372   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5373   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5374   Glue = Chain.getValue(1);
5375 
5376   // When performing tail call optimization the callee pops its arguments off
5377   // the stack. Account for this here so these bytes can be pushed back on in
5378   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5379   int BytesCalleePops = (CallConv == CallingConv::Fast &&
5380                          getTargetMachine().Options.GuaranteedTailCallOpt)
5381                             ? NumBytes
5382                             : 0;
5383 
5384   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5385                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5386                              Glue, dl);
5387   Glue = Chain.getValue(1);
5388 
5389   return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals);
5390 }
5391 
5392 SDValue
5393 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5394                              SmallVectorImpl<SDValue> &InVals) const {
5395   SelectionDAG &DAG                     = CLI.DAG;
5396   SDLoc &dl                             = CLI.DL;
5397   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5398   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5399   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5400   SDValue Chain                         = CLI.Chain;
5401   SDValue Callee                        = CLI.Callee;
5402   bool &isTailCall                      = CLI.IsTailCall;
5403   CallingConv::ID CallConv              = CLI.CallConv;
5404   bool isVarArg                         = CLI.IsVarArg;
5405   bool isPatchPoint                     = CLI.IsPatchPoint;
5406   ImmutableCallSite CS                  = CLI.CS;
5407 
5408   if (isTailCall) {
5409     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5410       isTailCall = false;
5411     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5412       isTailCall =
5413         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5414                                                  isVarArg, Outs, Ins, DAG);
5415     else
5416       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5417                                                      Ins, DAG);
5418     if (isTailCall) {
5419       ++NumTailCalls;
5420       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5421         ++NumSiblingCalls;
5422 
5423       assert(isa<GlobalAddressSDNode>(Callee) &&
5424              "Callee should be an llvm::Function object.");
5425       LLVM_DEBUG(
5426           const GlobalValue *GV =
5427               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5428           const unsigned Width =
5429               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5430           dbgs() << "TCO caller: "
5431                  << left_justify(DAG.getMachineFunction().getName(), Width)
5432                  << ", callee linkage: " << GV->getVisibility() << ", "
5433                  << GV->getLinkage() << "\n");
5434     }
5435   }
5436 
5437   if (!isTailCall && CS && CS.isMustTailCall())
5438     report_fatal_error("failed to perform tail call elimination on a call "
5439                        "site marked musttail");
5440 
5441   // When long calls (i.e. indirect calls) are always used, calls are always
5442   // made via function pointer. If we have a function name, first translate it
5443   // into a pointer.
5444   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5445       !isTailCall)
5446     Callee = LowerGlobalAddress(Callee, DAG);
5447 
5448   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5449     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5450                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5451                             dl, DAG, InVals, CS);
5452 
5453   if (Subtarget.isSVR4ABI())
5454     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5455                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5456                             dl, DAG, InVals, CS);
5457 
5458   if (Subtarget.isAIXABI())
5459     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5460                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5461                          dl, DAG, InVals, CS);
5462 
5463   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5464                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5465                           dl, DAG, InVals, CS);
5466 }
5467 
5468 SDValue PPCTargetLowering::LowerCall_32SVR4(
5469     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5470     bool isTailCall, bool isPatchPoint,
5471     const SmallVectorImpl<ISD::OutputArg> &Outs,
5472     const SmallVectorImpl<SDValue> &OutVals,
5473     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5474     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5475     ImmutableCallSite CS) const {
5476   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5477   // of the 32-bit SVR4 ABI stack frame layout.
5478 
5479   assert((CallConv == CallingConv::C ||
5480           CallConv == CallingConv::Cold ||
5481           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5482 
5483   unsigned PtrByteSize = 4;
5484 
5485   MachineFunction &MF = DAG.getMachineFunction();
5486 
5487   // Mark this function as potentially containing a function that contains a
5488   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5489   // and restoring the callers stack pointer in this functions epilog. This is
5490   // done because by tail calling the called function might overwrite the value
5491   // in this function's (MF) stack pointer stack slot 0(SP).
5492   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5493       CallConv == CallingConv::Fast)
5494     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5495 
5496   // Count how many bytes are to be pushed on the stack, including the linkage
5497   // area, parameter list area and the part of the local variable space which
5498   // contains copies of aggregates which are passed by value.
5499 
5500   // Assign locations to all of the outgoing arguments.
5501   SmallVector<CCValAssign, 16> ArgLocs;
5502   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5503 
5504   // Reserve space for the linkage area on the stack.
5505   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5506                        PtrByteSize);
5507   if (useSoftFloat())
5508     CCInfo.PreAnalyzeCallOperands(Outs);
5509 
5510   if (isVarArg) {
5511     // Handle fixed and variable vector arguments differently.
5512     // Fixed vector arguments go into registers as long as registers are
5513     // available. Variable vector arguments always go into memory.
5514     unsigned NumArgs = Outs.size();
5515 
5516     for (unsigned i = 0; i != NumArgs; ++i) {
5517       MVT ArgVT = Outs[i].VT;
5518       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5519       bool Result;
5520 
5521       if (Outs[i].IsFixed) {
5522         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5523                                CCInfo);
5524       } else {
5525         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5526                                       ArgFlags, CCInfo);
5527       }
5528 
5529       if (Result) {
5530 #ifndef NDEBUG
5531         errs() << "Call operand #" << i << " has unhandled type "
5532              << EVT(ArgVT).getEVTString() << "\n";
5533 #endif
5534         llvm_unreachable(nullptr);
5535       }
5536     }
5537   } else {
5538     // All arguments are treated the same.
5539     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5540   }
5541   CCInfo.clearWasPPCF128();
5542 
5543   // Assign locations to all of the outgoing aggregate by value arguments.
5544   SmallVector<CCValAssign, 16> ByValArgLocs;
5545   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5546 
5547   // Reserve stack space for the allocations in CCInfo.
5548   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5549 
5550   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5551 
5552   // Size of the linkage area, parameter list area and the part of the local
5553   // space variable where copies of aggregates which are passed by value are
5554   // stored.
5555   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5556 
5557   // Calculate by how many bytes the stack has to be adjusted in case of tail
5558   // call optimization.
5559   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5560 
5561   // Adjust the stack pointer for the new arguments...
5562   // These operations are automatically eliminated by the prolog/epilog pass
5563   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5564   SDValue CallSeqStart = Chain;
5565 
5566   // Load the return address and frame pointer so it can be moved somewhere else
5567   // later.
5568   SDValue LROp, FPOp;
5569   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5570 
5571   // Set up a copy of the stack pointer for use loading and storing any
5572   // arguments that may not fit in the registers available for argument
5573   // passing.
5574   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5575 
5576   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5577   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5578   SmallVector<SDValue, 8> MemOpChains;
5579 
5580   bool seenFloatArg = false;
5581   // Walk the register/memloc assignments, inserting copies/loads.
5582   // i - Tracks the index into the list of registers allocated for the call
5583   // RealArgIdx - Tracks the index into the list of actual function arguments
5584   // j - Tracks the index into the list of byval arguments
5585   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5586        i != e;
5587        ++i, ++RealArgIdx) {
5588     CCValAssign &VA = ArgLocs[i];
5589     SDValue Arg = OutVals[RealArgIdx];
5590     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5591 
5592     if (Flags.isByVal()) {
5593       // Argument is an aggregate which is passed by value, thus we need to
5594       // create a copy of it in the local variable space of the current stack
5595       // frame (which is the stack frame of the caller) and pass the address of
5596       // this copy to the callee.
5597       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5598       CCValAssign &ByValVA = ByValArgLocs[j++];
5599       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5600 
5601       // Memory reserved in the local variable space of the callers stack frame.
5602       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5603 
5604       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5605       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5606                            StackPtr, PtrOff);
5607 
5608       // Create a copy of the argument in the local area of the current
5609       // stack frame.
5610       SDValue MemcpyCall =
5611         CreateCopyOfByValArgument(Arg, PtrOff,
5612                                   CallSeqStart.getNode()->getOperand(0),
5613                                   Flags, DAG, dl);
5614 
5615       // This must go outside the CALLSEQ_START..END.
5616       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5617                                                      SDLoc(MemcpyCall));
5618       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5619                              NewCallSeqStart.getNode());
5620       Chain = CallSeqStart = NewCallSeqStart;
5621 
5622       // Pass the address of the aggregate copy on the stack either in a
5623       // physical register or in the parameter list area of the current stack
5624       // frame to the callee.
5625       Arg = PtrOff;
5626     }
5627 
5628     // When useCRBits() is true, there can be i1 arguments.
5629     // It is because getRegisterType(MVT::i1) => MVT::i1,
5630     // and for other integer types getRegisterType() => MVT::i32.
5631     // Extend i1 and ensure callee will get i32.
5632     if (Arg.getValueType() == MVT::i1)
5633       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5634                         dl, MVT::i32, Arg);
5635 
5636     if (VA.isRegLoc()) {
5637       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5638       // Put argument in a physical register.
5639       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5640         bool IsLE = Subtarget.isLittleEndian();
5641         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5642                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5643         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5644         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5645                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5646         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5647                              SVal.getValue(0)));
5648       } else
5649         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5650     } else {
5651       // Put argument in the parameter list area of the current stack frame.
5652       assert(VA.isMemLoc());
5653       unsigned LocMemOffset = VA.getLocMemOffset();
5654 
5655       if (!isTailCall) {
5656         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5657         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5658                              StackPtr, PtrOff);
5659 
5660         MemOpChains.push_back(
5661             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5662       } else {
5663         // Calculate and remember argument location.
5664         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5665                                  TailCallArguments);
5666       }
5667     }
5668   }
5669 
5670   if (!MemOpChains.empty())
5671     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5672 
5673   // Build a sequence of copy-to-reg nodes chained together with token chain
5674   // and flag operands which copy the outgoing args into the appropriate regs.
5675   SDValue InFlag;
5676   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5677     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5678                              RegsToPass[i].second, InFlag);
5679     InFlag = Chain.getValue(1);
5680   }
5681 
5682   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5683   // registers.
5684   if (isVarArg) {
5685     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5686     SDValue Ops[] = { Chain, InFlag };
5687 
5688     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5689                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5690 
5691     InFlag = Chain.getValue(1);
5692   }
5693 
5694   if (isTailCall)
5695     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5696                     TailCallArguments);
5697 
5698   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5699                     /* unused except on PPC64 ELFv1 */ false, DAG,
5700                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5701                     NumBytes, Ins, InVals, CS);
5702 }
5703 
5704 // Copy an argument into memory, being careful to do this outside the
5705 // call sequence for the call to which the argument belongs.
5706 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5707     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5708     SelectionDAG &DAG, const SDLoc &dl) const {
5709   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5710                         CallSeqStart.getNode()->getOperand(0),
5711                         Flags, DAG, dl);
5712   // The MEMCPY must go outside the CALLSEQ_START..END.
5713   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5714   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5715                                                  SDLoc(MemcpyCall));
5716   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5717                          NewCallSeqStart.getNode());
5718   return NewCallSeqStart;
5719 }
5720 
5721 SDValue PPCTargetLowering::LowerCall_64SVR4(
5722     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5723     bool isTailCall, bool isPatchPoint,
5724     const SmallVectorImpl<ISD::OutputArg> &Outs,
5725     const SmallVectorImpl<SDValue> &OutVals,
5726     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5727     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5728     ImmutableCallSite CS) const {
5729   bool isELFv2ABI = Subtarget.isELFv2ABI();
5730   bool isLittleEndian = Subtarget.isLittleEndian();
5731   unsigned NumOps = Outs.size();
5732   bool hasNest = false;
5733   bool IsSibCall = false;
5734 
5735   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5736   unsigned PtrByteSize = 8;
5737 
5738   MachineFunction &MF = DAG.getMachineFunction();
5739 
5740   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5741     IsSibCall = true;
5742 
5743   // Mark this function as potentially containing a function that contains a
5744   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5745   // and restoring the callers stack pointer in this functions epilog. This is
5746   // done because by tail calling the called function might overwrite the value
5747   // in this function's (MF) stack pointer stack slot 0(SP).
5748   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5749       CallConv == CallingConv::Fast)
5750     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5751 
5752   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5753          "fastcc not supported on varargs functions");
5754 
5755   // Count how many bytes are to be pushed on the stack, including the linkage
5756   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5757   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5758   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5759   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5760   unsigned NumBytes = LinkageSize;
5761   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5762   unsigned &QFPR_idx = FPR_idx;
5763 
5764   static const MCPhysReg GPR[] = {
5765     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5766     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5767   };
5768   static const MCPhysReg VR[] = {
5769     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5770     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5771   };
5772 
5773   const unsigned NumGPRs = array_lengthof(GPR);
5774   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5775   const unsigned NumVRs  = array_lengthof(VR);
5776   const unsigned NumQFPRs = NumFPRs;
5777 
5778   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5779   // can be passed to the callee in registers.
5780   // For the fast calling convention, there is another check below.
5781   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5782   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5783   if (!HasParameterArea) {
5784     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5785     unsigned AvailableFPRs = NumFPRs;
5786     unsigned AvailableVRs = NumVRs;
5787     unsigned NumBytesTmp = NumBytes;
5788     for (unsigned i = 0; i != NumOps; ++i) {
5789       if (Outs[i].Flags.isNest()) continue;
5790       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5791                                 PtrByteSize, LinkageSize, ParamAreaSize,
5792                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5793                                 Subtarget.hasQPX()))
5794         HasParameterArea = true;
5795     }
5796   }
5797 
5798   // When using the fast calling convention, we don't provide backing for
5799   // arguments that will be in registers.
5800   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5801 
5802   // Avoid allocating parameter area for fastcc functions if all the arguments
5803   // can be passed in the registers.
5804   if (CallConv == CallingConv::Fast)
5805     HasParameterArea = false;
5806 
5807   // Add up all the space actually used.
5808   for (unsigned i = 0; i != NumOps; ++i) {
5809     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5810     EVT ArgVT = Outs[i].VT;
5811     EVT OrigVT = Outs[i].ArgVT;
5812 
5813     if (Flags.isNest())
5814       continue;
5815 
5816     if (CallConv == CallingConv::Fast) {
5817       if (Flags.isByVal()) {
5818         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5819         if (NumGPRsUsed > NumGPRs)
5820           HasParameterArea = true;
5821       } else {
5822         switch (ArgVT.getSimpleVT().SimpleTy) {
5823         default: llvm_unreachable("Unexpected ValueType for argument!");
5824         case MVT::i1:
5825         case MVT::i32:
5826         case MVT::i64:
5827           if (++NumGPRsUsed <= NumGPRs)
5828             continue;
5829           break;
5830         case MVT::v4i32:
5831         case MVT::v8i16:
5832         case MVT::v16i8:
5833         case MVT::v2f64:
5834         case MVT::v2i64:
5835         case MVT::v1i128:
5836         case MVT::f128:
5837           if (++NumVRsUsed <= NumVRs)
5838             continue;
5839           break;
5840         case MVT::v4f32:
5841           // When using QPX, this is handled like a FP register, otherwise, it
5842           // is an Altivec register.
5843           if (Subtarget.hasQPX()) {
5844             if (++NumFPRsUsed <= NumFPRs)
5845               continue;
5846           } else {
5847             if (++NumVRsUsed <= NumVRs)
5848               continue;
5849           }
5850           break;
5851         case MVT::f32:
5852         case MVT::f64:
5853         case MVT::v4f64: // QPX
5854         case MVT::v4i1:  // QPX
5855           if (++NumFPRsUsed <= NumFPRs)
5856             continue;
5857           break;
5858         }
5859         HasParameterArea = true;
5860       }
5861     }
5862 
5863     /* Respect alignment of argument on the stack.  */
5864     unsigned Align =
5865       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5866     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5867 
5868     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5869     if (Flags.isInConsecutiveRegsLast())
5870       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5871   }
5872 
5873   unsigned NumBytesActuallyUsed = NumBytes;
5874 
5875   // In the old ELFv1 ABI,
5876   // the prolog code of the callee may store up to 8 GPR argument registers to
5877   // the stack, allowing va_start to index over them in memory if its varargs.
5878   // Because we cannot tell if this is needed on the caller side, we have to
5879   // conservatively assume that it is needed.  As such, make sure we have at
5880   // least enough stack space for the caller to store the 8 GPRs.
5881   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5882   // really requires memory operands, e.g. a vararg function.
5883   if (HasParameterArea)
5884     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5885   else
5886     NumBytes = LinkageSize;
5887 
5888   // Tail call needs the stack to be aligned.
5889   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5890       CallConv == CallingConv::Fast)
5891     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5892 
5893   int SPDiff = 0;
5894 
5895   // Calculate by how many bytes the stack has to be adjusted in case of tail
5896   // call optimization.
5897   if (!IsSibCall)
5898     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5899 
5900   // To protect arguments on the stack from being clobbered in a tail call,
5901   // force all the loads to happen before doing any other lowering.
5902   if (isTailCall)
5903     Chain = DAG.getStackArgumentTokenFactor(Chain);
5904 
5905   // Adjust the stack pointer for the new arguments...
5906   // These operations are automatically eliminated by the prolog/epilog pass
5907   if (!IsSibCall)
5908     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5909   SDValue CallSeqStart = Chain;
5910 
5911   // Load the return address and frame pointer so it can be move somewhere else
5912   // later.
5913   SDValue LROp, FPOp;
5914   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5915 
5916   // Set up a copy of the stack pointer for use loading and storing any
5917   // arguments that may not fit in the registers available for argument
5918   // passing.
5919   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5920 
5921   // Figure out which arguments are going to go in registers, and which in
5922   // memory.  Also, if this is a vararg function, floating point operations
5923   // must be stored to our stack, and loaded into integer regs as well, if
5924   // any integer regs are available for argument passing.
5925   unsigned ArgOffset = LinkageSize;
5926 
5927   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5928   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5929 
5930   SmallVector<SDValue, 8> MemOpChains;
5931   for (unsigned i = 0; i != NumOps; ++i) {
5932     SDValue Arg = OutVals[i];
5933     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5934     EVT ArgVT = Outs[i].VT;
5935     EVT OrigVT = Outs[i].ArgVT;
5936 
5937     // PtrOff will be used to store the current argument to the stack if a
5938     // register cannot be found for it.
5939     SDValue PtrOff;
5940 
5941     // We re-align the argument offset for each argument, except when using the
5942     // fast calling convention, when we need to make sure we do that only when
5943     // we'll actually use a stack slot.
5944     auto ComputePtrOff = [&]() {
5945       /* Respect alignment of argument on the stack.  */
5946       unsigned Align =
5947         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5948       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5949 
5950       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5951 
5952       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5953     };
5954 
5955     if (CallConv != CallingConv::Fast) {
5956       ComputePtrOff();
5957 
5958       /* Compute GPR index associated with argument offset.  */
5959       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5960       GPR_idx = std::min(GPR_idx, NumGPRs);
5961     }
5962 
5963     // Promote integers to 64-bit values.
5964     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5965       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5966       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5967       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5968     }
5969 
5970     // FIXME memcpy is used way more than necessary.  Correctness first.
5971     // Note: "by value" is code for passing a structure by value, not
5972     // basic types.
5973     if (Flags.isByVal()) {
5974       // Note: Size includes alignment padding, so
5975       //   struct x { short a; char b; }
5976       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5977       // These are the proper values we need for right-justifying the
5978       // aggregate in a parameter register.
5979       unsigned Size = Flags.getByValSize();
5980 
5981       // An empty aggregate parameter takes up no storage and no
5982       // registers.
5983       if (Size == 0)
5984         continue;
5985 
5986       if (CallConv == CallingConv::Fast)
5987         ComputePtrOff();
5988 
5989       // All aggregates smaller than 8 bytes must be passed right-justified.
5990       if (Size==1 || Size==2 || Size==4) {
5991         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5992         if (GPR_idx != NumGPRs) {
5993           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5994                                         MachinePointerInfo(), VT);
5995           MemOpChains.push_back(Load.getValue(1));
5996           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5997 
5998           ArgOffset += PtrByteSize;
5999           continue;
6000         }
6001       }
6002 
6003       if (GPR_idx == NumGPRs && Size < 8) {
6004         SDValue AddPtr = PtrOff;
6005         if (!isLittleEndian) {
6006           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6007                                           PtrOff.getValueType());
6008           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6009         }
6010         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6011                                                           CallSeqStart,
6012                                                           Flags, DAG, dl);
6013         ArgOffset += PtrByteSize;
6014         continue;
6015       }
6016       // Copy entire object into memory.  There are cases where gcc-generated
6017       // code assumes it is there, even if it could be put entirely into
6018       // registers.  (This is not what the doc says.)
6019 
6020       // FIXME: The above statement is likely due to a misunderstanding of the
6021       // documents.  All arguments must be copied into the parameter area BY
6022       // THE CALLEE in the event that the callee takes the address of any
6023       // formal argument.  That has not yet been implemented.  However, it is
6024       // reasonable to use the stack area as a staging area for the register
6025       // load.
6026 
6027       // Skip this for small aggregates, as we will use the same slot for a
6028       // right-justified copy, below.
6029       if (Size >= 8)
6030         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6031                                                           CallSeqStart,
6032                                                           Flags, DAG, dl);
6033 
6034       // When a register is available, pass a small aggregate right-justified.
6035       if (Size < 8 && GPR_idx != NumGPRs) {
6036         // The easiest way to get this right-justified in a register
6037         // is to copy the structure into the rightmost portion of a
6038         // local variable slot, then load the whole slot into the
6039         // register.
6040         // FIXME: The memcpy seems to produce pretty awful code for
6041         // small aggregates, particularly for packed ones.
6042         // FIXME: It would be preferable to use the slot in the
6043         // parameter save area instead of a new local variable.
6044         SDValue AddPtr = PtrOff;
6045         if (!isLittleEndian) {
6046           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6047           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6048         }
6049         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6050                                                           CallSeqStart,
6051                                                           Flags, DAG, dl);
6052 
6053         // Load the slot into the register.
6054         SDValue Load =
6055             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6056         MemOpChains.push_back(Load.getValue(1));
6057         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6058 
6059         // Done with this argument.
6060         ArgOffset += PtrByteSize;
6061         continue;
6062       }
6063 
6064       // For aggregates larger than PtrByteSize, copy the pieces of the
6065       // object that fit into registers from the parameter save area.
6066       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6067         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6068         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6069         if (GPR_idx != NumGPRs) {
6070           SDValue Load =
6071               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6072           MemOpChains.push_back(Load.getValue(1));
6073           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6074           ArgOffset += PtrByteSize;
6075         } else {
6076           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6077           break;
6078         }
6079       }
6080       continue;
6081     }
6082 
6083     switch (Arg.getSimpleValueType().SimpleTy) {
6084     default: llvm_unreachable("Unexpected ValueType for argument!");
6085     case MVT::i1:
6086     case MVT::i32:
6087     case MVT::i64:
6088       if (Flags.isNest()) {
6089         // The 'nest' parameter, if any, is passed in R11.
6090         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6091         hasNest = true;
6092         break;
6093       }
6094 
6095       // These can be scalar arguments or elements of an integer array type
6096       // passed directly.  Clang may use those instead of "byval" aggregate
6097       // types to avoid forcing arguments to memory unnecessarily.
6098       if (GPR_idx != NumGPRs) {
6099         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6100       } else {
6101         if (CallConv == CallingConv::Fast)
6102           ComputePtrOff();
6103 
6104         assert(HasParameterArea &&
6105                "Parameter area must exist to pass an argument in memory.");
6106         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6107                          true, isTailCall, false, MemOpChains,
6108                          TailCallArguments, dl);
6109         if (CallConv == CallingConv::Fast)
6110           ArgOffset += PtrByteSize;
6111       }
6112       if (CallConv != CallingConv::Fast)
6113         ArgOffset += PtrByteSize;
6114       break;
6115     case MVT::f32:
6116     case MVT::f64: {
6117       // These can be scalar arguments or elements of a float array type
6118       // passed directly.  The latter are used to implement ELFv2 homogenous
6119       // float aggregates.
6120 
6121       // Named arguments go into FPRs first, and once they overflow, the
6122       // remaining arguments go into GPRs and then the parameter save area.
6123       // Unnamed arguments for vararg functions always go to GPRs and
6124       // then the parameter save area.  For now, put all arguments to vararg
6125       // routines always in both locations (FPR *and* GPR or stack slot).
6126       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6127       bool NeededLoad = false;
6128 
6129       // First load the argument into the next available FPR.
6130       if (FPR_idx != NumFPRs)
6131         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6132 
6133       // Next, load the argument into GPR or stack slot if needed.
6134       if (!NeedGPROrStack)
6135         ;
6136       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6137         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6138         // once we support fp <-> gpr moves.
6139 
6140         // In the non-vararg case, this can only ever happen in the
6141         // presence of f32 array types, since otherwise we never run
6142         // out of FPRs before running out of GPRs.
6143         SDValue ArgVal;
6144 
6145         // Double values are always passed in a single GPR.
6146         if (Arg.getValueType() != MVT::f32) {
6147           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6148 
6149         // Non-array float values are extended and passed in a GPR.
6150         } else if (!Flags.isInConsecutiveRegs()) {
6151           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6152           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6153 
6154         // If we have an array of floats, we collect every odd element
6155         // together with its predecessor into one GPR.
6156         } else if (ArgOffset % PtrByteSize != 0) {
6157           SDValue Lo, Hi;
6158           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6159           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6160           if (!isLittleEndian)
6161             std::swap(Lo, Hi);
6162           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6163 
6164         // The final element, if even, goes into the first half of a GPR.
6165         } else if (Flags.isInConsecutiveRegsLast()) {
6166           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6167           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6168           if (!isLittleEndian)
6169             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6170                                  DAG.getConstant(32, dl, MVT::i32));
6171 
6172         // Non-final even elements are skipped; they will be handled
6173         // together the with subsequent argument on the next go-around.
6174         } else
6175           ArgVal = SDValue();
6176 
6177         if (ArgVal.getNode())
6178           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6179       } else {
6180         if (CallConv == CallingConv::Fast)
6181           ComputePtrOff();
6182 
6183         // Single-precision floating-point values are mapped to the
6184         // second (rightmost) word of the stack doubleword.
6185         if (Arg.getValueType() == MVT::f32 &&
6186             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6187           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6188           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6189         }
6190 
6191         assert(HasParameterArea &&
6192                "Parameter area must exist to pass an argument in memory.");
6193         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6194                          true, isTailCall, false, MemOpChains,
6195                          TailCallArguments, dl);
6196 
6197         NeededLoad = true;
6198       }
6199       // When passing an array of floats, the array occupies consecutive
6200       // space in the argument area; only round up to the next doubleword
6201       // at the end of the array.  Otherwise, each float takes 8 bytes.
6202       if (CallConv != CallingConv::Fast || NeededLoad) {
6203         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6204                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6205         if (Flags.isInConsecutiveRegsLast())
6206           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6207       }
6208       break;
6209     }
6210     case MVT::v4f32:
6211     case MVT::v4i32:
6212     case MVT::v8i16:
6213     case MVT::v16i8:
6214     case MVT::v2f64:
6215     case MVT::v2i64:
6216     case MVT::v1i128:
6217     case MVT::f128:
6218       if (!Subtarget.hasQPX()) {
6219       // These can be scalar arguments or elements of a vector array type
6220       // passed directly.  The latter are used to implement ELFv2 homogenous
6221       // vector aggregates.
6222 
6223       // For a varargs call, named arguments go into VRs or on the stack as
6224       // usual; unnamed arguments always go to the stack or the corresponding
6225       // GPRs when within range.  For now, we always put the value in both
6226       // locations (or even all three).
6227       if (isVarArg) {
6228         assert(HasParameterArea &&
6229                "Parameter area must exist if we have a varargs call.");
6230         // We could elide this store in the case where the object fits
6231         // entirely in R registers.  Maybe later.
6232         SDValue Store =
6233             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6234         MemOpChains.push_back(Store);
6235         if (VR_idx != NumVRs) {
6236           SDValue Load =
6237               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6238           MemOpChains.push_back(Load.getValue(1));
6239           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6240         }
6241         ArgOffset += 16;
6242         for (unsigned i=0; i<16; i+=PtrByteSize) {
6243           if (GPR_idx == NumGPRs)
6244             break;
6245           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6246                                    DAG.getConstant(i, dl, PtrVT));
6247           SDValue Load =
6248               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6249           MemOpChains.push_back(Load.getValue(1));
6250           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6251         }
6252         break;
6253       }
6254 
6255       // Non-varargs Altivec params go into VRs or on the stack.
6256       if (VR_idx != NumVRs) {
6257         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6258       } else {
6259         if (CallConv == CallingConv::Fast)
6260           ComputePtrOff();
6261 
6262         assert(HasParameterArea &&
6263                "Parameter area must exist to pass an argument in memory.");
6264         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6265                          true, isTailCall, true, MemOpChains,
6266                          TailCallArguments, dl);
6267         if (CallConv == CallingConv::Fast)
6268           ArgOffset += 16;
6269       }
6270 
6271       if (CallConv != CallingConv::Fast)
6272         ArgOffset += 16;
6273       break;
6274       } // not QPX
6275 
6276       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6277              "Invalid QPX parameter type");
6278 
6279       LLVM_FALLTHROUGH;
6280     case MVT::v4f64:
6281     case MVT::v4i1: {
6282       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6283       if (isVarArg) {
6284         assert(HasParameterArea &&
6285                "Parameter area must exist if we have a varargs call.");
6286         // We could elide this store in the case where the object fits
6287         // entirely in R registers.  Maybe later.
6288         SDValue Store =
6289             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6290         MemOpChains.push_back(Store);
6291         if (QFPR_idx != NumQFPRs) {
6292           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6293                                      PtrOff, MachinePointerInfo());
6294           MemOpChains.push_back(Load.getValue(1));
6295           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6296         }
6297         ArgOffset += (IsF32 ? 16 : 32);
6298         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6299           if (GPR_idx == NumGPRs)
6300             break;
6301           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6302                                    DAG.getConstant(i, dl, PtrVT));
6303           SDValue Load =
6304               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6305           MemOpChains.push_back(Load.getValue(1));
6306           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6307         }
6308         break;
6309       }
6310 
6311       // Non-varargs QPX params go into registers or on the stack.
6312       if (QFPR_idx != NumQFPRs) {
6313         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6314       } else {
6315         if (CallConv == CallingConv::Fast)
6316           ComputePtrOff();
6317 
6318         assert(HasParameterArea &&
6319                "Parameter area must exist to pass an argument in memory.");
6320         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6321                          true, isTailCall, true, MemOpChains,
6322                          TailCallArguments, dl);
6323         if (CallConv == CallingConv::Fast)
6324           ArgOffset += (IsF32 ? 16 : 32);
6325       }
6326 
6327       if (CallConv != CallingConv::Fast)
6328         ArgOffset += (IsF32 ? 16 : 32);
6329       break;
6330       }
6331     }
6332   }
6333 
6334   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6335          "mismatch in size of parameter area");
6336   (void)NumBytesActuallyUsed;
6337 
6338   if (!MemOpChains.empty())
6339     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6340 
6341   // Check if this is an indirect call (MTCTR/BCTRL).
6342   // See prepareDescriptorIndirectCall and buildCallOperands for more
6343   // information about calls through function pointers in the 64-bit SVR4 ABI.
6344   if (!isTailCall && !isPatchPoint &&
6345       !isFunctionGlobalAddress(Callee) &&
6346       !isa<ExternalSymbolSDNode>(Callee)) {
6347     // Load r2 into a virtual register and store it to the TOC save area.
6348     setUsesTOCBasePtr(DAG);
6349     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6350     // TOC save area offset.
6351     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6352     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6353     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6354     Chain = DAG.getStore(
6355         Val.getValue(1), dl, Val, AddPtr,
6356         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6357     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6358     // This does not mean the MTCTR instruction must use R12; it's easier
6359     // to model this as an extra parameter, so do that.
6360     if (isELFv2ABI && !isPatchPoint)
6361       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6362   }
6363 
6364   // Build a sequence of copy-to-reg nodes chained together with token chain
6365   // and flag operands which copy the outgoing args into the appropriate regs.
6366   SDValue InFlag;
6367   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6368     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6369                              RegsToPass[i].second, InFlag);
6370     InFlag = Chain.getValue(1);
6371   }
6372 
6373   if (isTailCall && !IsSibCall)
6374     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6375                     TailCallArguments);
6376 
6377   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6378                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6379                     SPDiff, NumBytes, Ins, InVals, CS);
6380 }
6381 
6382 SDValue PPCTargetLowering::LowerCall_Darwin(
6383     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6384     bool isTailCall, bool isPatchPoint,
6385     const SmallVectorImpl<ISD::OutputArg> &Outs,
6386     const SmallVectorImpl<SDValue> &OutVals,
6387     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6388     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6389     ImmutableCallSite CS) const {
6390   unsigned NumOps = Outs.size();
6391 
6392   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6393   bool isPPC64 = PtrVT == MVT::i64;
6394   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6395 
6396   MachineFunction &MF = DAG.getMachineFunction();
6397 
6398   // Mark this function as potentially containing a function that contains a
6399   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6400   // and restoring the callers stack pointer in this functions epilog. This is
6401   // done because by tail calling the called function might overwrite the value
6402   // in this function's (MF) stack pointer stack slot 0(SP).
6403   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6404       CallConv == CallingConv::Fast)
6405     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6406 
6407   // Count how many bytes are to be pushed on the stack, including the linkage
6408   // area, and parameter passing area.  We start with 24/48 bytes, which is
6409   // prereserved space for [SP][CR][LR][3 x unused].
6410   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6411   unsigned NumBytes = LinkageSize;
6412 
6413   // Add up all the space actually used.
6414   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6415   // they all go in registers, but we must reserve stack space for them for
6416   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6417   // assigned stack space in order, with padding so Altivec parameters are
6418   // 16-byte aligned.
6419   unsigned nAltivecParamsAtEnd = 0;
6420   for (unsigned i = 0; i != NumOps; ++i) {
6421     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6422     EVT ArgVT = Outs[i].VT;
6423     // Varargs Altivec parameters are padded to a 16 byte boundary.
6424     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6425         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6426         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6427       if (!isVarArg && !isPPC64) {
6428         // Non-varargs Altivec parameters go after all the non-Altivec
6429         // parameters; handle those later so we know how much padding we need.
6430         nAltivecParamsAtEnd++;
6431         continue;
6432       }
6433       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6434       NumBytes = ((NumBytes+15)/16)*16;
6435     }
6436     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6437   }
6438 
6439   // Allow for Altivec parameters at the end, if needed.
6440   if (nAltivecParamsAtEnd) {
6441     NumBytes = ((NumBytes+15)/16)*16;
6442     NumBytes += 16*nAltivecParamsAtEnd;
6443   }
6444 
6445   // The prolog code of the callee may store up to 8 GPR argument registers to
6446   // the stack, allowing va_start to index over them in memory if its varargs.
6447   // Because we cannot tell if this is needed on the caller side, we have to
6448   // conservatively assume that it is needed.  As such, make sure we have at
6449   // least enough stack space for the caller to store the 8 GPRs.
6450   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6451 
6452   // Tail call needs the stack to be aligned.
6453   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6454       CallConv == CallingConv::Fast)
6455     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6456 
6457   // Calculate by how many bytes the stack has to be adjusted in case of tail
6458   // call optimization.
6459   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6460 
6461   // To protect arguments on the stack from being clobbered in a tail call,
6462   // force all the loads to happen before doing any other lowering.
6463   if (isTailCall)
6464     Chain = DAG.getStackArgumentTokenFactor(Chain);
6465 
6466   // Adjust the stack pointer for the new arguments...
6467   // These operations are automatically eliminated by the prolog/epilog pass
6468   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6469   SDValue CallSeqStart = Chain;
6470 
6471   // Load the return address and frame pointer so it can be move somewhere else
6472   // later.
6473   SDValue LROp, FPOp;
6474   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6475 
6476   // Set up a copy of the stack pointer for use loading and storing any
6477   // arguments that may not fit in the registers available for argument
6478   // passing.
6479   SDValue StackPtr;
6480   if (isPPC64)
6481     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6482   else
6483     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6484 
6485   // Figure out which arguments are going to go in registers, and which in
6486   // memory.  Also, if this is a vararg function, floating point operations
6487   // must be stored to our stack, and loaded into integer regs as well, if
6488   // any integer regs are available for argument passing.
6489   unsigned ArgOffset = LinkageSize;
6490   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6491 
6492   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6493     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6494     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6495   };
6496   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6497     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6498     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6499   };
6500   static const MCPhysReg VR[] = {
6501     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6502     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6503   };
6504   const unsigned NumGPRs = array_lengthof(GPR_32);
6505   const unsigned NumFPRs = 13;
6506   const unsigned NumVRs  = array_lengthof(VR);
6507 
6508   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6509 
6510   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6511   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6512 
6513   SmallVector<SDValue, 8> MemOpChains;
6514   for (unsigned i = 0; i != NumOps; ++i) {
6515     SDValue Arg = OutVals[i];
6516     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6517 
6518     // PtrOff will be used to store the current argument to the stack if a
6519     // register cannot be found for it.
6520     SDValue PtrOff;
6521 
6522     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6523 
6524     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6525 
6526     // On PPC64, promote integers to 64-bit values.
6527     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6528       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6529       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6530       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6531     }
6532 
6533     // FIXME memcpy is used way more than necessary.  Correctness first.
6534     // Note: "by value" is code for passing a structure by value, not
6535     // basic types.
6536     if (Flags.isByVal()) {
6537       unsigned Size = Flags.getByValSize();
6538       // Very small objects are passed right-justified.  Everything else is
6539       // passed left-justified.
6540       if (Size==1 || Size==2) {
6541         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6542         if (GPR_idx != NumGPRs) {
6543           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6544                                         MachinePointerInfo(), VT);
6545           MemOpChains.push_back(Load.getValue(1));
6546           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6547 
6548           ArgOffset += PtrByteSize;
6549         } else {
6550           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6551                                           PtrOff.getValueType());
6552           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6553           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6554                                                             CallSeqStart,
6555                                                             Flags, DAG, dl);
6556           ArgOffset += PtrByteSize;
6557         }
6558         continue;
6559       }
6560       // Copy entire object into memory.  There are cases where gcc-generated
6561       // code assumes it is there, even if it could be put entirely into
6562       // registers.  (This is not what the doc says.)
6563       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6564                                                         CallSeqStart,
6565                                                         Flags, DAG, dl);
6566 
6567       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6568       // copy the pieces of the object that fit into registers from the
6569       // parameter save area.
6570       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6571         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6572         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6573         if (GPR_idx != NumGPRs) {
6574           SDValue Load =
6575               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6576           MemOpChains.push_back(Load.getValue(1));
6577           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6578           ArgOffset += PtrByteSize;
6579         } else {
6580           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6581           break;
6582         }
6583       }
6584       continue;
6585     }
6586 
6587     switch (Arg.getSimpleValueType().SimpleTy) {
6588     default: llvm_unreachable("Unexpected ValueType for argument!");
6589     case MVT::i1:
6590     case MVT::i32:
6591     case MVT::i64:
6592       if (GPR_idx != NumGPRs) {
6593         if (Arg.getValueType() == MVT::i1)
6594           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6595 
6596         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6597       } else {
6598         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6599                          isPPC64, isTailCall, false, MemOpChains,
6600                          TailCallArguments, dl);
6601       }
6602       ArgOffset += PtrByteSize;
6603       break;
6604     case MVT::f32:
6605     case MVT::f64:
6606       if (FPR_idx != NumFPRs) {
6607         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6608 
6609         if (isVarArg) {
6610           SDValue Store =
6611               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6612           MemOpChains.push_back(Store);
6613 
6614           // Float varargs are always shadowed in available integer registers
6615           if (GPR_idx != NumGPRs) {
6616             SDValue Load =
6617                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6618             MemOpChains.push_back(Load.getValue(1));
6619             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6620           }
6621           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6622             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6623             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6624             SDValue Load =
6625                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6626             MemOpChains.push_back(Load.getValue(1));
6627             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6628           }
6629         } else {
6630           // If we have any FPRs remaining, we may also have GPRs remaining.
6631           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6632           // GPRs.
6633           if (GPR_idx != NumGPRs)
6634             ++GPR_idx;
6635           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6636               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6637             ++GPR_idx;
6638         }
6639       } else
6640         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6641                          isPPC64, isTailCall, false, MemOpChains,
6642                          TailCallArguments, dl);
6643       if (isPPC64)
6644         ArgOffset += 8;
6645       else
6646         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6647       break;
6648     case MVT::v4f32:
6649     case MVT::v4i32:
6650     case MVT::v8i16:
6651     case MVT::v16i8:
6652       if (isVarArg) {
6653         // These go aligned on the stack, or in the corresponding R registers
6654         // when within range.  The Darwin PPC ABI doc claims they also go in
6655         // V registers; in fact gcc does this only for arguments that are
6656         // prototyped, not for those that match the ...  We do it for all
6657         // arguments, seems to work.
6658         while (ArgOffset % 16 !=0) {
6659           ArgOffset += PtrByteSize;
6660           if (GPR_idx != NumGPRs)
6661             GPR_idx++;
6662         }
6663         // We could elide this store in the case where the object fits
6664         // entirely in R registers.  Maybe later.
6665         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6666                              DAG.getConstant(ArgOffset, dl, PtrVT));
6667         SDValue Store =
6668             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6669         MemOpChains.push_back(Store);
6670         if (VR_idx != NumVRs) {
6671           SDValue Load =
6672               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6673           MemOpChains.push_back(Load.getValue(1));
6674           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6675         }
6676         ArgOffset += 16;
6677         for (unsigned i=0; i<16; i+=PtrByteSize) {
6678           if (GPR_idx == NumGPRs)
6679             break;
6680           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6681                                    DAG.getConstant(i, dl, PtrVT));
6682           SDValue Load =
6683               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6684           MemOpChains.push_back(Load.getValue(1));
6685           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6686         }
6687         break;
6688       }
6689 
6690       // Non-varargs Altivec params generally go in registers, but have
6691       // stack space allocated at the end.
6692       if (VR_idx != NumVRs) {
6693         // Doesn't have GPR space allocated.
6694         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6695       } else if (nAltivecParamsAtEnd==0) {
6696         // We are emitting Altivec params in order.
6697         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6698                          isPPC64, isTailCall, true, MemOpChains,
6699                          TailCallArguments, dl);
6700         ArgOffset += 16;
6701       }
6702       break;
6703     }
6704   }
6705   // If all Altivec parameters fit in registers, as they usually do,
6706   // they get stack space following the non-Altivec parameters.  We
6707   // don't track this here because nobody below needs it.
6708   // If there are more Altivec parameters than fit in registers emit
6709   // the stores here.
6710   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6711     unsigned j = 0;
6712     // Offset is aligned; skip 1st 12 params which go in V registers.
6713     ArgOffset = ((ArgOffset+15)/16)*16;
6714     ArgOffset += 12*16;
6715     for (unsigned i = 0; i != NumOps; ++i) {
6716       SDValue Arg = OutVals[i];
6717       EVT ArgType = Outs[i].VT;
6718       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6719           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6720         if (++j > NumVRs) {
6721           SDValue PtrOff;
6722           // We are emitting Altivec params in order.
6723           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6724                            isPPC64, isTailCall, true, MemOpChains,
6725                            TailCallArguments, dl);
6726           ArgOffset += 16;
6727         }
6728       }
6729     }
6730   }
6731 
6732   if (!MemOpChains.empty())
6733     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6734 
6735   // On Darwin, R12 must contain the address of an indirect callee.  This does
6736   // not mean the MTCTR instruction must use R12; it's easier to model this as
6737   // an extra parameter, so do that.
6738   if (!isTailCall &&
6739       !isFunctionGlobalAddress(Callee) &&
6740       !isa<ExternalSymbolSDNode>(Callee) &&
6741       !isBLACompatibleAddress(Callee, DAG))
6742     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6743                                                    PPC::R12), Callee));
6744 
6745   // Build a sequence of copy-to-reg nodes chained together with token chain
6746   // and flag operands which copy the outgoing args into the appropriate regs.
6747   SDValue InFlag;
6748   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6749     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6750                              RegsToPass[i].second, InFlag);
6751     InFlag = Chain.getValue(1);
6752   }
6753 
6754   if (isTailCall)
6755     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6756                     TailCallArguments);
6757 
6758   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6759                     /* unused except on PPC64 ELFv1 */ false, DAG,
6760                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6761                     NumBytes, Ins, InVals, CS);
6762 }
6763 
6764 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6765                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6766                    CCState &State) {
6767 
6768   if (ValVT == MVT::f128)
6769     report_fatal_error("f128 is unimplemented on AIX.");
6770 
6771   if (ArgFlags.isByVal())
6772     report_fatal_error("Passing structure by value is unimplemented.");
6773 
6774   if (ArgFlags.isSRet())
6775     report_fatal_error("Struct return arguments are unimplemented.");
6776 
6777   if (ArgFlags.isNest())
6778     report_fatal_error("Nest arguments are unimplemented.");
6779 
6780   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6781       State.getMachineFunction().getSubtarget());
6782   const bool IsPPC64 = Subtarget.isPPC64();
6783   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6784 
6785   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6786                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6787                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6788   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6789                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6790                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6791 
6792   // Arguments always reserve parameter save area.
6793   switch (ValVT.SimpleTy) {
6794   default:
6795     report_fatal_error("Unhandled value type for argument.");
6796   case MVT::i64:
6797     // i64 arguments should have been split to i32 for PPC32.
6798     assert(IsPPC64 && "PPC32 should have split i64 values.");
6799     LLVM_FALLTHROUGH;
6800   case MVT::i1:
6801   case MVT::i32:
6802     State.AllocateStack(PtrByteSize, PtrByteSize);
6803     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6804       MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6805       // Promote integers if needed.
6806       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6807         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6808                                     : CCValAssign::LocInfo::ZExt;
6809       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6810     }
6811     else
6812       report_fatal_error("Handling of placing parameters on the stack is "
6813                          "unimplemented!");
6814     return false;
6815 
6816   case MVT::f32:
6817   case MVT::f64: {
6818     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6819     const unsigned StoreSize = LocVT.getStoreSize();
6820     // Floats are always 4-byte aligned in the PSA on AIX.
6821     // This includes f64 in 64-bit mode for ABI compatibility.
6822     State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6823     if (unsigned Reg = State.AllocateReg(FPR))
6824       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo));
6825     else
6826       report_fatal_error("Handling of placing parameters on the stack is "
6827                          "unimplemented!");
6828 
6829     // f32 reserves 1 GPR in both PPC32 and PPC64.
6830     // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64.
6831     for (unsigned i = 0; i < StoreSize; i += PtrByteSize)
6832       State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32);
6833     return false;
6834   }
6835   }
6836 }
6837 
6838 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6839                                                     bool IsPPC64) {
6840   assert((IsPPC64 || SVT != MVT::i64) &&
6841          "i64 should have been split for 32-bit codegen.");
6842 
6843   switch (SVT) {
6844   default:
6845     report_fatal_error("Unexpected value type for formal argument");
6846   case MVT::i1:
6847   case MVT::i32:
6848   case MVT::i64:
6849     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6850   case MVT::f32:
6851     return &PPC::F4RCRegClass;
6852   case MVT::f64:
6853     return &PPC::F8RCRegClass;
6854   }
6855 }
6856 
6857 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6858                                         SelectionDAG &DAG, SDValue ArgValue,
6859                                         MVT LocVT, const SDLoc &dl) {
6860   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6861   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6862 
6863   if (Flags.isSExt())
6864     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6865                            DAG.getValueType(ValVT));
6866   else if (Flags.isZExt())
6867     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6868                            DAG.getValueType(ValVT));
6869 
6870   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6871 }
6872 
6873 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6874     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6875     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6876     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6877 
6878   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6879           CallConv == CallingConv::Fast) &&
6880          "Unexpected calling convention!");
6881 
6882   if (isVarArg)
6883     report_fatal_error("This call type is unimplemented on AIX.");
6884 
6885   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6886     report_fatal_error("Tail call support is unimplemented on AIX.");
6887 
6888   if (useSoftFloat())
6889     report_fatal_error("Soft float support is unimplemented on AIX.");
6890 
6891   const PPCSubtarget &Subtarget =
6892       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6893   if (Subtarget.hasQPX())
6894     report_fatal_error("QPX support is not supported on AIX.");
6895 
6896   const bool IsPPC64 = Subtarget.isPPC64();
6897   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6898 
6899   // Assign locations to all of the incoming arguments.
6900   SmallVector<CCValAssign, 16> ArgLocs;
6901   MachineFunction &MF = DAG.getMachineFunction();
6902   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6903 
6904   // Reserve space for the linkage area on the stack.
6905   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6906   // On AIX a minimum of 8 words is saved to the parameter save area.
6907   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6908   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
6909   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6910 
6911   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
6912     CCValAssign &VA = ArgLocs[i];
6913     SDValue ArgValue;
6914     ISD::ArgFlagsTy Flags = Ins[i].Flags;
6915     if (VA.isRegLoc()) {
6916       EVT ValVT = VA.getValVT();
6917       MVT LocVT = VA.getLocVT();
6918       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6919       unsigned VReg =
6920           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6921       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6922       if (ValVT.isScalarInteger() &&
6923           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
6924         ArgValue =
6925             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6926       }
6927       InVals.push_back(ArgValue);
6928     } else {
6929       report_fatal_error("Handling of formal arguments on the stack is "
6930                          "unimplemented!");
6931     }
6932   }
6933 
6934   // Area that is at least reserved in the caller of this function.
6935   unsigned MinReservedArea = CCInfo.getNextStackOffset();
6936 
6937   // Set the size that is at least reserved in caller of this function. Tail
6938   // call optimized function's reserved stack space needs to be aligned so
6939   // that taking the difference between two stack areas will result in an
6940   // aligned stack.
6941   MinReservedArea =
6942       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
6943   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6944   FuncInfo->setMinReservedArea(MinReservedArea);
6945 
6946   return Chain;
6947 }
6948 
6949 SDValue PPCTargetLowering::LowerCall_AIX(
6950     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6951     bool isTailCall, bool isPatchPoint,
6952     const SmallVectorImpl<ISD::OutputArg> &Outs,
6953     const SmallVectorImpl<SDValue> &OutVals,
6954     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6955     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6956     ImmutableCallSite CS) const {
6957 
6958   assert((CallConv == CallingConv::C ||
6959           CallConv == CallingConv::Cold ||
6960           CallConv == CallingConv::Fast) && "Unexpected calling convention!");
6961 
6962   if (isVarArg || isPatchPoint)
6963     report_fatal_error("This call type is unimplemented on AIX.");
6964 
6965   if (!isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
6966     report_fatal_error("Handling of indirect call is unimplemented!");
6967 
6968   const PPCSubtarget& Subtarget =
6969       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
6970   if (Subtarget.hasQPX())
6971     report_fatal_error("QPX is not supported on AIX.");
6972   if (Subtarget.hasAltivec())
6973     report_fatal_error("Altivec support is unimplemented on AIX.");
6974 
6975   MachineFunction &MF = DAG.getMachineFunction();
6976   SmallVector<CCValAssign, 16> ArgLocs;
6977   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6978 
6979   // Reserve space for the linkage save area (LSA) on the stack.
6980   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
6981   //   [SP][CR][LR][2 x reserved][TOC].
6982   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
6983   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6984   const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4;
6985   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
6986   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
6987 
6988   // The prolog code of the callee may store up to 8 GPR argument registers to
6989   // the stack, allowing va_start to index over them in memory if the callee
6990   // is variadic.
6991   // Because we cannot tell if this is needed on the caller side, we have to
6992   // conservatively assume that it is needed.  As such, make sure we have at
6993   // least enough stack space for the caller to store the 8 GPRs.
6994   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
6995   const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize;
6996 
6997   // Adjust the stack pointer for the new arguments...
6998   // These operations are automatically eliminated by the prolog/epilog pass.
6999   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7000   SDValue CallSeqStart = Chain;
7001 
7002   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7003 
7004   for (CCValAssign &VA : ArgLocs) {
7005     SDValue Arg = OutVals[VA.getValNo()];
7006 
7007     switch (VA.getLocInfo()) {
7008     default: report_fatal_error("Unexpected argument extension type.");
7009     case CCValAssign::Full: break;
7010     case CCValAssign::ZExt:
7011       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7012       break;
7013     case CCValAssign::SExt:
7014       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7015       break;
7016     }
7017 
7018     if (VA.isRegLoc())
7019       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7020 
7021     if (VA.isMemLoc())
7022       report_fatal_error("Handling of placing parameters on the stack is "
7023                          "unimplemented!");
7024   }
7025 
7026   // Build a sequence of copy-to-reg nodes chained together with token chain
7027   // and flag operands which copy the outgoing args into the appropriate regs.
7028   SDValue InFlag;
7029   for (auto Reg : RegsToPass) {
7030     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7031     InFlag = Chain.getValue(1);
7032   }
7033 
7034   const int SPDiff = 0;
7035   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
7036                     /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass,
7037                     InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins,
7038                     InVals, CS);
7039 }
7040 
7041 bool
7042 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7043                                   MachineFunction &MF, bool isVarArg,
7044                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7045                                   LLVMContext &Context) const {
7046   SmallVector<CCValAssign, 16> RVLocs;
7047   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7048   return CCInfo.CheckReturn(
7049       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7050                 ? RetCC_PPC_Cold
7051                 : RetCC_PPC);
7052 }
7053 
7054 SDValue
7055 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7056                                bool isVarArg,
7057                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7058                                const SmallVectorImpl<SDValue> &OutVals,
7059                                const SDLoc &dl, SelectionDAG &DAG) const {
7060   SmallVector<CCValAssign, 16> RVLocs;
7061   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7062                  *DAG.getContext());
7063   CCInfo.AnalyzeReturn(Outs,
7064                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7065                            ? RetCC_PPC_Cold
7066                            : RetCC_PPC);
7067 
7068   SDValue Flag;
7069   SmallVector<SDValue, 4> RetOps(1, Chain);
7070 
7071   // Copy the result values into the output registers.
7072   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7073     CCValAssign &VA = RVLocs[i];
7074     assert(VA.isRegLoc() && "Can only return in registers!");
7075 
7076     SDValue Arg = OutVals[RealResIdx];
7077 
7078     switch (VA.getLocInfo()) {
7079     default: llvm_unreachable("Unknown loc info!");
7080     case CCValAssign::Full: break;
7081     case CCValAssign::AExt:
7082       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7083       break;
7084     case CCValAssign::ZExt:
7085       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7086       break;
7087     case CCValAssign::SExt:
7088       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7089       break;
7090     }
7091     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7092       bool isLittleEndian = Subtarget.isLittleEndian();
7093       // Legalize ret f64 -> ret 2 x i32.
7094       SDValue SVal =
7095           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7096                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7097       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7098       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7099       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7100                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7101       Flag = Chain.getValue(1);
7102       VA = RVLocs[++i]; // skip ahead to next loc
7103       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7104     } else
7105       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7106     Flag = Chain.getValue(1);
7107     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7108   }
7109 
7110   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7111   const MCPhysReg *I =
7112     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7113   if (I) {
7114     for (; *I; ++I) {
7115 
7116       if (PPC::G8RCRegClass.contains(*I))
7117         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7118       else if (PPC::F8RCRegClass.contains(*I))
7119         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7120       else if (PPC::CRRCRegClass.contains(*I))
7121         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7122       else if (PPC::VRRCRegClass.contains(*I))
7123         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7124       else
7125         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7126     }
7127   }
7128 
7129   RetOps[0] = Chain;  // Update chain.
7130 
7131   // Add the flag if we have it.
7132   if (Flag.getNode())
7133     RetOps.push_back(Flag);
7134 
7135   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7136 }
7137 
7138 SDValue
7139 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7140                                                 SelectionDAG &DAG) const {
7141   SDLoc dl(Op);
7142 
7143   // Get the correct type for integers.
7144   EVT IntVT = Op.getValueType();
7145 
7146   // Get the inputs.
7147   SDValue Chain = Op.getOperand(0);
7148   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7149   // Build a DYNAREAOFFSET node.
7150   SDValue Ops[2] = {Chain, FPSIdx};
7151   SDVTList VTs = DAG.getVTList(IntVT);
7152   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7153 }
7154 
7155 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7156                                              SelectionDAG &DAG) const {
7157   // When we pop the dynamic allocation we need to restore the SP link.
7158   SDLoc dl(Op);
7159 
7160   // Get the correct type for pointers.
7161   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7162 
7163   // Construct the stack pointer operand.
7164   bool isPPC64 = Subtarget.isPPC64();
7165   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7166   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7167 
7168   // Get the operands for the STACKRESTORE.
7169   SDValue Chain = Op.getOperand(0);
7170   SDValue SaveSP = Op.getOperand(1);
7171 
7172   // Load the old link SP.
7173   SDValue LoadLinkSP =
7174       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7175 
7176   // Restore the stack pointer.
7177   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7178 
7179   // Store the old link SP.
7180   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7181 }
7182 
7183 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7184   MachineFunction &MF = DAG.getMachineFunction();
7185   bool isPPC64 = Subtarget.isPPC64();
7186   EVT PtrVT = getPointerTy(MF.getDataLayout());
7187 
7188   // Get current frame pointer save index.  The users of this index will be
7189   // primarily DYNALLOC instructions.
7190   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7191   int RASI = FI->getReturnAddrSaveIndex();
7192 
7193   // If the frame pointer save index hasn't been defined yet.
7194   if (!RASI) {
7195     // Find out what the fix offset of the frame pointer save area.
7196     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7197     // Allocate the frame index for frame pointer save area.
7198     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7199     // Save the result.
7200     FI->setReturnAddrSaveIndex(RASI);
7201   }
7202   return DAG.getFrameIndex(RASI, PtrVT);
7203 }
7204 
7205 SDValue
7206 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7207   MachineFunction &MF = DAG.getMachineFunction();
7208   bool isPPC64 = Subtarget.isPPC64();
7209   EVT PtrVT = getPointerTy(MF.getDataLayout());
7210 
7211   // Get current frame pointer save index.  The users of this index will be
7212   // primarily DYNALLOC instructions.
7213   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7214   int FPSI = FI->getFramePointerSaveIndex();
7215 
7216   // If the frame pointer save index hasn't been defined yet.
7217   if (!FPSI) {
7218     // Find out what the fix offset of the frame pointer save area.
7219     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7220     // Allocate the frame index for frame pointer save area.
7221     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7222     // Save the result.
7223     FI->setFramePointerSaveIndex(FPSI);
7224   }
7225   return DAG.getFrameIndex(FPSI, PtrVT);
7226 }
7227 
7228 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7229                                                    SelectionDAG &DAG) const {
7230   // Get the inputs.
7231   SDValue Chain = Op.getOperand(0);
7232   SDValue Size  = Op.getOperand(1);
7233   SDLoc dl(Op);
7234 
7235   // Get the correct type for pointers.
7236   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7237   // Negate the size.
7238   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7239                                 DAG.getConstant(0, dl, PtrVT), Size);
7240   // Construct a node for the frame pointer save index.
7241   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7242   // Build a DYNALLOC node.
7243   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7244   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7245   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7246 }
7247 
7248 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7249                                                      SelectionDAG &DAG) const {
7250   MachineFunction &MF = DAG.getMachineFunction();
7251 
7252   bool isPPC64 = Subtarget.isPPC64();
7253   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7254 
7255   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7256   return DAG.getFrameIndex(FI, PtrVT);
7257 }
7258 
7259 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7260                                                SelectionDAG &DAG) const {
7261   SDLoc DL(Op);
7262   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7263                      DAG.getVTList(MVT::i32, MVT::Other),
7264                      Op.getOperand(0), Op.getOperand(1));
7265 }
7266 
7267 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7268                                                 SelectionDAG &DAG) const {
7269   SDLoc DL(Op);
7270   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7271                      Op.getOperand(0), Op.getOperand(1));
7272 }
7273 
7274 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7275   if (Op.getValueType().isVector())
7276     return LowerVectorLoad(Op, DAG);
7277 
7278   assert(Op.getValueType() == MVT::i1 &&
7279          "Custom lowering only for i1 loads");
7280 
7281   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7282 
7283   SDLoc dl(Op);
7284   LoadSDNode *LD = cast<LoadSDNode>(Op);
7285 
7286   SDValue Chain = LD->getChain();
7287   SDValue BasePtr = LD->getBasePtr();
7288   MachineMemOperand *MMO = LD->getMemOperand();
7289 
7290   SDValue NewLD =
7291       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7292                      BasePtr, MVT::i8, MMO);
7293   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7294 
7295   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7296   return DAG.getMergeValues(Ops, dl);
7297 }
7298 
7299 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7300   if (Op.getOperand(1).getValueType().isVector())
7301     return LowerVectorStore(Op, DAG);
7302 
7303   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7304          "Custom lowering only for i1 stores");
7305 
7306   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7307 
7308   SDLoc dl(Op);
7309   StoreSDNode *ST = cast<StoreSDNode>(Op);
7310 
7311   SDValue Chain = ST->getChain();
7312   SDValue BasePtr = ST->getBasePtr();
7313   SDValue Value = ST->getValue();
7314   MachineMemOperand *MMO = ST->getMemOperand();
7315 
7316   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7317                       Value);
7318   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7319 }
7320 
7321 // FIXME: Remove this once the ANDI glue bug is fixed:
7322 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7323   assert(Op.getValueType() == MVT::i1 &&
7324          "Custom lowering only for i1 results");
7325 
7326   SDLoc DL(Op);
7327   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7328                      Op.getOperand(0));
7329 }
7330 
7331 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7332                                                SelectionDAG &DAG) const {
7333 
7334   // Implements a vector truncate that fits in a vector register as a shuffle.
7335   // We want to legalize vector truncates down to where the source fits in
7336   // a vector register (and target is therefore smaller than vector register
7337   // size).  At that point legalization will try to custom lower the sub-legal
7338   // result and get here - where we can contain the truncate as a single target
7339   // operation.
7340 
7341   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7342   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7343   //
7344   // We will implement it for big-endian ordering as this (where x denotes
7345   // undefined):
7346   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7347   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7348   //
7349   // The same operation in little-endian ordering will be:
7350   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7351   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7352 
7353   assert(Op.getValueType().isVector() && "Vector type expected.");
7354 
7355   SDLoc DL(Op);
7356   SDValue N1 = Op.getOperand(0);
7357   unsigned SrcSize = N1.getValueType().getSizeInBits();
7358   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7359   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7360 
7361   EVT TrgVT = Op.getValueType();
7362   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7363   EVT EltVT = TrgVT.getVectorElementType();
7364   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7365   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7366 
7367   // First list the elements we want to keep.
7368   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7369   SmallVector<int, 16> ShuffV;
7370   if (Subtarget.isLittleEndian())
7371     for (unsigned i = 0; i < TrgNumElts; ++i)
7372       ShuffV.push_back(i * SizeMult);
7373   else
7374     for (unsigned i = 1; i <= TrgNumElts; ++i)
7375       ShuffV.push_back(i * SizeMult - 1);
7376 
7377   // Populate the remaining elements with undefs.
7378   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7379     // ShuffV.push_back(i + WideNumElts);
7380     ShuffV.push_back(WideNumElts + 1);
7381 
7382   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7383   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7384 }
7385 
7386 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7387 /// possible.
7388 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7389   // Not FP? Not a fsel.
7390   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7391       !Op.getOperand(2).getValueType().isFloatingPoint())
7392     return Op;
7393 
7394   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7395   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7396   // We might be able to do better than this under some circumstances, but in
7397   // general, fsel-based lowering of select is a finite-math-only optimization.
7398   // For more information, see section F.3 of the 2.06 ISA specification.
7399   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7400   // presence of infinities.
7401   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7402     return Op;
7403   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7404 
7405   EVT ResVT = Op.getValueType();
7406   EVT CmpVT = Op.getOperand(0).getValueType();
7407   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7408   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7409   SDLoc dl(Op);
7410 
7411   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7412     switch (CC) {
7413     default:
7414       // Not a min/max but with finite math, we may still be able to use fsel.
7415       if (HasNoInfs && HasNoNaNs)
7416         break;
7417       return Op;
7418     case ISD::SETOGT:
7419     case ISD::SETGT:
7420       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7421     case ISD::SETOLT:
7422     case ISD::SETLT:
7423       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7424     }
7425   }
7426 
7427   // TODO: Propagate flags from the select rather than global settings.
7428   SDNodeFlags Flags;
7429   Flags.setNoInfs(true);
7430   Flags.setNoNaNs(true);
7431 
7432   // If the RHS of the comparison is a 0.0, we don't need to do the
7433   // subtraction at all.
7434   SDValue Sel1;
7435   if (isFloatingPointZero(RHS))
7436     switch (CC) {
7437     default: break;       // SETUO etc aren't handled by fsel.
7438     case ISD::SETNE:
7439       std::swap(TV, FV);
7440       LLVM_FALLTHROUGH;
7441     case ISD::SETEQ:
7442       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7443         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7444       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7445       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7446         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7447       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7448                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7449     case ISD::SETULT:
7450     case ISD::SETLT:
7451       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7452       LLVM_FALLTHROUGH;
7453     case ISD::SETOGE:
7454     case ISD::SETGE:
7455       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7456         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7457       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7458     case ISD::SETUGT:
7459     case ISD::SETGT:
7460       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7461       LLVM_FALLTHROUGH;
7462     case ISD::SETOLE:
7463     case ISD::SETLE:
7464       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7465         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7466       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7467                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7468     }
7469 
7470   SDValue Cmp;
7471   switch (CC) {
7472   default: break;       // SETUO etc aren't handled by fsel.
7473   case ISD::SETNE:
7474     std::swap(TV, FV);
7475     LLVM_FALLTHROUGH;
7476   case ISD::SETEQ:
7477     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7478     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7479       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7480     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7481     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7482       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7483     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7484                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7485   case ISD::SETULT:
7486   case ISD::SETLT:
7487     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7488     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7489       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7490     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7491   case ISD::SETOGE:
7492   case ISD::SETGE:
7493     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7494     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7495       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7496     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7497   case ISD::SETUGT:
7498   case ISD::SETGT:
7499     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7500     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7501       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7502     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7503   case ISD::SETOLE:
7504   case ISD::SETLE:
7505     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7506     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7507       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7508     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7509   }
7510   return Op;
7511 }
7512 
7513 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7514                                                SelectionDAG &DAG,
7515                                                const SDLoc &dl) const {
7516   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7517   SDValue Src = Op.getOperand(0);
7518   if (Src.getValueType() == MVT::f32)
7519     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7520 
7521   SDValue Tmp;
7522   switch (Op.getSimpleValueType().SimpleTy) {
7523   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7524   case MVT::i32:
7525     Tmp = DAG.getNode(
7526         Op.getOpcode() == ISD::FP_TO_SINT
7527             ? PPCISD::FCTIWZ
7528             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7529         dl, MVT::f64, Src);
7530     break;
7531   case MVT::i64:
7532     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7533            "i64 FP_TO_UINT is supported only with FPCVT");
7534     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7535                                                         PPCISD::FCTIDUZ,
7536                       dl, MVT::f64, Src);
7537     break;
7538   }
7539 
7540   // Convert the FP value to an int value through memory.
7541   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7542     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7543   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7544   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7545   MachinePointerInfo MPI =
7546       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7547 
7548   // Emit a store to the stack slot.
7549   SDValue Chain;
7550   if (i32Stack) {
7551     MachineFunction &MF = DAG.getMachineFunction();
7552     MachineMemOperand *MMO =
7553       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7554     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7555     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7556               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7557   } else
7558     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7559 
7560   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7561   // add in a bias on big endian.
7562   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7563     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7564                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7565     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7566   }
7567 
7568   RLI.Chain = Chain;
7569   RLI.Ptr = FIPtr;
7570   RLI.MPI = MPI;
7571 }
7572 
7573 /// Custom lowers floating point to integer conversions to use
7574 /// the direct move instructions available in ISA 2.07 to avoid the
7575 /// need for load/store combinations.
7576 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7577                                                     SelectionDAG &DAG,
7578                                                     const SDLoc &dl) const {
7579   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7580   SDValue Src = Op.getOperand(0);
7581 
7582   if (Src.getValueType() == MVT::f32)
7583     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7584 
7585   SDValue Tmp;
7586   switch (Op.getSimpleValueType().SimpleTy) {
7587   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7588   case MVT::i32:
7589     Tmp = DAG.getNode(
7590         Op.getOpcode() == ISD::FP_TO_SINT
7591             ? PPCISD::FCTIWZ
7592             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7593         dl, MVT::f64, Src);
7594     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7595     break;
7596   case MVT::i64:
7597     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7598            "i64 FP_TO_UINT is supported only with FPCVT");
7599     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7600                                                         PPCISD::FCTIDUZ,
7601                       dl, MVT::f64, Src);
7602     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7603     break;
7604   }
7605   return Tmp;
7606 }
7607 
7608 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7609                                           const SDLoc &dl) const {
7610 
7611   // FP to INT conversions are legal for f128.
7612   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7613     return Op;
7614 
7615   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7616   // PPC (the libcall is not available).
7617   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7618     if (Op.getValueType() == MVT::i32) {
7619       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7620         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7621                                  MVT::f64, Op.getOperand(0),
7622                                  DAG.getIntPtrConstant(0, dl));
7623         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7624                                  MVT::f64, Op.getOperand(0),
7625                                  DAG.getIntPtrConstant(1, dl));
7626 
7627         // Add the two halves of the long double in round-to-zero mode.
7628         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7629 
7630         // Now use a smaller FP_TO_SINT.
7631         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7632       }
7633       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7634         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7635         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7636         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7637         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7638         // FIXME: generated code sucks.
7639         // TODO: Are there fast-math-flags to propagate to this FSUB?
7640         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7641                                    Op.getOperand(0), Tmp);
7642         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7643         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7644                            DAG.getConstant(0x80000000, dl, MVT::i32));
7645         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7646                                     Op.getOperand(0));
7647         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7648                                ISD::SETGE);
7649       }
7650     }
7651 
7652     return SDValue();
7653   }
7654 
7655   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7656     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7657 
7658   ReuseLoadInfo RLI;
7659   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7660 
7661   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7662                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7663 }
7664 
7665 // We're trying to insert a regular store, S, and then a load, L. If the
7666 // incoming value, O, is a load, we might just be able to have our load use the
7667 // address used by O. However, we don't know if anything else will store to
7668 // that address before we can load from it. To prevent this situation, we need
7669 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7670 // the same chain operand as O, we create a token factor from the chain results
7671 // of O and L, and we replace all uses of O's chain result with that token
7672 // factor (see spliceIntoChain below for this last part).
7673 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7674                                             ReuseLoadInfo &RLI,
7675                                             SelectionDAG &DAG,
7676                                             ISD::LoadExtType ET) const {
7677   SDLoc dl(Op);
7678   if (ET == ISD::NON_EXTLOAD &&
7679       (Op.getOpcode() == ISD::FP_TO_UINT ||
7680        Op.getOpcode() == ISD::FP_TO_SINT) &&
7681       isOperationLegalOrCustom(Op.getOpcode(),
7682                                Op.getOperand(0).getValueType())) {
7683 
7684     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7685     return true;
7686   }
7687 
7688   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7689   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7690       LD->isNonTemporal())
7691     return false;
7692   if (LD->getMemoryVT() != MemVT)
7693     return false;
7694 
7695   RLI.Ptr = LD->getBasePtr();
7696   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7697     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7698            "Non-pre-inc AM on PPC?");
7699     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7700                           LD->getOffset());
7701   }
7702 
7703   RLI.Chain = LD->getChain();
7704   RLI.MPI = LD->getPointerInfo();
7705   RLI.IsDereferenceable = LD->isDereferenceable();
7706   RLI.IsInvariant = LD->isInvariant();
7707   RLI.Alignment = LD->getAlignment();
7708   RLI.AAInfo = LD->getAAInfo();
7709   RLI.Ranges = LD->getRanges();
7710 
7711   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7712   return true;
7713 }
7714 
7715 // Given the head of the old chain, ResChain, insert a token factor containing
7716 // it and NewResChain, and make users of ResChain now be users of that token
7717 // factor.
7718 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7719 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7720                                         SDValue NewResChain,
7721                                         SelectionDAG &DAG) const {
7722   if (!ResChain)
7723     return;
7724 
7725   SDLoc dl(NewResChain);
7726 
7727   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7728                            NewResChain, DAG.getUNDEF(MVT::Other));
7729   assert(TF.getNode() != NewResChain.getNode() &&
7730          "A new TF really is required here");
7731 
7732   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7733   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7734 }
7735 
7736 /// Analyze profitability of direct move
7737 /// prefer float load to int load plus direct move
7738 /// when there is no integer use of int load
7739 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7740   SDNode *Origin = Op.getOperand(0).getNode();
7741   if (Origin->getOpcode() != ISD::LOAD)
7742     return true;
7743 
7744   // If there is no LXSIBZX/LXSIHZX, like Power8,
7745   // prefer direct move if the memory size is 1 or 2 bytes.
7746   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7747   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7748     return true;
7749 
7750   for (SDNode::use_iterator UI = Origin->use_begin(),
7751                             UE = Origin->use_end();
7752        UI != UE; ++UI) {
7753 
7754     // Only look at the users of the loaded value.
7755     if (UI.getUse().get().getResNo() != 0)
7756       continue;
7757 
7758     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7759         UI->getOpcode() != ISD::UINT_TO_FP)
7760       return true;
7761   }
7762 
7763   return false;
7764 }
7765 
7766 /// Custom lowers integer to floating point conversions to use
7767 /// the direct move instructions available in ISA 2.07 to avoid the
7768 /// need for load/store combinations.
7769 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7770                                                     SelectionDAG &DAG,
7771                                                     const SDLoc &dl) const {
7772   assert((Op.getValueType() == MVT::f32 ||
7773           Op.getValueType() == MVT::f64) &&
7774          "Invalid floating point type as target of conversion");
7775   assert(Subtarget.hasFPCVT() &&
7776          "Int to FP conversions with direct moves require FPCVT");
7777   SDValue FP;
7778   SDValue Src = Op.getOperand(0);
7779   bool SinglePrec = Op.getValueType() == MVT::f32;
7780   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7781   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7782   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7783                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7784 
7785   if (WordInt) {
7786     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7787                      dl, MVT::f64, Src);
7788     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7789   }
7790   else {
7791     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7792     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7793   }
7794 
7795   return FP;
7796 }
7797 
7798 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7799 
7800   EVT VecVT = Vec.getValueType();
7801   assert(VecVT.isVector() && "Expected a vector type.");
7802   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7803 
7804   EVT EltVT = VecVT.getVectorElementType();
7805   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7806   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7807 
7808   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7809   SmallVector<SDValue, 16> Ops(NumConcat);
7810   Ops[0] = Vec;
7811   SDValue UndefVec = DAG.getUNDEF(VecVT);
7812   for (unsigned i = 1; i < NumConcat; ++i)
7813     Ops[i] = UndefVec;
7814 
7815   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7816 }
7817 
7818 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7819                                                 const SDLoc &dl) const {
7820 
7821   unsigned Opc = Op.getOpcode();
7822   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7823          "Unexpected conversion type");
7824   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7825          "Supports conversions to v2f64/v4f32 only.");
7826 
7827   bool SignedConv = Opc == ISD::SINT_TO_FP;
7828   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7829 
7830   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7831   EVT WideVT = Wide.getValueType();
7832   unsigned WideNumElts = WideVT.getVectorNumElements();
7833   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7834 
7835   SmallVector<int, 16> ShuffV;
7836   for (unsigned i = 0; i < WideNumElts; ++i)
7837     ShuffV.push_back(i + WideNumElts);
7838 
7839   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7840   int SaveElts = FourEltRes ? 4 : 2;
7841   if (Subtarget.isLittleEndian())
7842     for (int i = 0; i < SaveElts; i++)
7843       ShuffV[i * Stride] = i;
7844   else
7845     for (int i = 1; i <= SaveElts; i++)
7846       ShuffV[i * Stride - 1] = i - 1;
7847 
7848   SDValue ShuffleSrc2 =
7849       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7850   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7851   unsigned ExtendOp =
7852       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7853 
7854   SDValue Extend;
7855   if (!Subtarget.hasP9Altivec() && SignedConv) {
7856     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7857     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7858                          DAG.getValueType(Op.getOperand(0).getValueType()));
7859   } else
7860     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7861 
7862   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7863 }
7864 
7865 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7866                                           SelectionDAG &DAG) const {
7867   SDLoc dl(Op);
7868 
7869   EVT InVT = Op.getOperand(0).getValueType();
7870   EVT OutVT = Op.getValueType();
7871   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7872       isOperationCustom(Op.getOpcode(), InVT))
7873     return LowerINT_TO_FPVector(Op, DAG, dl);
7874 
7875   // Conversions to f128 are legal.
7876   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7877     return Op;
7878 
7879   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7880     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7881       return SDValue();
7882 
7883     SDValue Value = Op.getOperand(0);
7884     // The values are now known to be -1 (false) or 1 (true). To convert this
7885     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7886     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7887     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7888 
7889     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7890 
7891     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7892 
7893     if (Op.getValueType() != MVT::v4f64)
7894       Value = DAG.getNode(ISD::FP_ROUND, dl,
7895                           Op.getValueType(), Value,
7896                           DAG.getIntPtrConstant(1, dl));
7897     return Value;
7898   }
7899 
7900   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7901   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7902     return SDValue();
7903 
7904   if (Op.getOperand(0).getValueType() == MVT::i1)
7905     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7906                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7907                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7908 
7909   // If we have direct moves, we can do all the conversion, skip the store/load
7910   // however, without FPCVT we can't do most conversions.
7911   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7912       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7913     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7914 
7915   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7916          "UINT_TO_FP is supported only with FPCVT");
7917 
7918   // If we have FCFIDS, then use it when converting to single-precision.
7919   // Otherwise, convert to double-precision and then round.
7920   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7921                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7922                                                             : PPCISD::FCFIDS)
7923                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7924                                                             : PPCISD::FCFID);
7925   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7926                   ? MVT::f32
7927                   : MVT::f64;
7928 
7929   if (Op.getOperand(0).getValueType() == MVT::i64) {
7930     SDValue SINT = Op.getOperand(0);
7931     // When converting to single-precision, we actually need to convert
7932     // to double-precision first and then round to single-precision.
7933     // To avoid double-rounding effects during that operation, we have
7934     // to prepare the input operand.  Bits that might be truncated when
7935     // converting to double-precision are replaced by a bit that won't
7936     // be lost at this stage, but is below the single-precision rounding
7937     // position.
7938     //
7939     // However, if -enable-unsafe-fp-math is in effect, accept double
7940     // rounding to avoid the extra overhead.
7941     if (Op.getValueType() == MVT::f32 &&
7942         !Subtarget.hasFPCVT() &&
7943         !DAG.getTarget().Options.UnsafeFPMath) {
7944 
7945       // Twiddle input to make sure the low 11 bits are zero.  (If this
7946       // is the case, we are guaranteed the value will fit into the 53 bit
7947       // mantissa of an IEEE double-precision value without rounding.)
7948       // If any of those low 11 bits were not zero originally, make sure
7949       // bit 12 (value 2048) is set instead, so that the final rounding
7950       // to single-precision gets the correct result.
7951       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7952                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7953       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7954                           Round, DAG.getConstant(2047, dl, MVT::i64));
7955       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7956       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7957                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7958 
7959       // However, we cannot use that value unconditionally: if the magnitude
7960       // of the input value is small, the bit-twiddling we did above might
7961       // end up visibly changing the output.  Fortunately, in that case, we
7962       // don't need to twiddle bits since the original input will convert
7963       // exactly to double-precision floating-point already.  Therefore,
7964       // construct a conditional to use the original value if the top 11
7965       // bits are all sign-bit copies, and use the rounded value computed
7966       // above otherwise.
7967       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7968                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7969       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7970                          Cond, DAG.getConstant(1, dl, MVT::i64));
7971       Cond = DAG.getSetCC(dl, MVT::i32,
7972                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7973 
7974       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7975     }
7976 
7977     ReuseLoadInfo RLI;
7978     SDValue Bits;
7979 
7980     MachineFunction &MF = DAG.getMachineFunction();
7981     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7982       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7983                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7984       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7985     } else if (Subtarget.hasLFIWAX() &&
7986                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7987       MachineMemOperand *MMO =
7988         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7989                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7990       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7991       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7992                                      DAG.getVTList(MVT::f64, MVT::Other),
7993                                      Ops, MVT::i32, MMO);
7994       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7995     } else if (Subtarget.hasFPCVT() &&
7996                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7997       MachineMemOperand *MMO =
7998         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7999                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8000       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8001       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8002                                      DAG.getVTList(MVT::f64, MVT::Other),
8003                                      Ops, MVT::i32, MMO);
8004       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8005     } else if (((Subtarget.hasLFIWAX() &&
8006                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8007                 (Subtarget.hasFPCVT() &&
8008                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8009                SINT.getOperand(0).getValueType() == MVT::i32) {
8010       MachineFrameInfo &MFI = MF.getFrameInfo();
8011       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8012 
8013       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8014       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8015 
8016       SDValue Store =
8017           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8018                        MachinePointerInfo::getFixedStack(
8019                            DAG.getMachineFunction(), FrameIdx));
8020 
8021       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8022              "Expected an i32 store");
8023 
8024       RLI.Ptr = FIdx;
8025       RLI.Chain = Store;
8026       RLI.MPI =
8027           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8028       RLI.Alignment = 4;
8029 
8030       MachineMemOperand *MMO =
8031         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8032                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8033       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8034       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8035                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8036                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8037                                      Ops, MVT::i32, MMO);
8038     } else
8039       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8040 
8041     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8042 
8043     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8044       FP = DAG.getNode(ISD::FP_ROUND, dl,
8045                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8046     return FP;
8047   }
8048 
8049   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8050          "Unhandled INT_TO_FP type in custom expander!");
8051   // Since we only generate this in 64-bit mode, we can take advantage of
8052   // 64-bit registers.  In particular, sign extend the input value into the
8053   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8054   // then lfd it and fcfid it.
8055   MachineFunction &MF = DAG.getMachineFunction();
8056   MachineFrameInfo &MFI = MF.getFrameInfo();
8057   EVT PtrVT = getPointerTy(MF.getDataLayout());
8058 
8059   SDValue Ld;
8060   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8061     ReuseLoadInfo RLI;
8062     bool ReusingLoad;
8063     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8064                                             DAG))) {
8065       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8066       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8067 
8068       SDValue Store =
8069           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8070                        MachinePointerInfo::getFixedStack(
8071                            DAG.getMachineFunction(), FrameIdx));
8072 
8073       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8074              "Expected an i32 store");
8075 
8076       RLI.Ptr = FIdx;
8077       RLI.Chain = Store;
8078       RLI.MPI =
8079           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8080       RLI.Alignment = 4;
8081     }
8082 
8083     MachineMemOperand *MMO =
8084       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8085                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8086     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8087     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8088                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8089                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8090                                  Ops, MVT::i32, MMO);
8091     if (ReusingLoad)
8092       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8093   } else {
8094     assert(Subtarget.isPPC64() &&
8095            "i32->FP without LFIWAX supported only on PPC64");
8096 
8097     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8098     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8099 
8100     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8101                                 Op.getOperand(0));
8102 
8103     // STD the extended value into the stack slot.
8104     SDValue Store = DAG.getStore(
8105         DAG.getEntryNode(), dl, Ext64, FIdx,
8106         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8107 
8108     // Load the value as a double.
8109     Ld = DAG.getLoad(
8110         MVT::f64, dl, Store, FIdx,
8111         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8112   }
8113 
8114   // FCFID it and return it.
8115   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8116   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8117     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8118                      DAG.getIntPtrConstant(0, dl));
8119   return FP;
8120 }
8121 
8122 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8123                                             SelectionDAG &DAG) const {
8124   SDLoc dl(Op);
8125   /*
8126    The rounding mode is in bits 30:31 of FPSR, and has the following
8127    settings:
8128      00 Round to nearest
8129      01 Round to 0
8130      10 Round to +inf
8131      11 Round to -inf
8132 
8133   FLT_ROUNDS, on the other hand, expects the following:
8134     -1 Undefined
8135      0 Round to 0
8136      1 Round to nearest
8137      2 Round to +inf
8138      3 Round to -inf
8139 
8140   To perform the conversion, we do:
8141     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8142   */
8143 
8144   MachineFunction &MF = DAG.getMachineFunction();
8145   EVT VT = Op.getValueType();
8146   EVT PtrVT = getPointerTy(MF.getDataLayout());
8147 
8148   // Save FP Control Word to register
8149   EVT NodeTys[] = {
8150     MVT::f64,    // return register
8151     MVT::Glue    // unused in this context
8152   };
8153   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
8154 
8155   // Save FP register to stack slot
8156   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8157   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8158   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
8159                                MachinePointerInfo());
8160 
8161   // Load FP Control Word from low 32 bits of stack slot.
8162   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8163   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8164   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
8165 
8166   // Transform as necessary
8167   SDValue CWD1 =
8168     DAG.getNode(ISD::AND, dl, MVT::i32,
8169                 CWD, DAG.getConstant(3, dl, MVT::i32));
8170   SDValue CWD2 =
8171     DAG.getNode(ISD::SRL, dl, MVT::i32,
8172                 DAG.getNode(ISD::AND, dl, MVT::i32,
8173                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8174                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8175                             DAG.getConstant(3, dl, MVT::i32)),
8176                 DAG.getConstant(1, dl, MVT::i32));
8177 
8178   SDValue RetVal =
8179     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8180 
8181   return DAG.getNode((VT.getSizeInBits() < 16 ?
8182                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8183 }
8184 
8185 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8186   EVT VT = Op.getValueType();
8187   unsigned BitWidth = VT.getSizeInBits();
8188   SDLoc dl(Op);
8189   assert(Op.getNumOperands() == 3 &&
8190          VT == Op.getOperand(1).getValueType() &&
8191          "Unexpected SHL!");
8192 
8193   // Expand into a bunch of logical ops.  Note that these ops
8194   // depend on the PPC behavior for oversized shift amounts.
8195   SDValue Lo = Op.getOperand(0);
8196   SDValue Hi = Op.getOperand(1);
8197   SDValue Amt = Op.getOperand(2);
8198   EVT AmtVT = Amt.getValueType();
8199 
8200   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8201                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8202   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8203   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8204   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8205   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8206                              DAG.getConstant(-BitWidth, dl, AmtVT));
8207   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8208   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8209   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8210   SDValue OutOps[] = { OutLo, OutHi };
8211   return DAG.getMergeValues(OutOps, dl);
8212 }
8213 
8214 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8215   EVT VT = Op.getValueType();
8216   SDLoc dl(Op);
8217   unsigned BitWidth = VT.getSizeInBits();
8218   assert(Op.getNumOperands() == 3 &&
8219          VT == Op.getOperand(1).getValueType() &&
8220          "Unexpected SRL!");
8221 
8222   // Expand into a bunch of logical ops.  Note that these ops
8223   // depend on the PPC behavior for oversized shift amounts.
8224   SDValue Lo = Op.getOperand(0);
8225   SDValue Hi = Op.getOperand(1);
8226   SDValue Amt = Op.getOperand(2);
8227   EVT AmtVT = Amt.getValueType();
8228 
8229   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8230                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8231   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8232   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8233   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8234   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8235                              DAG.getConstant(-BitWidth, dl, AmtVT));
8236   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8237   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8238   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8239   SDValue OutOps[] = { OutLo, OutHi };
8240   return DAG.getMergeValues(OutOps, dl);
8241 }
8242 
8243 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8244   SDLoc dl(Op);
8245   EVT VT = Op.getValueType();
8246   unsigned BitWidth = VT.getSizeInBits();
8247   assert(Op.getNumOperands() == 3 &&
8248          VT == Op.getOperand(1).getValueType() &&
8249          "Unexpected SRA!");
8250 
8251   // Expand into a bunch of logical ops, followed by a select_cc.
8252   SDValue Lo = Op.getOperand(0);
8253   SDValue Hi = Op.getOperand(1);
8254   SDValue Amt = Op.getOperand(2);
8255   EVT AmtVT = Amt.getValueType();
8256 
8257   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8258                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8259   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8260   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8261   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8262   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8263                              DAG.getConstant(-BitWidth, dl, AmtVT));
8264   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8265   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8266   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8267                                   Tmp4, Tmp6, ISD::SETLE);
8268   SDValue OutOps[] = { OutLo, OutHi };
8269   return DAG.getMergeValues(OutOps, dl);
8270 }
8271 
8272 //===----------------------------------------------------------------------===//
8273 // Vector related lowering.
8274 //
8275 
8276 /// BuildSplatI - Build a canonical splati of Val with an element size of
8277 /// SplatSize.  Cast the result to VT.
8278 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8279                            SelectionDAG &DAG, const SDLoc &dl) {
8280   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
8281 
8282   static const MVT VTys[] = { // canonical VT to use for each size.
8283     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8284   };
8285 
8286   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8287 
8288   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8289   if (Val == -1)
8290     SplatSize = 1;
8291 
8292   EVT CanonicalVT = VTys[SplatSize-1];
8293 
8294   // Build a canonical splat for this value.
8295   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8296 }
8297 
8298 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8299 /// specified intrinsic ID.
8300 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8301                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8302   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8303   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8304                      DAG.getConstant(IID, dl, MVT::i32), Op);
8305 }
8306 
8307 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8308 /// specified intrinsic ID.
8309 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8310                                 SelectionDAG &DAG, const SDLoc &dl,
8311                                 EVT DestVT = MVT::Other) {
8312   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8313   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8314                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8315 }
8316 
8317 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8318 /// specified intrinsic ID.
8319 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8320                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8321                                 EVT DestVT = MVT::Other) {
8322   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8323   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8324                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8325 }
8326 
8327 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8328 /// amount.  The result has the specified value type.
8329 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8330                            SelectionDAG &DAG, const SDLoc &dl) {
8331   // Force LHS/RHS to be the right type.
8332   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8333   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8334 
8335   int Ops[16];
8336   for (unsigned i = 0; i != 16; ++i)
8337     Ops[i] = i + Amt;
8338   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8339   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8340 }
8341 
8342 /// Do we have an efficient pattern in a .td file for this node?
8343 ///
8344 /// \param V - pointer to the BuildVectorSDNode being matched
8345 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8346 ///
8347 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8348 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8349 /// the opposite is true (expansion is beneficial) are:
8350 /// - The node builds a vector out of integers that are not 32 or 64-bits
8351 /// - The node builds a vector out of constants
8352 /// - The node is a "load-and-splat"
8353 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8354 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8355                                             bool HasDirectMove,
8356                                             bool HasP8Vector) {
8357   EVT VecVT = V->getValueType(0);
8358   bool RightType = VecVT == MVT::v2f64 ||
8359     (HasP8Vector && VecVT == MVT::v4f32) ||
8360     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8361   if (!RightType)
8362     return false;
8363 
8364   bool IsSplat = true;
8365   bool IsLoad = false;
8366   SDValue Op0 = V->getOperand(0);
8367 
8368   // This function is called in a block that confirms the node is not a constant
8369   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8370   // different constants.
8371   if (V->isConstant())
8372     return false;
8373   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8374     if (V->getOperand(i).isUndef())
8375       return false;
8376     // We want to expand nodes that represent load-and-splat even if the
8377     // loaded value is a floating point truncation or conversion to int.
8378     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8379         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8380          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8381         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8382          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8383         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8384          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8385       IsLoad = true;
8386     // If the operands are different or the input is not a load and has more
8387     // uses than just this BV node, then it isn't a splat.
8388     if (V->getOperand(i) != Op0 ||
8389         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8390       IsSplat = false;
8391   }
8392   return !(IsSplat && IsLoad);
8393 }
8394 
8395 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8396 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8397 
8398   SDLoc dl(Op);
8399   SDValue Op0 = Op->getOperand(0);
8400 
8401   if (!EnableQuadPrecision ||
8402       (Op.getValueType() != MVT::f128 ) ||
8403       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8404       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8405       (Op0.getOperand(1).getValueType() != MVT::i64))
8406     return SDValue();
8407 
8408   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8409                      Op0.getOperand(1));
8410 }
8411 
8412 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8413   const SDValue *InputLoad = &Op;
8414   if (InputLoad->getOpcode() == ISD::BITCAST)
8415     InputLoad = &InputLoad->getOperand(0);
8416   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8417     InputLoad = &InputLoad->getOperand(0);
8418   if (InputLoad->getOpcode() != ISD::LOAD)
8419     return nullptr;
8420   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8421   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8422 }
8423 
8424 // If this is a case we can't handle, return null and let the default
8425 // expansion code take care of it.  If we CAN select this case, and if it
8426 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8427 // this case more efficiently than a constant pool load, lower it to the
8428 // sequence of ops that should be used.
8429 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8430                                              SelectionDAG &DAG) const {
8431   SDLoc dl(Op);
8432   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8433   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8434 
8435   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8436     // We first build an i32 vector, load it into a QPX register,
8437     // then convert it to a floating-point vector and compare it
8438     // to a zero vector to get the boolean result.
8439     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8440     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8441     MachinePointerInfo PtrInfo =
8442         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8443     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8444     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8445 
8446     assert(BVN->getNumOperands() == 4 &&
8447       "BUILD_VECTOR for v4i1 does not have 4 operands");
8448 
8449     bool IsConst = true;
8450     for (unsigned i = 0; i < 4; ++i) {
8451       if (BVN->getOperand(i).isUndef()) continue;
8452       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8453         IsConst = false;
8454         break;
8455       }
8456     }
8457 
8458     if (IsConst) {
8459       Constant *One =
8460         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8461       Constant *NegOne =
8462         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8463 
8464       Constant *CV[4];
8465       for (unsigned i = 0; i < 4; ++i) {
8466         if (BVN->getOperand(i).isUndef())
8467           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8468         else if (isNullConstant(BVN->getOperand(i)))
8469           CV[i] = NegOne;
8470         else
8471           CV[i] = One;
8472       }
8473 
8474       Constant *CP = ConstantVector::get(CV);
8475       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8476                                           16 /* alignment */);
8477 
8478       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8479       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8480       return DAG.getMemIntrinsicNode(
8481           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8482           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8483     }
8484 
8485     SmallVector<SDValue, 4> Stores;
8486     for (unsigned i = 0; i < 4; ++i) {
8487       if (BVN->getOperand(i).isUndef()) continue;
8488 
8489       unsigned Offset = 4*i;
8490       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8491       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8492 
8493       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8494       if (StoreSize > 4) {
8495         Stores.push_back(
8496             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8497                               PtrInfo.getWithOffset(Offset), MVT::i32));
8498       } else {
8499         SDValue StoreValue = BVN->getOperand(i);
8500         if (StoreSize < 4)
8501           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8502 
8503         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8504                                       PtrInfo.getWithOffset(Offset)));
8505       }
8506     }
8507 
8508     SDValue StoreChain;
8509     if (!Stores.empty())
8510       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8511     else
8512       StoreChain = DAG.getEntryNode();
8513 
8514     // Now load from v4i32 into the QPX register; this will extend it to
8515     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8516     // is typed as v4f64 because the QPX register integer states are not
8517     // explicitly represented.
8518 
8519     SDValue Ops[] = {StoreChain,
8520                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8521                      FIdx};
8522     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8523 
8524     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8525       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8526     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8527       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8528       LoadedVect);
8529 
8530     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8531 
8532     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8533   }
8534 
8535   // All other QPX vectors are handled by generic code.
8536   if (Subtarget.hasQPX())
8537     return SDValue();
8538 
8539   // Check if this is a splat of a constant value.
8540   APInt APSplatBits, APSplatUndef;
8541   unsigned SplatBitSize;
8542   bool HasAnyUndefs;
8543   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8544                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8545       SplatBitSize > 32) {
8546 
8547     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8548     // Handle load-and-splat patterns as we have instructions that will do this
8549     // in one go.
8550     if (InputLoad && DAG.isSplatValue(Op, true)) {
8551       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8552 
8553       // We have handling for 4 and 8 byte elements.
8554       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8555 
8556       // Checking for a single use of this load, we have to check for vector
8557       // width (128 bits) / ElementSize uses (since each operand of the
8558       // BUILD_VECTOR is a separate use of the value.
8559       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8560           ((Subtarget.hasVSX() && ElementSize == 64) ||
8561            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8562         SDValue Ops[] = {
8563           LD->getChain(),    // Chain
8564           LD->getBasePtr(),  // Ptr
8565           DAG.getValueType(Op.getValueType()) // VT
8566         };
8567         return
8568           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8569                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8570                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8571       }
8572     }
8573 
8574     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8575     // lowered to VSX instructions under certain conditions.
8576     // Without VSX, there is no pattern more efficient than expanding the node.
8577     if (Subtarget.hasVSX() &&
8578         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8579                                         Subtarget.hasP8Vector()))
8580       return Op;
8581     return SDValue();
8582   }
8583 
8584   unsigned SplatBits = APSplatBits.getZExtValue();
8585   unsigned SplatUndef = APSplatUndef.getZExtValue();
8586   unsigned SplatSize = SplatBitSize / 8;
8587 
8588   // First, handle single instruction cases.
8589 
8590   // All zeros?
8591   if (SplatBits == 0) {
8592     // Canonicalize all zero vectors to be v4i32.
8593     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8594       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8595       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8596     }
8597     return Op;
8598   }
8599 
8600   // We have XXSPLTIB for constant splats one byte wide
8601   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8602     // This is a splat of 1-byte elements with some elements potentially undef.
8603     // Rather than trying to match undef in the SDAG patterns, ensure that all
8604     // elements are the same constant.
8605     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8606       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8607                                                        dl, MVT::i32));
8608       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8609       if (Op.getValueType() != MVT::v16i8)
8610         return DAG.getBitcast(Op.getValueType(), NewBV);
8611       return NewBV;
8612     }
8613 
8614     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8615     // detect that constant splats like v8i16: 0xABAB are really just splats
8616     // of a 1-byte constant. In this case, we need to convert the node to a
8617     // splat of v16i8 and a bitcast.
8618     if (Op.getValueType() != MVT::v16i8)
8619       return DAG.getBitcast(Op.getValueType(),
8620                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8621 
8622     return Op;
8623   }
8624 
8625   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8626   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8627                     (32-SplatBitSize));
8628   if (SextVal >= -16 && SextVal <= 15)
8629     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8630 
8631   // Two instruction sequences.
8632 
8633   // If this value is in the range [-32,30] and is even, use:
8634   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8635   // If this value is in the range [17,31] and is odd, use:
8636   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8637   // If this value is in the range [-31,-17] and is odd, use:
8638   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8639   // Note the last two are three-instruction sequences.
8640   if (SextVal >= -32 && SextVal <= 31) {
8641     // To avoid having these optimizations undone by constant folding,
8642     // we convert to a pseudo that will be expanded later into one of
8643     // the above forms.
8644     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8645     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8646               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8647     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8648     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8649     if (VT == Op.getValueType())
8650       return RetVal;
8651     else
8652       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8653   }
8654 
8655   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8656   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8657   // for fneg/fabs.
8658   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8659     // Make -1 and vspltisw -1:
8660     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8661 
8662     // Make the VSLW intrinsic, computing 0x8000_0000.
8663     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8664                                    OnesV, DAG, dl);
8665 
8666     // xor by OnesV to invert it.
8667     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8668     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8669   }
8670 
8671   // Check to see if this is a wide variety of vsplti*, binop self cases.
8672   static const signed char SplatCsts[] = {
8673     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8674     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8675   };
8676 
8677   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8678     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8679     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8680     int i = SplatCsts[idx];
8681 
8682     // Figure out what shift amount will be used by altivec if shifted by i in
8683     // this splat size.
8684     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8685 
8686     // vsplti + shl self.
8687     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8688       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8689       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8690         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8691         Intrinsic::ppc_altivec_vslw
8692       };
8693       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8694       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8695     }
8696 
8697     // vsplti + srl self.
8698     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8699       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8700       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8701         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8702         Intrinsic::ppc_altivec_vsrw
8703       };
8704       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8705       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8706     }
8707 
8708     // vsplti + sra self.
8709     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8710       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8711       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8712         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8713         Intrinsic::ppc_altivec_vsraw
8714       };
8715       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8716       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8717     }
8718 
8719     // vsplti + rol self.
8720     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8721                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8722       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8723       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8724         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8725         Intrinsic::ppc_altivec_vrlw
8726       };
8727       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8728       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8729     }
8730 
8731     // t = vsplti c, result = vsldoi t, t, 1
8732     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8733       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8734       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8735       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8736     }
8737     // t = vsplti c, result = vsldoi t, t, 2
8738     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8739       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8740       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8741       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8742     }
8743     // t = vsplti c, result = vsldoi t, t, 3
8744     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8745       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8746       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8747       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8748     }
8749   }
8750 
8751   return SDValue();
8752 }
8753 
8754 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8755 /// the specified operations to build the shuffle.
8756 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8757                                       SDValue RHS, SelectionDAG &DAG,
8758                                       const SDLoc &dl) {
8759   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8760   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8761   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8762 
8763   enum {
8764     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8765     OP_VMRGHW,
8766     OP_VMRGLW,
8767     OP_VSPLTISW0,
8768     OP_VSPLTISW1,
8769     OP_VSPLTISW2,
8770     OP_VSPLTISW3,
8771     OP_VSLDOI4,
8772     OP_VSLDOI8,
8773     OP_VSLDOI12
8774   };
8775 
8776   if (OpNum == OP_COPY) {
8777     if (LHSID == (1*9+2)*9+3) return LHS;
8778     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8779     return RHS;
8780   }
8781 
8782   SDValue OpLHS, OpRHS;
8783   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8784   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8785 
8786   int ShufIdxs[16];
8787   switch (OpNum) {
8788   default: llvm_unreachable("Unknown i32 permute!");
8789   case OP_VMRGHW:
8790     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8791     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8792     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8793     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8794     break;
8795   case OP_VMRGLW:
8796     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8797     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8798     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8799     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8800     break;
8801   case OP_VSPLTISW0:
8802     for (unsigned i = 0; i != 16; ++i)
8803       ShufIdxs[i] = (i&3)+0;
8804     break;
8805   case OP_VSPLTISW1:
8806     for (unsigned i = 0; i != 16; ++i)
8807       ShufIdxs[i] = (i&3)+4;
8808     break;
8809   case OP_VSPLTISW2:
8810     for (unsigned i = 0; i != 16; ++i)
8811       ShufIdxs[i] = (i&3)+8;
8812     break;
8813   case OP_VSPLTISW3:
8814     for (unsigned i = 0; i != 16; ++i)
8815       ShufIdxs[i] = (i&3)+12;
8816     break;
8817   case OP_VSLDOI4:
8818     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8819   case OP_VSLDOI8:
8820     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8821   case OP_VSLDOI12:
8822     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8823   }
8824   EVT VT = OpLHS.getValueType();
8825   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8826   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8827   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8828   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8829 }
8830 
8831 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8832 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8833 /// SDValue.
8834 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8835                                            SelectionDAG &DAG) const {
8836   const unsigned BytesInVector = 16;
8837   bool IsLE = Subtarget.isLittleEndian();
8838   SDLoc dl(N);
8839   SDValue V1 = N->getOperand(0);
8840   SDValue V2 = N->getOperand(1);
8841   unsigned ShiftElts = 0, InsertAtByte = 0;
8842   bool Swap = false;
8843 
8844   // Shifts required to get the byte we want at element 7.
8845   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8846                                    0, 15, 14, 13, 12, 11, 10, 9};
8847   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8848                                 1, 2,  3,  4,  5,  6,  7,  8};
8849 
8850   ArrayRef<int> Mask = N->getMask();
8851   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8852 
8853   // For each mask element, find out if we're just inserting something
8854   // from V2 into V1 or vice versa.
8855   // Possible permutations inserting an element from V2 into V1:
8856   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8857   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8858   //   ...
8859   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8860   // Inserting from V1 into V2 will be similar, except mask range will be
8861   // [16,31].
8862 
8863   bool FoundCandidate = false;
8864   // If both vector operands for the shuffle are the same vector, the mask
8865   // will contain only elements from the first one and the second one will be
8866   // undef.
8867   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8868   // Go through the mask of half-words to find an element that's being moved
8869   // from one vector to the other.
8870   for (unsigned i = 0; i < BytesInVector; ++i) {
8871     unsigned CurrentElement = Mask[i];
8872     // If 2nd operand is undefined, we should only look for element 7 in the
8873     // Mask.
8874     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8875       continue;
8876 
8877     bool OtherElementsInOrder = true;
8878     // Examine the other elements in the Mask to see if they're in original
8879     // order.
8880     for (unsigned j = 0; j < BytesInVector; ++j) {
8881       if (j == i)
8882         continue;
8883       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8884       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8885       // in which we always assume we're always picking from the 1st operand.
8886       int MaskOffset =
8887           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8888       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8889         OtherElementsInOrder = false;
8890         break;
8891       }
8892     }
8893     // If other elements are in original order, we record the number of shifts
8894     // we need to get the element we want into element 7. Also record which byte
8895     // in the vector we should insert into.
8896     if (OtherElementsInOrder) {
8897       // If 2nd operand is undefined, we assume no shifts and no swapping.
8898       if (V2.isUndef()) {
8899         ShiftElts = 0;
8900         Swap = false;
8901       } else {
8902         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8903         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8904                          : BigEndianShifts[CurrentElement & 0xF];
8905         Swap = CurrentElement < BytesInVector;
8906       }
8907       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8908       FoundCandidate = true;
8909       break;
8910     }
8911   }
8912 
8913   if (!FoundCandidate)
8914     return SDValue();
8915 
8916   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8917   // optionally with VECSHL if shift is required.
8918   if (Swap)
8919     std::swap(V1, V2);
8920   if (V2.isUndef())
8921     V2 = V1;
8922   if (ShiftElts) {
8923     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8924                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8925     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8926                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8927   }
8928   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8929                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8930 }
8931 
8932 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8933 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8934 /// SDValue.
8935 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8936                                            SelectionDAG &DAG) const {
8937   const unsigned NumHalfWords = 8;
8938   const unsigned BytesInVector = NumHalfWords * 2;
8939   // Check that the shuffle is on half-words.
8940   if (!isNByteElemShuffleMask(N, 2, 1))
8941     return SDValue();
8942 
8943   bool IsLE = Subtarget.isLittleEndian();
8944   SDLoc dl(N);
8945   SDValue V1 = N->getOperand(0);
8946   SDValue V2 = N->getOperand(1);
8947   unsigned ShiftElts = 0, InsertAtByte = 0;
8948   bool Swap = false;
8949 
8950   // Shifts required to get the half-word we want at element 3.
8951   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8952   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8953 
8954   uint32_t Mask = 0;
8955   uint32_t OriginalOrderLow = 0x1234567;
8956   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8957   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8958   // 32-bit space, only need 4-bit nibbles per element.
8959   for (unsigned i = 0; i < NumHalfWords; ++i) {
8960     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8961     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8962   }
8963 
8964   // For each mask element, find out if we're just inserting something
8965   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8966   // from V2 into V1:
8967   //   X, 1, 2, 3, 4, 5, 6, 7
8968   //   0, X, 2, 3, 4, 5, 6, 7
8969   //   0, 1, X, 3, 4, 5, 6, 7
8970   //   0, 1, 2, X, 4, 5, 6, 7
8971   //   0, 1, 2, 3, X, 5, 6, 7
8972   //   0, 1, 2, 3, 4, X, 6, 7
8973   //   0, 1, 2, 3, 4, 5, X, 7
8974   //   0, 1, 2, 3, 4, 5, 6, X
8975   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8976 
8977   bool FoundCandidate = false;
8978   // Go through the mask of half-words to find an element that's being moved
8979   // from one vector to the other.
8980   for (unsigned i = 0; i < NumHalfWords; ++i) {
8981     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8982     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8983     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8984     uint32_t TargetOrder = 0x0;
8985 
8986     // If both vector operands for the shuffle are the same vector, the mask
8987     // will contain only elements from the first one and the second one will be
8988     // undef.
8989     if (V2.isUndef()) {
8990       ShiftElts = 0;
8991       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8992       TargetOrder = OriginalOrderLow;
8993       Swap = false;
8994       // Skip if not the correct element or mask of other elements don't equal
8995       // to our expected order.
8996       if (MaskOneElt == VINSERTHSrcElem &&
8997           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8998         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8999         FoundCandidate = true;
9000         break;
9001       }
9002     } else { // If both operands are defined.
9003       // Target order is [8,15] if the current mask is between [0,7].
9004       TargetOrder =
9005           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9006       // Skip if mask of other elements don't equal our expected order.
9007       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9008         // We only need the last 3 bits for the number of shifts.
9009         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9010                          : BigEndianShifts[MaskOneElt & 0x7];
9011         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9012         Swap = MaskOneElt < NumHalfWords;
9013         FoundCandidate = true;
9014         break;
9015       }
9016     }
9017   }
9018 
9019   if (!FoundCandidate)
9020     return SDValue();
9021 
9022   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9023   // optionally with VECSHL if shift is required.
9024   if (Swap)
9025     std::swap(V1, V2);
9026   if (V2.isUndef())
9027     V2 = V1;
9028   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9029   if (ShiftElts) {
9030     // Double ShiftElts because we're left shifting on v16i8 type.
9031     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9032                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9033     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9034     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9035                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9036     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9037   }
9038   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9039   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9040                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9041   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9042 }
9043 
9044 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9045 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9046 /// return the code it can be lowered into.  Worst case, it can always be
9047 /// lowered into a vperm.
9048 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9049                                                SelectionDAG &DAG) const {
9050   SDLoc dl(Op);
9051   SDValue V1 = Op.getOperand(0);
9052   SDValue V2 = Op.getOperand(1);
9053   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9054   EVT VT = Op.getValueType();
9055   bool isLittleEndian = Subtarget.isLittleEndian();
9056 
9057   unsigned ShiftElts, InsertAtByte;
9058   bool Swap = false;
9059 
9060   // If this is a load-and-splat, we can do that with a single instruction
9061   // in some cases. However if the load has multiple uses, we don't want to
9062   // combine it because that will just produce multiple loads.
9063   const SDValue *InputLoad = getNormalLoadInput(V1);
9064   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9065       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9066       InputLoad->hasOneUse()) {
9067     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9068     int SplatIdx =
9069       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9070 
9071     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9072     // For 4-byte load-and-splat, we need Power9.
9073     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9074       uint64_t Offset = 0;
9075       if (IsFourByte)
9076         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9077       else
9078         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9079       SDValue BasePtr = LD->getBasePtr();
9080       if (Offset != 0)
9081         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9082                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9083       SDValue Ops[] = {
9084         LD->getChain(),    // Chain
9085         BasePtr,           // BasePtr
9086         DAG.getValueType(Op.getValueType()) // VT
9087       };
9088       SDVTList VTL =
9089         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9090       SDValue LdSplt =
9091         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9092                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9093       if (LdSplt.getValueType() != SVOp->getValueType(0))
9094         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9095       return LdSplt;
9096     }
9097   }
9098   if (Subtarget.hasP9Vector() &&
9099       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9100                            isLittleEndian)) {
9101     if (Swap)
9102       std::swap(V1, V2);
9103     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9104     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9105     if (ShiftElts) {
9106       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9107                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9108       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9109                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9110       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9111     }
9112     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9113                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9114     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9115   }
9116 
9117   if (Subtarget.hasP9Altivec()) {
9118     SDValue NewISDNode;
9119     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9120       return NewISDNode;
9121 
9122     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9123       return NewISDNode;
9124   }
9125 
9126   if (Subtarget.hasVSX() &&
9127       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9128     if (Swap)
9129       std::swap(V1, V2);
9130     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9131     SDValue Conv2 =
9132         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9133 
9134     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9135                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9136     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9137   }
9138 
9139   if (Subtarget.hasVSX() &&
9140     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9141     if (Swap)
9142       std::swap(V1, V2);
9143     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9144     SDValue Conv2 =
9145         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9146 
9147     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9148                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9149     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9150   }
9151 
9152   if (Subtarget.hasP9Vector()) {
9153      if (PPC::isXXBRHShuffleMask(SVOp)) {
9154       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9155       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
9156       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9157     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9158       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9159       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
9160       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9161     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9162       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9163       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
9164       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9165     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9166       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9167       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
9168       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9169     }
9170   }
9171 
9172   if (Subtarget.hasVSX()) {
9173     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9174       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9175 
9176       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9177       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9178                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9179       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9180     }
9181 
9182     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9183     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9184       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9185       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9186       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9187     }
9188   }
9189 
9190   if (Subtarget.hasQPX()) {
9191     if (VT.getVectorNumElements() != 4)
9192       return SDValue();
9193 
9194     if (V2.isUndef()) V2 = V1;
9195 
9196     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9197     if (AlignIdx != -1) {
9198       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9199                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9200     } else if (SVOp->isSplat()) {
9201       int SplatIdx = SVOp->getSplatIndex();
9202       if (SplatIdx >= 4) {
9203         std::swap(V1, V2);
9204         SplatIdx -= 4;
9205       }
9206 
9207       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9208                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9209     }
9210 
9211     // Lower this into a qvgpci/qvfperm pair.
9212 
9213     // Compute the qvgpci literal
9214     unsigned idx = 0;
9215     for (unsigned i = 0; i < 4; ++i) {
9216       int m = SVOp->getMaskElt(i);
9217       unsigned mm = m >= 0 ? (unsigned) m : i;
9218       idx |= mm << (3-i)*3;
9219     }
9220 
9221     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9222                              DAG.getConstant(idx, dl, MVT::i32));
9223     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9224   }
9225 
9226   // Cases that are handled by instructions that take permute immediates
9227   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9228   // selected by the instruction selector.
9229   if (V2.isUndef()) {
9230     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9231         PPC::isSplatShuffleMask(SVOp, 2) ||
9232         PPC::isSplatShuffleMask(SVOp, 4) ||
9233         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9234         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9235         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9236         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9237         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9238         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9239         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9240         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9241         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9242         (Subtarget.hasP8Altivec() && (
9243          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9244          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9245          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9246       return Op;
9247     }
9248   }
9249 
9250   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9251   // and produce a fixed permutation.  If any of these match, do not lower to
9252   // VPERM.
9253   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9254   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9255       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9256       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9257       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9258       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9259       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9260       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9261       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9262       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9263       (Subtarget.hasP8Altivec() && (
9264        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9265        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9266        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9267     return Op;
9268 
9269   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9270   // perfect shuffle table to emit an optimal matching sequence.
9271   ArrayRef<int> PermMask = SVOp->getMask();
9272 
9273   unsigned PFIndexes[4];
9274   bool isFourElementShuffle = true;
9275   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9276     unsigned EltNo = 8;   // Start out undef.
9277     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9278       if (PermMask[i*4+j] < 0)
9279         continue;   // Undef, ignore it.
9280 
9281       unsigned ByteSource = PermMask[i*4+j];
9282       if ((ByteSource & 3) != j) {
9283         isFourElementShuffle = false;
9284         break;
9285       }
9286 
9287       if (EltNo == 8) {
9288         EltNo = ByteSource/4;
9289       } else if (EltNo != ByteSource/4) {
9290         isFourElementShuffle = false;
9291         break;
9292       }
9293     }
9294     PFIndexes[i] = EltNo;
9295   }
9296 
9297   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9298   // perfect shuffle vector to determine if it is cost effective to do this as
9299   // discrete instructions, or whether we should use a vperm.
9300   // For now, we skip this for little endian until such time as we have a
9301   // little-endian perfect shuffle table.
9302   if (isFourElementShuffle && !isLittleEndian) {
9303     // Compute the index in the perfect shuffle table.
9304     unsigned PFTableIndex =
9305       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9306 
9307     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9308     unsigned Cost  = (PFEntry >> 30);
9309 
9310     // Determining when to avoid vperm is tricky.  Many things affect the cost
9311     // of vperm, particularly how many times the perm mask needs to be computed.
9312     // For example, if the perm mask can be hoisted out of a loop or is already
9313     // used (perhaps because there are multiple permutes with the same shuffle
9314     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9315     // the loop requires an extra register.
9316     //
9317     // As a compromise, we only emit discrete instructions if the shuffle can be
9318     // generated in 3 or fewer operations.  When we have loop information
9319     // available, if this block is within a loop, we should avoid using vperm
9320     // for 3-operation perms and use a constant pool load instead.
9321     if (Cost < 3)
9322       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9323   }
9324 
9325   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9326   // vector that will get spilled to the constant pool.
9327   if (V2.isUndef()) V2 = V1;
9328 
9329   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9330   // that it is in input element units, not in bytes.  Convert now.
9331 
9332   // For little endian, the order of the input vectors is reversed, and
9333   // the permutation mask is complemented with respect to 31.  This is
9334   // necessary to produce proper semantics with the big-endian-biased vperm
9335   // instruction.
9336   EVT EltVT = V1.getValueType().getVectorElementType();
9337   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9338 
9339   SmallVector<SDValue, 16> ResultMask;
9340   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9341     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9342 
9343     for (unsigned j = 0; j != BytesPerElement; ++j)
9344       if (isLittleEndian)
9345         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9346                                              dl, MVT::i32));
9347       else
9348         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9349                                              MVT::i32));
9350   }
9351 
9352   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9353   if (isLittleEndian)
9354     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9355                        V2, V1, VPermMask);
9356   else
9357     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9358                        V1, V2, VPermMask);
9359 }
9360 
9361 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9362 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9363 /// information about the intrinsic.
9364 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9365                                  bool &isDot, const PPCSubtarget &Subtarget) {
9366   unsigned IntrinsicID =
9367       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9368   CompareOpc = -1;
9369   isDot = false;
9370   switch (IntrinsicID) {
9371   default:
9372     return false;
9373   // Comparison predicates.
9374   case Intrinsic::ppc_altivec_vcmpbfp_p:
9375     CompareOpc = 966;
9376     isDot = true;
9377     break;
9378   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9379     CompareOpc = 198;
9380     isDot = true;
9381     break;
9382   case Intrinsic::ppc_altivec_vcmpequb_p:
9383     CompareOpc = 6;
9384     isDot = true;
9385     break;
9386   case Intrinsic::ppc_altivec_vcmpequh_p:
9387     CompareOpc = 70;
9388     isDot = true;
9389     break;
9390   case Intrinsic::ppc_altivec_vcmpequw_p:
9391     CompareOpc = 134;
9392     isDot = true;
9393     break;
9394   case Intrinsic::ppc_altivec_vcmpequd_p:
9395     if (Subtarget.hasP8Altivec()) {
9396       CompareOpc = 199;
9397       isDot = true;
9398     } else
9399       return false;
9400     break;
9401   case Intrinsic::ppc_altivec_vcmpneb_p:
9402   case Intrinsic::ppc_altivec_vcmpneh_p:
9403   case Intrinsic::ppc_altivec_vcmpnew_p:
9404   case Intrinsic::ppc_altivec_vcmpnezb_p:
9405   case Intrinsic::ppc_altivec_vcmpnezh_p:
9406   case Intrinsic::ppc_altivec_vcmpnezw_p:
9407     if (Subtarget.hasP9Altivec()) {
9408       switch (IntrinsicID) {
9409       default:
9410         llvm_unreachable("Unknown comparison intrinsic.");
9411       case Intrinsic::ppc_altivec_vcmpneb_p:
9412         CompareOpc = 7;
9413         break;
9414       case Intrinsic::ppc_altivec_vcmpneh_p:
9415         CompareOpc = 71;
9416         break;
9417       case Intrinsic::ppc_altivec_vcmpnew_p:
9418         CompareOpc = 135;
9419         break;
9420       case Intrinsic::ppc_altivec_vcmpnezb_p:
9421         CompareOpc = 263;
9422         break;
9423       case Intrinsic::ppc_altivec_vcmpnezh_p:
9424         CompareOpc = 327;
9425         break;
9426       case Intrinsic::ppc_altivec_vcmpnezw_p:
9427         CompareOpc = 391;
9428         break;
9429       }
9430       isDot = true;
9431     } else
9432       return false;
9433     break;
9434   case Intrinsic::ppc_altivec_vcmpgefp_p:
9435     CompareOpc = 454;
9436     isDot = true;
9437     break;
9438   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9439     CompareOpc = 710;
9440     isDot = true;
9441     break;
9442   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9443     CompareOpc = 774;
9444     isDot = true;
9445     break;
9446   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9447     CompareOpc = 838;
9448     isDot = true;
9449     break;
9450   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9451     CompareOpc = 902;
9452     isDot = true;
9453     break;
9454   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9455     if (Subtarget.hasP8Altivec()) {
9456       CompareOpc = 967;
9457       isDot = true;
9458     } else
9459       return false;
9460     break;
9461   case Intrinsic::ppc_altivec_vcmpgtub_p:
9462     CompareOpc = 518;
9463     isDot = true;
9464     break;
9465   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9466     CompareOpc = 582;
9467     isDot = true;
9468     break;
9469   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9470     CompareOpc = 646;
9471     isDot = true;
9472     break;
9473   case Intrinsic::ppc_altivec_vcmpgtud_p:
9474     if (Subtarget.hasP8Altivec()) {
9475       CompareOpc = 711;
9476       isDot = true;
9477     } else
9478       return false;
9479     break;
9480 
9481   // VSX predicate comparisons use the same infrastructure
9482   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9483   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9484   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9485   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9486   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9487   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9488     if (Subtarget.hasVSX()) {
9489       switch (IntrinsicID) {
9490       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9491         CompareOpc = 99;
9492         break;
9493       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9494         CompareOpc = 115;
9495         break;
9496       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9497         CompareOpc = 107;
9498         break;
9499       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9500         CompareOpc = 67;
9501         break;
9502       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9503         CompareOpc = 83;
9504         break;
9505       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9506         CompareOpc = 75;
9507         break;
9508       }
9509       isDot = true;
9510     } else
9511       return false;
9512     break;
9513 
9514   // Normal Comparisons.
9515   case Intrinsic::ppc_altivec_vcmpbfp:
9516     CompareOpc = 966;
9517     break;
9518   case Intrinsic::ppc_altivec_vcmpeqfp:
9519     CompareOpc = 198;
9520     break;
9521   case Intrinsic::ppc_altivec_vcmpequb:
9522     CompareOpc = 6;
9523     break;
9524   case Intrinsic::ppc_altivec_vcmpequh:
9525     CompareOpc = 70;
9526     break;
9527   case Intrinsic::ppc_altivec_vcmpequw:
9528     CompareOpc = 134;
9529     break;
9530   case Intrinsic::ppc_altivec_vcmpequd:
9531     if (Subtarget.hasP8Altivec())
9532       CompareOpc = 199;
9533     else
9534       return false;
9535     break;
9536   case Intrinsic::ppc_altivec_vcmpneb:
9537   case Intrinsic::ppc_altivec_vcmpneh:
9538   case Intrinsic::ppc_altivec_vcmpnew:
9539   case Intrinsic::ppc_altivec_vcmpnezb:
9540   case Intrinsic::ppc_altivec_vcmpnezh:
9541   case Intrinsic::ppc_altivec_vcmpnezw:
9542     if (Subtarget.hasP9Altivec())
9543       switch (IntrinsicID) {
9544       default:
9545         llvm_unreachable("Unknown comparison intrinsic.");
9546       case Intrinsic::ppc_altivec_vcmpneb:
9547         CompareOpc = 7;
9548         break;
9549       case Intrinsic::ppc_altivec_vcmpneh:
9550         CompareOpc = 71;
9551         break;
9552       case Intrinsic::ppc_altivec_vcmpnew:
9553         CompareOpc = 135;
9554         break;
9555       case Intrinsic::ppc_altivec_vcmpnezb:
9556         CompareOpc = 263;
9557         break;
9558       case Intrinsic::ppc_altivec_vcmpnezh:
9559         CompareOpc = 327;
9560         break;
9561       case Intrinsic::ppc_altivec_vcmpnezw:
9562         CompareOpc = 391;
9563         break;
9564       }
9565     else
9566       return false;
9567     break;
9568   case Intrinsic::ppc_altivec_vcmpgefp:
9569     CompareOpc = 454;
9570     break;
9571   case Intrinsic::ppc_altivec_vcmpgtfp:
9572     CompareOpc = 710;
9573     break;
9574   case Intrinsic::ppc_altivec_vcmpgtsb:
9575     CompareOpc = 774;
9576     break;
9577   case Intrinsic::ppc_altivec_vcmpgtsh:
9578     CompareOpc = 838;
9579     break;
9580   case Intrinsic::ppc_altivec_vcmpgtsw:
9581     CompareOpc = 902;
9582     break;
9583   case Intrinsic::ppc_altivec_vcmpgtsd:
9584     if (Subtarget.hasP8Altivec())
9585       CompareOpc = 967;
9586     else
9587       return false;
9588     break;
9589   case Intrinsic::ppc_altivec_vcmpgtub:
9590     CompareOpc = 518;
9591     break;
9592   case Intrinsic::ppc_altivec_vcmpgtuh:
9593     CompareOpc = 582;
9594     break;
9595   case Intrinsic::ppc_altivec_vcmpgtuw:
9596     CompareOpc = 646;
9597     break;
9598   case Intrinsic::ppc_altivec_vcmpgtud:
9599     if (Subtarget.hasP8Altivec())
9600       CompareOpc = 711;
9601     else
9602       return false;
9603     break;
9604   }
9605   return true;
9606 }
9607 
9608 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9609 /// lower, do it, otherwise return null.
9610 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9611                                                    SelectionDAG &DAG) const {
9612   unsigned IntrinsicID =
9613     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9614 
9615   SDLoc dl(Op);
9616 
9617   if (IntrinsicID == Intrinsic::thread_pointer) {
9618     // Reads the thread pointer register, used for __builtin_thread_pointer.
9619     if (Subtarget.isPPC64())
9620       return DAG.getRegister(PPC::X13, MVT::i64);
9621     return DAG.getRegister(PPC::R2, MVT::i32);
9622   }
9623 
9624   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9625   // opcode number of the comparison.
9626   int CompareOpc;
9627   bool isDot;
9628   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9629     return SDValue();    // Don't custom lower most intrinsics.
9630 
9631   // If this is a non-dot comparison, make the VCMP node and we are done.
9632   if (!isDot) {
9633     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9634                               Op.getOperand(1), Op.getOperand(2),
9635                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9636     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9637   }
9638 
9639   // Create the PPCISD altivec 'dot' comparison node.
9640   SDValue Ops[] = {
9641     Op.getOperand(2),  // LHS
9642     Op.getOperand(3),  // RHS
9643     DAG.getConstant(CompareOpc, dl, MVT::i32)
9644   };
9645   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9646   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9647 
9648   // Now that we have the comparison, emit a copy from the CR to a GPR.
9649   // This is flagged to the above dot comparison.
9650   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9651                                 DAG.getRegister(PPC::CR6, MVT::i32),
9652                                 CompNode.getValue(1));
9653 
9654   // Unpack the result based on how the target uses it.
9655   unsigned BitNo;   // Bit # of CR6.
9656   bool InvertBit;   // Invert result?
9657   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9658   default:  // Can't happen, don't crash on invalid number though.
9659   case 0:   // Return the value of the EQ bit of CR6.
9660     BitNo = 0; InvertBit = false;
9661     break;
9662   case 1:   // Return the inverted value of the EQ bit of CR6.
9663     BitNo = 0; InvertBit = true;
9664     break;
9665   case 2:   // Return the value of the LT bit of CR6.
9666     BitNo = 2; InvertBit = false;
9667     break;
9668   case 3:   // Return the inverted value of the LT bit of CR6.
9669     BitNo = 2; InvertBit = true;
9670     break;
9671   }
9672 
9673   // Shift the bit into the low position.
9674   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9675                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9676   // Isolate the bit.
9677   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9678                       DAG.getConstant(1, dl, MVT::i32));
9679 
9680   // If we are supposed to, toggle the bit.
9681   if (InvertBit)
9682     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9683                         DAG.getConstant(1, dl, MVT::i32));
9684   return Flags;
9685 }
9686 
9687 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9688                                                SelectionDAG &DAG) const {
9689   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9690   // the beginning of the argument list.
9691   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9692   SDLoc DL(Op);
9693   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9694   case Intrinsic::ppc_cfence: {
9695     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9696     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9697     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9698                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9699                                                   Op.getOperand(ArgStart + 1)),
9700                                       Op.getOperand(0)),
9701                    0);
9702   }
9703   default:
9704     break;
9705   }
9706   return SDValue();
9707 }
9708 
9709 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9710   // Check for a DIV with the same operands as this REM.
9711   for (auto UI : Op.getOperand(1)->uses()) {
9712     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9713         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9714       if (UI->getOperand(0) == Op.getOperand(0) &&
9715           UI->getOperand(1) == Op.getOperand(1))
9716         return SDValue();
9717   }
9718   return Op;
9719 }
9720 
9721 // Lower scalar BSWAP64 to xxbrd.
9722 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9723   SDLoc dl(Op);
9724   // MTVSRDD
9725   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9726                    Op.getOperand(0));
9727   // XXBRD
9728   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9729   // MFVSRD
9730   int VectorIndex = 0;
9731   if (Subtarget.isLittleEndian())
9732     VectorIndex = 1;
9733   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9734                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9735   return Op;
9736 }
9737 
9738 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9739 // compared to a value that is atomically loaded (atomic loads zero-extend).
9740 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9741                                                 SelectionDAG &DAG) const {
9742   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9743          "Expecting an atomic compare-and-swap here.");
9744   SDLoc dl(Op);
9745   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9746   EVT MemVT = AtomicNode->getMemoryVT();
9747   if (MemVT.getSizeInBits() >= 32)
9748     return Op;
9749 
9750   SDValue CmpOp = Op.getOperand(2);
9751   // If this is already correctly zero-extended, leave it alone.
9752   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9753   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9754     return Op;
9755 
9756   // Clear the high bits of the compare operand.
9757   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9758   SDValue NewCmpOp =
9759     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9760                 DAG.getConstant(MaskVal, dl, MVT::i32));
9761 
9762   // Replace the existing compare operand with the properly zero-extended one.
9763   SmallVector<SDValue, 4> Ops;
9764   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9765     Ops.push_back(AtomicNode->getOperand(i));
9766   Ops[2] = NewCmpOp;
9767   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9768   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9769   auto NodeTy =
9770     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9771   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9772 }
9773 
9774 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9775                                                  SelectionDAG &DAG) const {
9776   SDLoc dl(Op);
9777   // Create a stack slot that is 16-byte aligned.
9778   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9779   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9780   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9781   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9782 
9783   // Store the input value into Value#0 of the stack slot.
9784   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9785                                MachinePointerInfo());
9786   // Load it out.
9787   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9788 }
9789 
9790 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9791                                                   SelectionDAG &DAG) const {
9792   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9793          "Should only be called for ISD::INSERT_VECTOR_ELT");
9794 
9795   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9796   // We have legal lowering for constant indices but not for variable ones.
9797   if (!C)
9798     return SDValue();
9799 
9800   EVT VT = Op.getValueType();
9801   SDLoc dl(Op);
9802   SDValue V1 = Op.getOperand(0);
9803   SDValue V2 = Op.getOperand(1);
9804   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9805   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9806     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9807     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9808     unsigned InsertAtElement = C->getZExtValue();
9809     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9810     if (Subtarget.isLittleEndian()) {
9811       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9812     }
9813     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9814                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9815   }
9816   return Op;
9817 }
9818 
9819 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9820                                                    SelectionDAG &DAG) const {
9821   SDLoc dl(Op);
9822   SDNode *N = Op.getNode();
9823 
9824   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9825          "Unknown extract_vector_elt type");
9826 
9827   SDValue Value = N->getOperand(0);
9828 
9829   // The first part of this is like the store lowering except that we don't
9830   // need to track the chain.
9831 
9832   // The values are now known to be -1 (false) or 1 (true). To convert this
9833   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9834   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9835   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9836 
9837   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9838   // understand how to form the extending load.
9839   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9840 
9841   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9842 
9843   // Now convert to an integer and store.
9844   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9845     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9846     Value);
9847 
9848   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9849   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9850   MachinePointerInfo PtrInfo =
9851       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9852   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9853   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9854 
9855   SDValue StoreChain = DAG.getEntryNode();
9856   SDValue Ops[] = {StoreChain,
9857                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9858                    Value, FIdx};
9859   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9860 
9861   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9862     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9863 
9864   // Extract the value requested.
9865   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9866   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9867   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9868 
9869   SDValue IntVal =
9870       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9871 
9872   if (!Subtarget.useCRBits())
9873     return IntVal;
9874 
9875   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9876 }
9877 
9878 /// Lowering for QPX v4i1 loads
9879 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9880                                            SelectionDAG &DAG) const {
9881   SDLoc dl(Op);
9882   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9883   SDValue LoadChain = LN->getChain();
9884   SDValue BasePtr = LN->getBasePtr();
9885 
9886   if (Op.getValueType() == MVT::v4f64 ||
9887       Op.getValueType() == MVT::v4f32) {
9888     EVT MemVT = LN->getMemoryVT();
9889     unsigned Alignment = LN->getAlignment();
9890 
9891     // If this load is properly aligned, then it is legal.
9892     if (Alignment >= MemVT.getStoreSize())
9893       return Op;
9894 
9895     EVT ScalarVT = Op.getValueType().getScalarType(),
9896         ScalarMemVT = MemVT.getScalarType();
9897     unsigned Stride = ScalarMemVT.getStoreSize();
9898 
9899     SDValue Vals[4], LoadChains[4];
9900     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9901       SDValue Load;
9902       if (ScalarVT != ScalarMemVT)
9903         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9904                               BasePtr,
9905                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9906                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9907                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9908       else
9909         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9910                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9911                            MinAlign(Alignment, Idx * Stride),
9912                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9913 
9914       if (Idx == 0 && LN->isIndexed()) {
9915         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9916                "Unknown addressing mode on vector load");
9917         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9918                                   LN->getAddressingMode());
9919       }
9920 
9921       Vals[Idx] = Load;
9922       LoadChains[Idx] = Load.getValue(1);
9923 
9924       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9925                             DAG.getConstant(Stride, dl,
9926                                             BasePtr.getValueType()));
9927     }
9928 
9929     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9930     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9931 
9932     if (LN->isIndexed()) {
9933       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9934       return DAG.getMergeValues(RetOps, dl);
9935     }
9936 
9937     SDValue RetOps[] = { Value, TF };
9938     return DAG.getMergeValues(RetOps, dl);
9939   }
9940 
9941   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9942   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9943 
9944   // To lower v4i1 from a byte array, we load the byte elements of the
9945   // vector and then reuse the BUILD_VECTOR logic.
9946 
9947   SDValue VectElmts[4], VectElmtChains[4];
9948   for (unsigned i = 0; i < 4; ++i) {
9949     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9950     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9951 
9952     VectElmts[i] = DAG.getExtLoad(
9953         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9954         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9955         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9956     VectElmtChains[i] = VectElmts[i].getValue(1);
9957   }
9958 
9959   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9960   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9961 
9962   SDValue RVals[] = { Value, LoadChain };
9963   return DAG.getMergeValues(RVals, dl);
9964 }
9965 
9966 /// Lowering for QPX v4i1 stores
9967 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9968                                             SelectionDAG &DAG) const {
9969   SDLoc dl(Op);
9970   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9971   SDValue StoreChain = SN->getChain();
9972   SDValue BasePtr = SN->getBasePtr();
9973   SDValue Value = SN->getValue();
9974 
9975   if (Value.getValueType() == MVT::v4f64 ||
9976       Value.getValueType() == MVT::v4f32) {
9977     EVT MemVT = SN->getMemoryVT();
9978     unsigned Alignment = SN->getAlignment();
9979 
9980     // If this store is properly aligned, then it is legal.
9981     if (Alignment >= MemVT.getStoreSize())
9982       return Op;
9983 
9984     EVT ScalarVT = Value.getValueType().getScalarType(),
9985         ScalarMemVT = MemVT.getScalarType();
9986     unsigned Stride = ScalarMemVT.getStoreSize();
9987 
9988     SDValue Stores[4];
9989     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9990       SDValue Ex = DAG.getNode(
9991           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9992           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9993       SDValue Store;
9994       if (ScalarVT != ScalarMemVT)
9995         Store =
9996             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9997                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9998                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9999                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10000       else
10001         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10002                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10003                              MinAlign(Alignment, Idx * Stride),
10004                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10005 
10006       if (Idx == 0 && SN->isIndexed()) {
10007         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10008                "Unknown addressing mode on vector store");
10009         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10010                                     SN->getAddressingMode());
10011       }
10012 
10013       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10014                             DAG.getConstant(Stride, dl,
10015                                             BasePtr.getValueType()));
10016       Stores[Idx] = Store;
10017     }
10018 
10019     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10020 
10021     if (SN->isIndexed()) {
10022       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10023       return DAG.getMergeValues(RetOps, dl);
10024     }
10025 
10026     return TF;
10027   }
10028 
10029   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10030   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10031 
10032   // The values are now known to be -1 (false) or 1 (true). To convert this
10033   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10034   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10035   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10036 
10037   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10038   // understand how to form the extending load.
10039   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10040 
10041   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10042 
10043   // Now convert to an integer and store.
10044   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10045     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10046     Value);
10047 
10048   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10049   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10050   MachinePointerInfo PtrInfo =
10051       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10052   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10053   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10054 
10055   SDValue Ops[] = {StoreChain,
10056                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10057                    Value, FIdx};
10058   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10059 
10060   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10061     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10062 
10063   // Move data into the byte array.
10064   SDValue Loads[4], LoadChains[4];
10065   for (unsigned i = 0; i < 4; ++i) {
10066     unsigned Offset = 4*i;
10067     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10068     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10069 
10070     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10071                            PtrInfo.getWithOffset(Offset));
10072     LoadChains[i] = Loads[i].getValue(1);
10073   }
10074 
10075   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10076 
10077   SDValue Stores[4];
10078   for (unsigned i = 0; i < 4; ++i) {
10079     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10080     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10081 
10082     Stores[i] = DAG.getTruncStore(
10083         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10084         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10085         SN->getAAInfo());
10086   }
10087 
10088   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10089 
10090   return StoreChain;
10091 }
10092 
10093 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10094   SDLoc dl(Op);
10095   if (Op.getValueType() == MVT::v4i32) {
10096     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10097 
10098     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10099     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10100 
10101     SDValue RHSSwap =   // = vrlw RHS, 16
10102       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10103 
10104     // Shrinkify inputs to v8i16.
10105     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10106     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10107     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10108 
10109     // Low parts multiplied together, generating 32-bit results (we ignore the
10110     // top parts).
10111     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10112                                         LHS, RHS, DAG, dl, MVT::v4i32);
10113 
10114     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10115                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10116     // Shift the high parts up 16 bits.
10117     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10118                               Neg16, DAG, dl);
10119     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10120   } else if (Op.getValueType() == MVT::v8i16) {
10121     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10122 
10123     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10124 
10125     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10126                             LHS, RHS, Zero, DAG, dl);
10127   } else if (Op.getValueType() == MVT::v16i8) {
10128     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10129     bool isLittleEndian = Subtarget.isLittleEndian();
10130 
10131     // Multiply the even 8-bit parts, producing 16-bit sums.
10132     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10133                                            LHS, RHS, DAG, dl, MVT::v8i16);
10134     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10135 
10136     // Multiply the odd 8-bit parts, producing 16-bit sums.
10137     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10138                                           LHS, RHS, DAG, dl, MVT::v8i16);
10139     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10140 
10141     // Merge the results together.  Because vmuleub and vmuloub are
10142     // instructions with a big-endian bias, we must reverse the
10143     // element numbering and reverse the meaning of "odd" and "even"
10144     // when generating little endian code.
10145     int Ops[16];
10146     for (unsigned i = 0; i != 8; ++i) {
10147       if (isLittleEndian) {
10148         Ops[i*2  ] = 2*i;
10149         Ops[i*2+1] = 2*i+16;
10150       } else {
10151         Ops[i*2  ] = 2*i+1;
10152         Ops[i*2+1] = 2*i+1+16;
10153       }
10154     }
10155     if (isLittleEndian)
10156       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10157     else
10158       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10159   } else {
10160     llvm_unreachable("Unknown mul to lower!");
10161   }
10162 }
10163 
10164 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10165 
10166   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10167 
10168   EVT VT = Op.getValueType();
10169   assert(VT.isVector() &&
10170          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10171   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10172           VT == MVT::v16i8) &&
10173          "Unexpected vector element type!");
10174   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10175          "Current subtarget doesn't support smax v2i64!");
10176 
10177   // For vector abs, it can be lowered to:
10178   // abs x
10179   // ==>
10180   // y = -x
10181   // smax(x, y)
10182 
10183   SDLoc dl(Op);
10184   SDValue X = Op.getOperand(0);
10185   SDValue Zero = DAG.getConstant(0, dl, VT);
10186   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10187 
10188   // SMAX patch https://reviews.llvm.org/D47332
10189   // hasn't landed yet, so use intrinsic first here.
10190   // TODO: Should use SMAX directly once SMAX patch landed
10191   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10192   if (VT == MVT::v2i64)
10193     BifID = Intrinsic::ppc_altivec_vmaxsd;
10194   else if (VT == MVT::v8i16)
10195     BifID = Intrinsic::ppc_altivec_vmaxsh;
10196   else if (VT == MVT::v16i8)
10197     BifID = Intrinsic::ppc_altivec_vmaxsb;
10198 
10199   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10200 }
10201 
10202 // Custom lowering for fpext vf32 to v2f64
10203 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10204 
10205   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10206          "Should only be called for ISD::FP_EXTEND");
10207 
10208   // We only want to custom lower an extend from v2f32 to v2f64.
10209   if (Op.getValueType() != MVT::v2f64 ||
10210       Op.getOperand(0).getValueType() != MVT::v2f32)
10211     return SDValue();
10212 
10213   SDLoc dl(Op);
10214   SDValue Op0 = Op.getOperand(0);
10215 
10216   switch (Op0.getOpcode()) {
10217   default:
10218     return SDValue();
10219   case ISD::EXTRACT_SUBVECTOR: {
10220     assert(Op0.getNumOperands() == 2 &&
10221            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10222            "Node should have 2 operands with second one being a constant!");
10223 
10224     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10225       return SDValue();
10226 
10227     // Custom lower is only done for high or low doubleword.
10228     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10229     if (Idx % 2 != 0)
10230       return SDValue();
10231 
10232     // Since input is v4f32, at this point Idx is either 0 or 2.
10233     // Shift to get the doubleword position we want.
10234     int DWord = Idx >> 1;
10235 
10236     // High and low word positions are different on little endian.
10237     if (Subtarget.isLittleEndian())
10238       DWord ^= 0x1;
10239 
10240     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10241                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10242   }
10243   case ISD::FADD:
10244   case ISD::FMUL:
10245   case ISD::FSUB: {
10246     SDValue NewLoad[2];
10247     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10248       // Ensure both input are loads.
10249       SDValue LdOp = Op0.getOperand(i);
10250       if (LdOp.getOpcode() != ISD::LOAD)
10251         return SDValue();
10252       // Generate new load node.
10253       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10254       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10255       NewLoad[i] = DAG.getMemIntrinsicNode(
10256           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10257           LD->getMemoryVT(), LD->getMemOperand());
10258     }
10259     SDValue NewOp =
10260         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10261                     NewLoad[1], Op0.getNode()->getFlags());
10262     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10263                        DAG.getConstant(0, dl, MVT::i32));
10264   }
10265   case ISD::LOAD: {
10266     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10267     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10268     SDValue NewLd = DAG.getMemIntrinsicNode(
10269         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10270         LD->getMemoryVT(), LD->getMemOperand());
10271     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10272                        DAG.getConstant(0, dl, MVT::i32));
10273   }
10274   }
10275   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10276 }
10277 
10278 /// LowerOperation - Provide custom lowering hooks for some operations.
10279 ///
10280 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10281   switch (Op.getOpcode()) {
10282   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10283   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10284   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10285   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10286   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10287   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10288   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10289   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10290   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10291 
10292   // Variable argument lowering.
10293   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10294   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10295   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10296 
10297   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10298   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10299   case ISD::GET_DYNAMIC_AREA_OFFSET:
10300     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10301 
10302   // Exception handling lowering.
10303   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10304   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10305   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10306 
10307   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10308   case ISD::STORE:              return LowerSTORE(Op, DAG);
10309   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10310   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10311   case ISD::FP_TO_UINT:
10312   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10313   case ISD::UINT_TO_FP:
10314   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10315   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10316 
10317   // Lower 64-bit shifts.
10318   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10319   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10320   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10321 
10322   // Vector-related lowering.
10323   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10324   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10325   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10326   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10327   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10328   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10329   case ISD::MUL:                return LowerMUL(Op, DAG);
10330   case ISD::ABS:                return LowerABS(Op, DAG);
10331   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10332 
10333   // For counter-based loop handling.
10334   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10335 
10336   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10337 
10338   // Frame & Return address.
10339   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10340   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10341 
10342   case ISD::INTRINSIC_VOID:
10343     return LowerINTRINSIC_VOID(Op, DAG);
10344   case ISD::SREM:
10345   case ISD::UREM:
10346     return LowerREM(Op, DAG);
10347   case ISD::BSWAP:
10348     return LowerBSWAP(Op, DAG);
10349   case ISD::ATOMIC_CMP_SWAP:
10350     return LowerATOMIC_CMP_SWAP(Op, DAG);
10351   }
10352 }
10353 
10354 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10355                                            SmallVectorImpl<SDValue>&Results,
10356                                            SelectionDAG &DAG) const {
10357   SDLoc dl(N);
10358   switch (N->getOpcode()) {
10359   default:
10360     llvm_unreachable("Do not know how to custom type legalize this operation!");
10361   case ISD::READCYCLECOUNTER: {
10362     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10363     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10364 
10365     Results.push_back(RTB);
10366     Results.push_back(RTB.getValue(1));
10367     Results.push_back(RTB.getValue(2));
10368     break;
10369   }
10370   case ISD::INTRINSIC_W_CHAIN: {
10371     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10372         Intrinsic::loop_decrement)
10373       break;
10374 
10375     assert(N->getValueType(0) == MVT::i1 &&
10376            "Unexpected result type for CTR decrement intrinsic");
10377     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10378                                  N->getValueType(0));
10379     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10380     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10381                                  N->getOperand(1));
10382 
10383     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10384     Results.push_back(NewInt.getValue(1));
10385     break;
10386   }
10387   case ISD::VAARG: {
10388     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10389       return;
10390 
10391     EVT VT = N->getValueType(0);
10392 
10393     if (VT == MVT::i64) {
10394       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10395 
10396       Results.push_back(NewNode);
10397       Results.push_back(NewNode.getValue(1));
10398     }
10399     return;
10400   }
10401   case ISD::FP_TO_SINT:
10402   case ISD::FP_TO_UINT:
10403     // LowerFP_TO_INT() can only handle f32 and f64.
10404     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10405       return;
10406     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10407     return;
10408   case ISD::TRUNCATE: {
10409     EVT TrgVT = N->getValueType(0);
10410     EVT OpVT = N->getOperand(0).getValueType();
10411     if (TrgVT.isVector() &&
10412         isOperationCustom(N->getOpcode(), TrgVT) &&
10413         OpVT.getSizeInBits() <= 128 &&
10414         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10415       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10416     return;
10417   }
10418   case ISD::BITCAST:
10419     // Don't handle bitcast here.
10420     return;
10421   }
10422 }
10423 
10424 //===----------------------------------------------------------------------===//
10425 //  Other Lowering Code
10426 //===----------------------------------------------------------------------===//
10427 
10428 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10429   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10430   Function *Func = Intrinsic::getDeclaration(M, Id);
10431   return Builder.CreateCall(Func, {});
10432 }
10433 
10434 // The mappings for emitLeading/TrailingFence is taken from
10435 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10436 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10437                                                  Instruction *Inst,
10438                                                  AtomicOrdering Ord) const {
10439   if (Ord == AtomicOrdering::SequentiallyConsistent)
10440     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10441   if (isReleaseOrStronger(Ord))
10442     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10443   return nullptr;
10444 }
10445 
10446 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10447                                                   Instruction *Inst,
10448                                                   AtomicOrdering Ord) const {
10449   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10450     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10451     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10452     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10453     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10454       return Builder.CreateCall(
10455           Intrinsic::getDeclaration(
10456               Builder.GetInsertBlock()->getParent()->getParent(),
10457               Intrinsic::ppc_cfence, {Inst->getType()}),
10458           {Inst});
10459     // FIXME: Can use isync for rmw operation.
10460     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10461   }
10462   return nullptr;
10463 }
10464 
10465 MachineBasicBlock *
10466 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10467                                     unsigned AtomicSize,
10468                                     unsigned BinOpcode,
10469                                     unsigned CmpOpcode,
10470                                     unsigned CmpPred) const {
10471   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10472   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10473 
10474   auto LoadMnemonic = PPC::LDARX;
10475   auto StoreMnemonic = PPC::STDCX;
10476   switch (AtomicSize) {
10477   default:
10478     llvm_unreachable("Unexpected size of atomic entity");
10479   case 1:
10480     LoadMnemonic = PPC::LBARX;
10481     StoreMnemonic = PPC::STBCX;
10482     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10483     break;
10484   case 2:
10485     LoadMnemonic = PPC::LHARX;
10486     StoreMnemonic = PPC::STHCX;
10487     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10488     break;
10489   case 4:
10490     LoadMnemonic = PPC::LWARX;
10491     StoreMnemonic = PPC::STWCX;
10492     break;
10493   case 8:
10494     LoadMnemonic = PPC::LDARX;
10495     StoreMnemonic = PPC::STDCX;
10496     break;
10497   }
10498 
10499   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10500   MachineFunction *F = BB->getParent();
10501   MachineFunction::iterator It = ++BB->getIterator();
10502 
10503   Register dest = MI.getOperand(0).getReg();
10504   Register ptrA = MI.getOperand(1).getReg();
10505   Register ptrB = MI.getOperand(2).getReg();
10506   Register incr = MI.getOperand(3).getReg();
10507   DebugLoc dl = MI.getDebugLoc();
10508 
10509   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10510   MachineBasicBlock *loop2MBB =
10511     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10512   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10513   F->insert(It, loopMBB);
10514   if (CmpOpcode)
10515     F->insert(It, loop2MBB);
10516   F->insert(It, exitMBB);
10517   exitMBB->splice(exitMBB->begin(), BB,
10518                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10519   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10520 
10521   MachineRegisterInfo &RegInfo = F->getRegInfo();
10522   Register TmpReg = (!BinOpcode) ? incr :
10523     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10524                                            : &PPC::GPRCRegClass);
10525 
10526   //  thisMBB:
10527   //   ...
10528   //   fallthrough --> loopMBB
10529   BB->addSuccessor(loopMBB);
10530 
10531   //  loopMBB:
10532   //   l[wd]arx dest, ptr
10533   //   add r0, dest, incr
10534   //   st[wd]cx. r0, ptr
10535   //   bne- loopMBB
10536   //   fallthrough --> exitMBB
10537 
10538   // For max/min...
10539   //  loopMBB:
10540   //   l[wd]arx dest, ptr
10541   //   cmpl?[wd] incr, dest
10542   //   bgt exitMBB
10543   //  loop2MBB:
10544   //   st[wd]cx. dest, ptr
10545   //   bne- loopMBB
10546   //   fallthrough --> exitMBB
10547 
10548   BB = loopMBB;
10549   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10550     .addReg(ptrA).addReg(ptrB);
10551   if (BinOpcode)
10552     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10553   if (CmpOpcode) {
10554     // Signed comparisons of byte or halfword values must be sign-extended.
10555     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10556       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10557       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10558               ExtReg).addReg(dest);
10559       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10560         .addReg(incr).addReg(ExtReg);
10561     } else
10562       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10563         .addReg(incr).addReg(dest);
10564 
10565     BuildMI(BB, dl, TII->get(PPC::BCC))
10566       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10567     BB->addSuccessor(loop2MBB);
10568     BB->addSuccessor(exitMBB);
10569     BB = loop2MBB;
10570   }
10571   BuildMI(BB, dl, TII->get(StoreMnemonic))
10572     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10573   BuildMI(BB, dl, TII->get(PPC::BCC))
10574     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10575   BB->addSuccessor(loopMBB);
10576   BB->addSuccessor(exitMBB);
10577 
10578   //  exitMBB:
10579   //   ...
10580   BB = exitMBB;
10581   return BB;
10582 }
10583 
10584 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10585     MachineInstr &MI, MachineBasicBlock *BB,
10586     bool is8bit, // operation
10587     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10588   // If we support part-word atomic mnemonics, just use them
10589   if (Subtarget.hasPartwordAtomics())
10590     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10591                             CmpPred);
10592 
10593   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10594   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10595   // In 64 bit mode we have to use 64 bits for addresses, even though the
10596   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10597   // registers without caring whether they're 32 or 64, but here we're
10598   // doing actual arithmetic on the addresses.
10599   bool is64bit = Subtarget.isPPC64();
10600   bool isLittleEndian = Subtarget.isLittleEndian();
10601   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10602 
10603   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10604   MachineFunction *F = BB->getParent();
10605   MachineFunction::iterator It = ++BB->getIterator();
10606 
10607   Register dest = MI.getOperand(0).getReg();
10608   Register ptrA = MI.getOperand(1).getReg();
10609   Register ptrB = MI.getOperand(2).getReg();
10610   Register incr = MI.getOperand(3).getReg();
10611   DebugLoc dl = MI.getDebugLoc();
10612 
10613   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10614   MachineBasicBlock *loop2MBB =
10615       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10616   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10617   F->insert(It, loopMBB);
10618   if (CmpOpcode)
10619     F->insert(It, loop2MBB);
10620   F->insert(It, exitMBB);
10621   exitMBB->splice(exitMBB->begin(), BB,
10622                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10623   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10624 
10625   MachineRegisterInfo &RegInfo = F->getRegInfo();
10626   const TargetRegisterClass *RC =
10627       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10628   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10629 
10630   Register PtrReg = RegInfo.createVirtualRegister(RC);
10631   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10632   Register ShiftReg =
10633       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10634   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10635   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10636   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10637   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10638   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10639   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10640   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10641   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10642   Register Ptr1Reg;
10643   Register TmpReg =
10644       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10645 
10646   //  thisMBB:
10647   //   ...
10648   //   fallthrough --> loopMBB
10649   BB->addSuccessor(loopMBB);
10650 
10651   // The 4-byte load must be aligned, while a char or short may be
10652   // anywhere in the word.  Hence all this nasty bookkeeping code.
10653   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10654   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10655   //   xori shift, shift1, 24 [16]
10656   //   rlwinm ptr, ptr1, 0, 0, 29
10657   //   slw incr2, incr, shift
10658   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10659   //   slw mask, mask2, shift
10660   //  loopMBB:
10661   //   lwarx tmpDest, ptr
10662   //   add tmp, tmpDest, incr2
10663   //   andc tmp2, tmpDest, mask
10664   //   and tmp3, tmp, mask
10665   //   or tmp4, tmp3, tmp2
10666   //   stwcx. tmp4, ptr
10667   //   bne- loopMBB
10668   //   fallthrough --> exitMBB
10669   //   srw dest, tmpDest, shift
10670   if (ptrA != ZeroReg) {
10671     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10672     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10673         .addReg(ptrA)
10674         .addReg(ptrB);
10675   } else {
10676     Ptr1Reg = ptrB;
10677   }
10678   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10679   // mode.
10680   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10681       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10682       .addImm(3)
10683       .addImm(27)
10684       .addImm(is8bit ? 28 : 27);
10685   if (!isLittleEndian)
10686     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10687         .addReg(Shift1Reg)
10688         .addImm(is8bit ? 24 : 16);
10689   if (is64bit)
10690     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10691         .addReg(Ptr1Reg)
10692         .addImm(0)
10693         .addImm(61);
10694   else
10695     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10696         .addReg(Ptr1Reg)
10697         .addImm(0)
10698         .addImm(0)
10699         .addImm(29);
10700   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10701   if (is8bit)
10702     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10703   else {
10704     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10705     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10706         .addReg(Mask3Reg)
10707         .addImm(65535);
10708   }
10709   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10710       .addReg(Mask2Reg)
10711       .addReg(ShiftReg);
10712 
10713   BB = loopMBB;
10714   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10715       .addReg(ZeroReg)
10716       .addReg(PtrReg);
10717   if (BinOpcode)
10718     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10719         .addReg(Incr2Reg)
10720         .addReg(TmpDestReg);
10721   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10722       .addReg(TmpDestReg)
10723       .addReg(MaskReg);
10724   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10725   if (CmpOpcode) {
10726     // For unsigned comparisons, we can directly compare the shifted values.
10727     // For signed comparisons we shift and sign extend.
10728     Register SReg = RegInfo.createVirtualRegister(GPRC);
10729     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10730         .addReg(TmpDestReg)
10731         .addReg(MaskReg);
10732     unsigned ValueReg = SReg;
10733     unsigned CmpReg = Incr2Reg;
10734     if (CmpOpcode == PPC::CMPW) {
10735       ValueReg = RegInfo.createVirtualRegister(GPRC);
10736       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10737           .addReg(SReg)
10738           .addReg(ShiftReg);
10739       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10740       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10741           .addReg(ValueReg);
10742       ValueReg = ValueSReg;
10743       CmpReg = incr;
10744     }
10745     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10746         .addReg(CmpReg)
10747         .addReg(ValueReg);
10748     BuildMI(BB, dl, TII->get(PPC::BCC))
10749         .addImm(CmpPred)
10750         .addReg(PPC::CR0)
10751         .addMBB(exitMBB);
10752     BB->addSuccessor(loop2MBB);
10753     BB->addSuccessor(exitMBB);
10754     BB = loop2MBB;
10755   }
10756   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10757   BuildMI(BB, dl, TII->get(PPC::STWCX))
10758       .addReg(Tmp4Reg)
10759       .addReg(ZeroReg)
10760       .addReg(PtrReg);
10761   BuildMI(BB, dl, TII->get(PPC::BCC))
10762       .addImm(PPC::PRED_NE)
10763       .addReg(PPC::CR0)
10764       .addMBB(loopMBB);
10765   BB->addSuccessor(loopMBB);
10766   BB->addSuccessor(exitMBB);
10767 
10768   //  exitMBB:
10769   //   ...
10770   BB = exitMBB;
10771   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10772       .addReg(TmpDestReg)
10773       .addReg(ShiftReg);
10774   return BB;
10775 }
10776 
10777 llvm::MachineBasicBlock *
10778 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10779                                     MachineBasicBlock *MBB) const {
10780   DebugLoc DL = MI.getDebugLoc();
10781   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10782   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10783 
10784   MachineFunction *MF = MBB->getParent();
10785   MachineRegisterInfo &MRI = MF->getRegInfo();
10786 
10787   const BasicBlock *BB = MBB->getBasicBlock();
10788   MachineFunction::iterator I = ++MBB->getIterator();
10789 
10790   Register DstReg = MI.getOperand(0).getReg();
10791   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10792   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10793   Register mainDstReg = MRI.createVirtualRegister(RC);
10794   Register restoreDstReg = MRI.createVirtualRegister(RC);
10795 
10796   MVT PVT = getPointerTy(MF->getDataLayout());
10797   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10798          "Invalid Pointer Size!");
10799   // For v = setjmp(buf), we generate
10800   //
10801   // thisMBB:
10802   //  SjLjSetup mainMBB
10803   //  bl mainMBB
10804   //  v_restore = 1
10805   //  b sinkMBB
10806   //
10807   // mainMBB:
10808   //  buf[LabelOffset] = LR
10809   //  v_main = 0
10810   //
10811   // sinkMBB:
10812   //  v = phi(main, restore)
10813   //
10814 
10815   MachineBasicBlock *thisMBB = MBB;
10816   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10817   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10818   MF->insert(I, mainMBB);
10819   MF->insert(I, sinkMBB);
10820 
10821   MachineInstrBuilder MIB;
10822 
10823   // Transfer the remainder of BB and its successor edges to sinkMBB.
10824   sinkMBB->splice(sinkMBB->begin(), MBB,
10825                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10826   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10827 
10828   // Note that the structure of the jmp_buf used here is not compatible
10829   // with that used by libc, and is not designed to be. Specifically, it
10830   // stores only those 'reserved' registers that LLVM does not otherwise
10831   // understand how to spill. Also, by convention, by the time this
10832   // intrinsic is called, Clang has already stored the frame address in the
10833   // first slot of the buffer and stack address in the third. Following the
10834   // X86 target code, we'll store the jump address in the second slot. We also
10835   // need to save the TOC pointer (R2) to handle jumps between shared
10836   // libraries, and that will be stored in the fourth slot. The thread
10837   // identifier (R13) is not affected.
10838 
10839   // thisMBB:
10840   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10841   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10842   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10843 
10844   // Prepare IP either in reg.
10845   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10846   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10847   Register BufReg = MI.getOperand(1).getReg();
10848 
10849   if (Subtarget.is64BitELFABI()) {
10850     setUsesTOCBasePtr(*MBB->getParent());
10851     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10852               .addReg(PPC::X2)
10853               .addImm(TOCOffset)
10854               .addReg(BufReg)
10855               .cloneMemRefs(MI);
10856   }
10857 
10858   // Naked functions never have a base pointer, and so we use r1. For all
10859   // other functions, this decision must be delayed until during PEI.
10860   unsigned BaseReg;
10861   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10862     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10863   else
10864     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10865 
10866   MIB = BuildMI(*thisMBB, MI, DL,
10867                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10868             .addReg(BaseReg)
10869             .addImm(BPOffset)
10870             .addReg(BufReg)
10871             .cloneMemRefs(MI);
10872 
10873   // Setup
10874   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10875   MIB.addRegMask(TRI->getNoPreservedMask());
10876 
10877   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10878 
10879   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10880           .addMBB(mainMBB);
10881   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10882 
10883   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10884   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10885 
10886   // mainMBB:
10887   //  mainDstReg = 0
10888   MIB =
10889       BuildMI(mainMBB, DL,
10890               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10891 
10892   // Store IP
10893   if (Subtarget.isPPC64()) {
10894     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10895             .addReg(LabelReg)
10896             .addImm(LabelOffset)
10897             .addReg(BufReg);
10898   } else {
10899     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10900             .addReg(LabelReg)
10901             .addImm(LabelOffset)
10902             .addReg(BufReg);
10903   }
10904   MIB.cloneMemRefs(MI);
10905 
10906   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10907   mainMBB->addSuccessor(sinkMBB);
10908 
10909   // sinkMBB:
10910   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10911           TII->get(PPC::PHI), DstReg)
10912     .addReg(mainDstReg).addMBB(mainMBB)
10913     .addReg(restoreDstReg).addMBB(thisMBB);
10914 
10915   MI.eraseFromParent();
10916   return sinkMBB;
10917 }
10918 
10919 MachineBasicBlock *
10920 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10921                                      MachineBasicBlock *MBB) const {
10922   DebugLoc DL = MI.getDebugLoc();
10923   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10924 
10925   MachineFunction *MF = MBB->getParent();
10926   MachineRegisterInfo &MRI = MF->getRegInfo();
10927 
10928   MVT PVT = getPointerTy(MF->getDataLayout());
10929   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10930          "Invalid Pointer Size!");
10931 
10932   const TargetRegisterClass *RC =
10933     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10934   Register Tmp = MRI.createVirtualRegister(RC);
10935   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10936   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10937   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10938   unsigned BP =
10939       (PVT == MVT::i64)
10940           ? PPC::X30
10941           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10942                                                               : PPC::R30);
10943 
10944   MachineInstrBuilder MIB;
10945 
10946   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10947   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10948   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10949   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10950 
10951   Register BufReg = MI.getOperand(0).getReg();
10952 
10953   // Reload FP (the jumped-to function may not have had a
10954   // frame pointer, and if so, then its r31 will be restored
10955   // as necessary).
10956   if (PVT == MVT::i64) {
10957     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10958             .addImm(0)
10959             .addReg(BufReg);
10960   } else {
10961     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10962             .addImm(0)
10963             .addReg(BufReg);
10964   }
10965   MIB.cloneMemRefs(MI);
10966 
10967   // Reload IP
10968   if (PVT == MVT::i64) {
10969     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10970             .addImm(LabelOffset)
10971             .addReg(BufReg);
10972   } else {
10973     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10974             .addImm(LabelOffset)
10975             .addReg(BufReg);
10976   }
10977   MIB.cloneMemRefs(MI);
10978 
10979   // Reload SP
10980   if (PVT == MVT::i64) {
10981     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10982             .addImm(SPOffset)
10983             .addReg(BufReg);
10984   } else {
10985     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10986             .addImm(SPOffset)
10987             .addReg(BufReg);
10988   }
10989   MIB.cloneMemRefs(MI);
10990 
10991   // Reload BP
10992   if (PVT == MVT::i64) {
10993     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10994             .addImm(BPOffset)
10995             .addReg(BufReg);
10996   } else {
10997     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10998             .addImm(BPOffset)
10999             .addReg(BufReg);
11000   }
11001   MIB.cloneMemRefs(MI);
11002 
11003   // Reload TOC
11004   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11005     setUsesTOCBasePtr(*MBB->getParent());
11006     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11007               .addImm(TOCOffset)
11008               .addReg(BufReg)
11009               .cloneMemRefs(MI);
11010   }
11011 
11012   // Jump
11013   BuildMI(*MBB, MI, DL,
11014           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11015   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11016 
11017   MI.eraseFromParent();
11018   return MBB;
11019 }
11020 
11021 MachineBasicBlock *
11022 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11023                                                MachineBasicBlock *BB) const {
11024   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11025       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11026     if (Subtarget.is64BitELFABI() &&
11027         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11028       // Call lowering should have added an r2 operand to indicate a dependence
11029       // on the TOC base pointer value. It can't however, because there is no
11030       // way to mark the dependence as implicit there, and so the stackmap code
11031       // will confuse it with a regular operand. Instead, add the dependence
11032       // here.
11033       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11034     }
11035 
11036     return emitPatchPoint(MI, BB);
11037   }
11038 
11039   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11040       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11041     return emitEHSjLjSetJmp(MI, BB);
11042   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11043              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11044     return emitEHSjLjLongJmp(MI, BB);
11045   }
11046 
11047   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11048 
11049   // To "insert" these instructions we actually have to insert their
11050   // control-flow patterns.
11051   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11052   MachineFunction::iterator It = ++BB->getIterator();
11053 
11054   MachineFunction *F = BB->getParent();
11055 
11056   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11057       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11058       MI.getOpcode() == PPC::SELECT_I8) {
11059     SmallVector<MachineOperand, 2> Cond;
11060     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11061         MI.getOpcode() == PPC::SELECT_CC_I8)
11062       Cond.push_back(MI.getOperand(4));
11063     else
11064       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11065     Cond.push_back(MI.getOperand(1));
11066 
11067     DebugLoc dl = MI.getDebugLoc();
11068     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11069                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11070   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11071              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11072              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11073              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11074              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11075              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11076              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11077              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11078              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11079              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11080              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11081              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11082              MI.getOpcode() == PPC::SELECT_F4 ||
11083              MI.getOpcode() == PPC::SELECT_F8 ||
11084              MI.getOpcode() == PPC::SELECT_F16 ||
11085              MI.getOpcode() == PPC::SELECT_QFRC ||
11086              MI.getOpcode() == PPC::SELECT_QSRC ||
11087              MI.getOpcode() == PPC::SELECT_QBRC ||
11088              MI.getOpcode() == PPC::SELECT_SPE ||
11089              MI.getOpcode() == PPC::SELECT_SPE4 ||
11090              MI.getOpcode() == PPC::SELECT_VRRC ||
11091              MI.getOpcode() == PPC::SELECT_VSFRC ||
11092              MI.getOpcode() == PPC::SELECT_VSSRC ||
11093              MI.getOpcode() == PPC::SELECT_VSRC) {
11094     // The incoming instruction knows the destination vreg to set, the
11095     // condition code register to branch on, the true/false values to
11096     // select between, and a branch opcode to use.
11097 
11098     //  thisMBB:
11099     //  ...
11100     //   TrueVal = ...
11101     //   cmpTY ccX, r1, r2
11102     //   bCC copy1MBB
11103     //   fallthrough --> copy0MBB
11104     MachineBasicBlock *thisMBB = BB;
11105     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11106     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11107     DebugLoc dl = MI.getDebugLoc();
11108     F->insert(It, copy0MBB);
11109     F->insert(It, sinkMBB);
11110 
11111     // Transfer the remainder of BB and its successor edges to sinkMBB.
11112     sinkMBB->splice(sinkMBB->begin(), BB,
11113                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11114     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11115 
11116     // Next, add the true and fallthrough blocks as its successors.
11117     BB->addSuccessor(copy0MBB);
11118     BB->addSuccessor(sinkMBB);
11119 
11120     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11121         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11122         MI.getOpcode() == PPC::SELECT_F16 ||
11123         MI.getOpcode() == PPC::SELECT_SPE4 ||
11124         MI.getOpcode() == PPC::SELECT_SPE ||
11125         MI.getOpcode() == PPC::SELECT_QFRC ||
11126         MI.getOpcode() == PPC::SELECT_QSRC ||
11127         MI.getOpcode() == PPC::SELECT_QBRC ||
11128         MI.getOpcode() == PPC::SELECT_VRRC ||
11129         MI.getOpcode() == PPC::SELECT_VSFRC ||
11130         MI.getOpcode() == PPC::SELECT_VSSRC ||
11131         MI.getOpcode() == PPC::SELECT_VSRC) {
11132       BuildMI(BB, dl, TII->get(PPC::BC))
11133           .addReg(MI.getOperand(1).getReg())
11134           .addMBB(sinkMBB);
11135     } else {
11136       unsigned SelectPred = MI.getOperand(4).getImm();
11137       BuildMI(BB, dl, TII->get(PPC::BCC))
11138           .addImm(SelectPred)
11139           .addReg(MI.getOperand(1).getReg())
11140           .addMBB(sinkMBB);
11141     }
11142 
11143     //  copy0MBB:
11144     //   %FalseValue = ...
11145     //   # fallthrough to sinkMBB
11146     BB = copy0MBB;
11147 
11148     // Update machine-CFG edges
11149     BB->addSuccessor(sinkMBB);
11150 
11151     //  sinkMBB:
11152     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11153     //  ...
11154     BB = sinkMBB;
11155     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11156         .addReg(MI.getOperand(3).getReg())
11157         .addMBB(copy0MBB)
11158         .addReg(MI.getOperand(2).getReg())
11159         .addMBB(thisMBB);
11160   } else if (MI.getOpcode() == PPC::ReadTB) {
11161     // To read the 64-bit time-base register on a 32-bit target, we read the
11162     // two halves. Should the counter have wrapped while it was being read, we
11163     // need to try again.
11164     // ...
11165     // readLoop:
11166     // mfspr Rx,TBU # load from TBU
11167     // mfspr Ry,TB  # load from TB
11168     // mfspr Rz,TBU # load from TBU
11169     // cmpw crX,Rx,Rz # check if 'old'='new'
11170     // bne readLoop   # branch if they're not equal
11171     // ...
11172 
11173     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11174     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11175     DebugLoc dl = MI.getDebugLoc();
11176     F->insert(It, readMBB);
11177     F->insert(It, sinkMBB);
11178 
11179     // Transfer the remainder of BB and its successor edges to sinkMBB.
11180     sinkMBB->splice(sinkMBB->begin(), BB,
11181                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11182     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11183 
11184     BB->addSuccessor(readMBB);
11185     BB = readMBB;
11186 
11187     MachineRegisterInfo &RegInfo = F->getRegInfo();
11188     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11189     Register LoReg = MI.getOperand(0).getReg();
11190     Register HiReg = MI.getOperand(1).getReg();
11191 
11192     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11193     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11194     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11195 
11196     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11197 
11198     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11199         .addReg(HiReg)
11200         .addReg(ReadAgainReg);
11201     BuildMI(BB, dl, TII->get(PPC::BCC))
11202         .addImm(PPC::PRED_NE)
11203         .addReg(CmpReg)
11204         .addMBB(readMBB);
11205 
11206     BB->addSuccessor(readMBB);
11207     BB->addSuccessor(sinkMBB);
11208   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11209     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11210   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11211     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11212   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11213     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11214   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11215     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11216 
11217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11218     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11219   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11220     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11221   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11222     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11223   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11224     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11225 
11226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11227     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11228   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11229     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11230   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11231     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11232   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11233     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11234 
11235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11236     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11237   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11238     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11239   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11240     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11241   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11242     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11243 
11244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11245     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11246   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11247     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11248   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11249     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11250   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11251     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11252 
11253   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11254     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11255   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11256     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11257   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11258     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11259   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11260     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11261 
11262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11263     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11264   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11265     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11266   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11267     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11268   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11269     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11270 
11271   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11272     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11273   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11274     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11275   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11276     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11277   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11278     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11279 
11280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11281     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11282   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11283     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11284   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11285     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11286   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11287     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11288 
11289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11290     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11291   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11292     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11293   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11294     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11295   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11296     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11297 
11298   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11299     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11300   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11301     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11302   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11303     BB = EmitAtomicBinary(MI, BB, 4, 0);
11304   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11305     BB = EmitAtomicBinary(MI, BB, 8, 0);
11306   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11307            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11308            (Subtarget.hasPartwordAtomics() &&
11309             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11310            (Subtarget.hasPartwordAtomics() &&
11311             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11312     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11313 
11314     auto LoadMnemonic = PPC::LDARX;
11315     auto StoreMnemonic = PPC::STDCX;
11316     switch (MI.getOpcode()) {
11317     default:
11318       llvm_unreachable("Compare and swap of unknown size");
11319     case PPC::ATOMIC_CMP_SWAP_I8:
11320       LoadMnemonic = PPC::LBARX;
11321       StoreMnemonic = PPC::STBCX;
11322       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11323       break;
11324     case PPC::ATOMIC_CMP_SWAP_I16:
11325       LoadMnemonic = PPC::LHARX;
11326       StoreMnemonic = PPC::STHCX;
11327       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11328       break;
11329     case PPC::ATOMIC_CMP_SWAP_I32:
11330       LoadMnemonic = PPC::LWARX;
11331       StoreMnemonic = PPC::STWCX;
11332       break;
11333     case PPC::ATOMIC_CMP_SWAP_I64:
11334       LoadMnemonic = PPC::LDARX;
11335       StoreMnemonic = PPC::STDCX;
11336       break;
11337     }
11338     Register dest = MI.getOperand(0).getReg();
11339     Register ptrA = MI.getOperand(1).getReg();
11340     Register ptrB = MI.getOperand(2).getReg();
11341     Register oldval = MI.getOperand(3).getReg();
11342     Register newval = MI.getOperand(4).getReg();
11343     DebugLoc dl = MI.getDebugLoc();
11344 
11345     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11346     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11347     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11348     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11349     F->insert(It, loop1MBB);
11350     F->insert(It, loop2MBB);
11351     F->insert(It, midMBB);
11352     F->insert(It, exitMBB);
11353     exitMBB->splice(exitMBB->begin(), BB,
11354                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11355     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11356 
11357     //  thisMBB:
11358     //   ...
11359     //   fallthrough --> loopMBB
11360     BB->addSuccessor(loop1MBB);
11361 
11362     // loop1MBB:
11363     //   l[bhwd]arx dest, ptr
11364     //   cmp[wd] dest, oldval
11365     //   bne- midMBB
11366     // loop2MBB:
11367     //   st[bhwd]cx. newval, ptr
11368     //   bne- loopMBB
11369     //   b exitBB
11370     // midMBB:
11371     //   st[bhwd]cx. dest, ptr
11372     // exitBB:
11373     BB = loop1MBB;
11374     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11375     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11376         .addReg(oldval)
11377         .addReg(dest);
11378     BuildMI(BB, dl, TII->get(PPC::BCC))
11379         .addImm(PPC::PRED_NE)
11380         .addReg(PPC::CR0)
11381         .addMBB(midMBB);
11382     BB->addSuccessor(loop2MBB);
11383     BB->addSuccessor(midMBB);
11384 
11385     BB = loop2MBB;
11386     BuildMI(BB, dl, TII->get(StoreMnemonic))
11387         .addReg(newval)
11388         .addReg(ptrA)
11389         .addReg(ptrB);
11390     BuildMI(BB, dl, TII->get(PPC::BCC))
11391         .addImm(PPC::PRED_NE)
11392         .addReg(PPC::CR0)
11393         .addMBB(loop1MBB);
11394     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11395     BB->addSuccessor(loop1MBB);
11396     BB->addSuccessor(exitMBB);
11397 
11398     BB = midMBB;
11399     BuildMI(BB, dl, TII->get(StoreMnemonic))
11400         .addReg(dest)
11401         .addReg(ptrA)
11402         .addReg(ptrB);
11403     BB->addSuccessor(exitMBB);
11404 
11405     //  exitMBB:
11406     //   ...
11407     BB = exitMBB;
11408   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11409              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11410     // We must use 64-bit registers for addresses when targeting 64-bit,
11411     // since we're actually doing arithmetic on them.  Other registers
11412     // can be 32-bit.
11413     bool is64bit = Subtarget.isPPC64();
11414     bool isLittleEndian = Subtarget.isLittleEndian();
11415     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11416 
11417     Register dest = MI.getOperand(0).getReg();
11418     Register ptrA = MI.getOperand(1).getReg();
11419     Register ptrB = MI.getOperand(2).getReg();
11420     Register oldval = MI.getOperand(3).getReg();
11421     Register newval = MI.getOperand(4).getReg();
11422     DebugLoc dl = MI.getDebugLoc();
11423 
11424     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11425     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11426     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11427     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11428     F->insert(It, loop1MBB);
11429     F->insert(It, loop2MBB);
11430     F->insert(It, midMBB);
11431     F->insert(It, exitMBB);
11432     exitMBB->splice(exitMBB->begin(), BB,
11433                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11434     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11435 
11436     MachineRegisterInfo &RegInfo = F->getRegInfo();
11437     const TargetRegisterClass *RC =
11438         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11439     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11440 
11441     Register PtrReg = RegInfo.createVirtualRegister(RC);
11442     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11443     Register ShiftReg =
11444         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11445     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11446     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11447     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11448     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11449     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11450     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11451     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11452     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11453     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11454     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11455     Register Ptr1Reg;
11456     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11457     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11458     //  thisMBB:
11459     //   ...
11460     //   fallthrough --> loopMBB
11461     BB->addSuccessor(loop1MBB);
11462 
11463     // The 4-byte load must be aligned, while a char or short may be
11464     // anywhere in the word.  Hence all this nasty bookkeeping code.
11465     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11466     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11467     //   xori shift, shift1, 24 [16]
11468     //   rlwinm ptr, ptr1, 0, 0, 29
11469     //   slw newval2, newval, shift
11470     //   slw oldval2, oldval,shift
11471     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11472     //   slw mask, mask2, shift
11473     //   and newval3, newval2, mask
11474     //   and oldval3, oldval2, mask
11475     // loop1MBB:
11476     //   lwarx tmpDest, ptr
11477     //   and tmp, tmpDest, mask
11478     //   cmpw tmp, oldval3
11479     //   bne- midMBB
11480     // loop2MBB:
11481     //   andc tmp2, tmpDest, mask
11482     //   or tmp4, tmp2, newval3
11483     //   stwcx. tmp4, ptr
11484     //   bne- loop1MBB
11485     //   b exitBB
11486     // midMBB:
11487     //   stwcx. tmpDest, ptr
11488     // exitBB:
11489     //   srw dest, tmpDest, shift
11490     if (ptrA != ZeroReg) {
11491       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11492       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11493           .addReg(ptrA)
11494           .addReg(ptrB);
11495     } else {
11496       Ptr1Reg = ptrB;
11497     }
11498 
11499     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11500     // mode.
11501     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11502         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11503         .addImm(3)
11504         .addImm(27)
11505         .addImm(is8bit ? 28 : 27);
11506     if (!isLittleEndian)
11507       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11508           .addReg(Shift1Reg)
11509           .addImm(is8bit ? 24 : 16);
11510     if (is64bit)
11511       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11512           .addReg(Ptr1Reg)
11513           .addImm(0)
11514           .addImm(61);
11515     else
11516       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11517           .addReg(Ptr1Reg)
11518           .addImm(0)
11519           .addImm(0)
11520           .addImm(29);
11521     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11522         .addReg(newval)
11523         .addReg(ShiftReg);
11524     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11525         .addReg(oldval)
11526         .addReg(ShiftReg);
11527     if (is8bit)
11528       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11529     else {
11530       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11531       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11532           .addReg(Mask3Reg)
11533           .addImm(65535);
11534     }
11535     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11536         .addReg(Mask2Reg)
11537         .addReg(ShiftReg);
11538     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11539         .addReg(NewVal2Reg)
11540         .addReg(MaskReg);
11541     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11542         .addReg(OldVal2Reg)
11543         .addReg(MaskReg);
11544 
11545     BB = loop1MBB;
11546     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11547         .addReg(ZeroReg)
11548         .addReg(PtrReg);
11549     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11550         .addReg(TmpDestReg)
11551         .addReg(MaskReg);
11552     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11553         .addReg(TmpReg)
11554         .addReg(OldVal3Reg);
11555     BuildMI(BB, dl, TII->get(PPC::BCC))
11556         .addImm(PPC::PRED_NE)
11557         .addReg(PPC::CR0)
11558         .addMBB(midMBB);
11559     BB->addSuccessor(loop2MBB);
11560     BB->addSuccessor(midMBB);
11561 
11562     BB = loop2MBB;
11563     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11564         .addReg(TmpDestReg)
11565         .addReg(MaskReg);
11566     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11567         .addReg(Tmp2Reg)
11568         .addReg(NewVal3Reg);
11569     BuildMI(BB, dl, TII->get(PPC::STWCX))
11570         .addReg(Tmp4Reg)
11571         .addReg(ZeroReg)
11572         .addReg(PtrReg);
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(PPC::STWCX))
11583         .addReg(TmpDestReg)
11584         .addReg(ZeroReg)
11585         .addReg(PtrReg);
11586     BB->addSuccessor(exitMBB);
11587 
11588     //  exitMBB:
11589     //   ...
11590     BB = exitMBB;
11591     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11592         .addReg(TmpReg)
11593         .addReg(ShiftReg);
11594   } else if (MI.getOpcode() == PPC::FADDrtz) {
11595     // This pseudo performs an FADD with rounding mode temporarily forced
11596     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11597     // is not modeled at the SelectionDAG level.
11598     Register Dest = MI.getOperand(0).getReg();
11599     Register Src1 = MI.getOperand(1).getReg();
11600     Register Src2 = MI.getOperand(2).getReg();
11601     DebugLoc dl = MI.getDebugLoc();
11602 
11603     MachineRegisterInfo &RegInfo = F->getRegInfo();
11604     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11605 
11606     // Save FPSCR value.
11607     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11608 
11609     // Set rounding mode to round-to-zero.
11610     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11611     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11612 
11613     // Perform addition.
11614     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11615 
11616     // Restore FPSCR value.
11617     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11618   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11619              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11620              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11621              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11622     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11623                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11624                           ? PPC::ANDI8o
11625                           : PPC::ANDIo;
11626     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11627                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11628 
11629     MachineRegisterInfo &RegInfo = F->getRegInfo();
11630     Register Dest = RegInfo.createVirtualRegister(
11631         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11632 
11633     DebugLoc dl = MI.getDebugLoc();
11634     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11635         .addReg(MI.getOperand(1).getReg())
11636         .addImm(1);
11637     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11638             MI.getOperand(0).getReg())
11639         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11640   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11641     DebugLoc Dl = MI.getDebugLoc();
11642     MachineRegisterInfo &RegInfo = F->getRegInfo();
11643     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11644     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11645     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11646             MI.getOperand(0).getReg())
11647         .addReg(CRReg);
11648   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11649     DebugLoc Dl = MI.getDebugLoc();
11650     unsigned Imm = MI.getOperand(1).getImm();
11651     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11652     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11653             MI.getOperand(0).getReg())
11654         .addReg(PPC::CR0EQ);
11655   } else if (MI.getOpcode() == PPC::SETRNDi) {
11656     DebugLoc dl = MI.getDebugLoc();
11657     Register OldFPSCRReg = MI.getOperand(0).getReg();
11658 
11659     // Save FPSCR value.
11660     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11661 
11662     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11663     // the following settings:
11664     //   00 Round to nearest
11665     //   01 Round to 0
11666     //   10 Round to +inf
11667     //   11 Round to -inf
11668 
11669     // When the operand is immediate, using the two least significant bits of
11670     // the immediate to set the bits 62:63 of FPSCR.
11671     unsigned Mode = MI.getOperand(1).getImm();
11672     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11673       .addImm(31);
11674 
11675     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11676       .addImm(30);
11677   } else if (MI.getOpcode() == PPC::SETRND) {
11678     DebugLoc dl = MI.getDebugLoc();
11679 
11680     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11681     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11682     // If the target doesn't have DirectMove, we should use stack to do the
11683     // conversion, because the target doesn't have the instructions like mtvsrd
11684     // or mfvsrd to do this conversion directly.
11685     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11686       if (Subtarget.hasDirectMove()) {
11687         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11688           .addReg(SrcReg);
11689       } else {
11690         // Use stack to do the register copy.
11691         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11692         MachineRegisterInfo &RegInfo = F->getRegInfo();
11693         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11694         if (RC == &PPC::F8RCRegClass) {
11695           // Copy register from F8RCRegClass to G8RCRegclass.
11696           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11697                  "Unsupported RegClass.");
11698 
11699           StoreOp = PPC::STFD;
11700           LoadOp = PPC::LD;
11701         } else {
11702           // Copy register from G8RCRegClass to F8RCRegclass.
11703           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11704                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11705                  "Unsupported RegClass.");
11706         }
11707 
11708         MachineFrameInfo &MFI = F->getFrameInfo();
11709         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11710 
11711         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11712           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11713           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11714           MFI.getObjectAlignment(FrameIdx));
11715 
11716         // Store the SrcReg into the stack.
11717         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11718           .addReg(SrcReg)
11719           .addImm(0)
11720           .addFrameIndex(FrameIdx)
11721           .addMemOperand(MMOStore);
11722 
11723         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11724           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11725           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11726           MFI.getObjectAlignment(FrameIdx));
11727 
11728         // Load from the stack where SrcReg is stored, and save to DestReg,
11729         // so we have done the RegClass conversion from RegClass::SrcReg to
11730         // RegClass::DestReg.
11731         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11732           .addImm(0)
11733           .addFrameIndex(FrameIdx)
11734           .addMemOperand(MMOLoad);
11735       }
11736     };
11737 
11738     Register OldFPSCRReg = MI.getOperand(0).getReg();
11739 
11740     // Save FPSCR value.
11741     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11742 
11743     // When the operand is gprc register, use two least significant bits of the
11744     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11745     //
11746     // copy OldFPSCRTmpReg, OldFPSCRReg
11747     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11748     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11749     // copy NewFPSCRReg, NewFPSCRTmpReg
11750     // mtfsf 255, NewFPSCRReg
11751     MachineOperand SrcOp = MI.getOperand(1);
11752     MachineRegisterInfo &RegInfo = F->getRegInfo();
11753     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11754 
11755     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11756 
11757     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11758     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11759 
11760     // The first operand of INSERT_SUBREG should be a register which has
11761     // subregisters, we only care about its RegClass, so we should use an
11762     // IMPLICIT_DEF register.
11763     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11764     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11765       .addReg(ImDefReg)
11766       .add(SrcOp)
11767       .addImm(1);
11768 
11769     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11770     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11771       .addReg(OldFPSCRTmpReg)
11772       .addReg(ExtSrcReg)
11773       .addImm(0)
11774       .addImm(62);
11775 
11776     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11777     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11778 
11779     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11780     // bits of FPSCR.
11781     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11782       .addImm(255)
11783       .addReg(NewFPSCRReg)
11784       .addImm(0)
11785       .addImm(0);
11786   } else {
11787     llvm_unreachable("Unexpected instr type to insert");
11788   }
11789 
11790   MI.eraseFromParent(); // The pseudo instruction is gone now.
11791   return BB;
11792 }
11793 
11794 //===----------------------------------------------------------------------===//
11795 // Target Optimization Hooks
11796 //===----------------------------------------------------------------------===//
11797 
11798 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11799   // For the estimates, convergence is quadratic, so we essentially double the
11800   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11801   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11802   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11803   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11804   if (VT.getScalarType() == MVT::f64)
11805     RefinementSteps++;
11806   return RefinementSteps;
11807 }
11808 
11809 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11810                                            int Enabled, int &RefinementSteps,
11811                                            bool &UseOneConstNR,
11812                                            bool Reciprocal) const {
11813   EVT VT = Operand.getValueType();
11814   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11815       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11816       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11817       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11818       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11819       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11820     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11821       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11822 
11823     // The Newton-Raphson computation with a single constant does not provide
11824     // enough accuracy on some CPUs.
11825     UseOneConstNR = !Subtarget.needsTwoConstNR();
11826     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11827   }
11828   return SDValue();
11829 }
11830 
11831 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11832                                             int Enabled,
11833                                             int &RefinementSteps) const {
11834   EVT VT = Operand.getValueType();
11835   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11836       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11837       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11838       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11839       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11840       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11841     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11842       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11843     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11844   }
11845   return SDValue();
11846 }
11847 
11848 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11849   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11850   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11851   // enabled for division), this functionality is redundant with the default
11852   // combiner logic (once the division -> reciprocal/multiply transformation
11853   // has taken place). As a result, this matters more for older cores than for
11854   // newer ones.
11855 
11856   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11857   // reciprocal if there are two or more FDIVs (for embedded cores with only
11858   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11859   switch (Subtarget.getCPUDirective()) {
11860   default:
11861     return 3;
11862   case PPC::DIR_440:
11863   case PPC::DIR_A2:
11864   case PPC::DIR_E500:
11865   case PPC::DIR_E500mc:
11866   case PPC::DIR_E5500:
11867     return 2;
11868   }
11869 }
11870 
11871 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11872 // collapsed, and so we need to look through chains of them.
11873 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11874                                      int64_t& Offset, SelectionDAG &DAG) {
11875   if (DAG.isBaseWithConstantOffset(Loc)) {
11876     Base = Loc.getOperand(0);
11877     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11878 
11879     // The base might itself be a base plus an offset, and if so, accumulate
11880     // that as well.
11881     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11882   }
11883 }
11884 
11885 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11886                             unsigned Bytes, int Dist,
11887                             SelectionDAG &DAG) {
11888   if (VT.getSizeInBits() / 8 != Bytes)
11889     return false;
11890 
11891   SDValue BaseLoc = Base->getBasePtr();
11892   if (Loc.getOpcode() == ISD::FrameIndex) {
11893     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11894       return false;
11895     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11896     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11897     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11898     int FS  = MFI.getObjectSize(FI);
11899     int BFS = MFI.getObjectSize(BFI);
11900     if (FS != BFS || FS != (int)Bytes) return false;
11901     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11902   }
11903 
11904   SDValue Base1 = Loc, Base2 = BaseLoc;
11905   int64_t Offset1 = 0, Offset2 = 0;
11906   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11907   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11908   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11909     return true;
11910 
11911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11912   const GlobalValue *GV1 = nullptr;
11913   const GlobalValue *GV2 = nullptr;
11914   Offset1 = 0;
11915   Offset2 = 0;
11916   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11917   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11918   if (isGA1 && isGA2 && GV1 == GV2)
11919     return Offset1 == (Offset2 + Dist*Bytes);
11920   return false;
11921 }
11922 
11923 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11924 // not enforce equality of the chain operands.
11925 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11926                             unsigned Bytes, int Dist,
11927                             SelectionDAG &DAG) {
11928   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11929     EVT VT = LS->getMemoryVT();
11930     SDValue Loc = LS->getBasePtr();
11931     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11932   }
11933 
11934   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11935     EVT VT;
11936     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11937     default: return false;
11938     case Intrinsic::ppc_qpx_qvlfd:
11939     case Intrinsic::ppc_qpx_qvlfda:
11940       VT = MVT::v4f64;
11941       break;
11942     case Intrinsic::ppc_qpx_qvlfs:
11943     case Intrinsic::ppc_qpx_qvlfsa:
11944       VT = MVT::v4f32;
11945       break;
11946     case Intrinsic::ppc_qpx_qvlfcd:
11947     case Intrinsic::ppc_qpx_qvlfcda:
11948       VT = MVT::v2f64;
11949       break;
11950     case Intrinsic::ppc_qpx_qvlfcs:
11951     case Intrinsic::ppc_qpx_qvlfcsa:
11952       VT = MVT::v2f32;
11953       break;
11954     case Intrinsic::ppc_qpx_qvlfiwa:
11955     case Intrinsic::ppc_qpx_qvlfiwz:
11956     case Intrinsic::ppc_altivec_lvx:
11957     case Intrinsic::ppc_altivec_lvxl:
11958     case Intrinsic::ppc_vsx_lxvw4x:
11959     case Intrinsic::ppc_vsx_lxvw4x_be:
11960       VT = MVT::v4i32;
11961       break;
11962     case Intrinsic::ppc_vsx_lxvd2x:
11963     case Intrinsic::ppc_vsx_lxvd2x_be:
11964       VT = MVT::v2f64;
11965       break;
11966     case Intrinsic::ppc_altivec_lvebx:
11967       VT = MVT::i8;
11968       break;
11969     case Intrinsic::ppc_altivec_lvehx:
11970       VT = MVT::i16;
11971       break;
11972     case Intrinsic::ppc_altivec_lvewx:
11973       VT = MVT::i32;
11974       break;
11975     }
11976 
11977     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11978   }
11979 
11980   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11981     EVT VT;
11982     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11983     default: return false;
11984     case Intrinsic::ppc_qpx_qvstfd:
11985     case Intrinsic::ppc_qpx_qvstfda:
11986       VT = MVT::v4f64;
11987       break;
11988     case Intrinsic::ppc_qpx_qvstfs:
11989     case Intrinsic::ppc_qpx_qvstfsa:
11990       VT = MVT::v4f32;
11991       break;
11992     case Intrinsic::ppc_qpx_qvstfcd:
11993     case Intrinsic::ppc_qpx_qvstfcda:
11994       VT = MVT::v2f64;
11995       break;
11996     case Intrinsic::ppc_qpx_qvstfcs:
11997     case Intrinsic::ppc_qpx_qvstfcsa:
11998       VT = MVT::v2f32;
11999       break;
12000     case Intrinsic::ppc_qpx_qvstfiw:
12001     case Intrinsic::ppc_qpx_qvstfiwa:
12002     case Intrinsic::ppc_altivec_stvx:
12003     case Intrinsic::ppc_altivec_stvxl:
12004     case Intrinsic::ppc_vsx_stxvw4x:
12005       VT = MVT::v4i32;
12006       break;
12007     case Intrinsic::ppc_vsx_stxvd2x:
12008       VT = MVT::v2f64;
12009       break;
12010     case Intrinsic::ppc_vsx_stxvw4x_be:
12011       VT = MVT::v4i32;
12012       break;
12013     case Intrinsic::ppc_vsx_stxvd2x_be:
12014       VT = MVT::v2f64;
12015       break;
12016     case Intrinsic::ppc_altivec_stvebx:
12017       VT = MVT::i8;
12018       break;
12019     case Intrinsic::ppc_altivec_stvehx:
12020       VT = MVT::i16;
12021       break;
12022     case Intrinsic::ppc_altivec_stvewx:
12023       VT = MVT::i32;
12024       break;
12025     }
12026 
12027     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12028   }
12029 
12030   return false;
12031 }
12032 
12033 // Return true is there is a nearyby consecutive load to the one provided
12034 // (regardless of alignment). We search up and down the chain, looking though
12035 // token factors and other loads (but nothing else). As a result, a true result
12036 // indicates that it is safe to create a new consecutive load adjacent to the
12037 // load provided.
12038 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12039   SDValue Chain = LD->getChain();
12040   EVT VT = LD->getMemoryVT();
12041 
12042   SmallSet<SDNode *, 16> LoadRoots;
12043   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12044   SmallSet<SDNode *, 16> Visited;
12045 
12046   // First, search up the chain, branching to follow all token-factor operands.
12047   // If we find a consecutive load, then we're done, otherwise, record all
12048   // nodes just above the top-level loads and token factors.
12049   while (!Queue.empty()) {
12050     SDNode *ChainNext = Queue.pop_back_val();
12051     if (!Visited.insert(ChainNext).second)
12052       continue;
12053 
12054     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12055       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12056         return true;
12057 
12058       if (!Visited.count(ChainLD->getChain().getNode()))
12059         Queue.push_back(ChainLD->getChain().getNode());
12060     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12061       for (const SDUse &O : ChainNext->ops())
12062         if (!Visited.count(O.getNode()))
12063           Queue.push_back(O.getNode());
12064     } else
12065       LoadRoots.insert(ChainNext);
12066   }
12067 
12068   // Second, search down the chain, starting from the top-level nodes recorded
12069   // in the first phase. These top-level nodes are the nodes just above all
12070   // loads and token factors. Starting with their uses, recursively look though
12071   // all loads (just the chain uses) and token factors to find a consecutive
12072   // load.
12073   Visited.clear();
12074   Queue.clear();
12075 
12076   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12077        IE = LoadRoots.end(); I != IE; ++I) {
12078     Queue.push_back(*I);
12079 
12080     while (!Queue.empty()) {
12081       SDNode *LoadRoot = Queue.pop_back_val();
12082       if (!Visited.insert(LoadRoot).second)
12083         continue;
12084 
12085       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12086         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12087           return true;
12088 
12089       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12090            UE = LoadRoot->use_end(); UI != UE; ++UI)
12091         if (((isa<MemSDNode>(*UI) &&
12092             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12093             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12094           Queue.push_back(*UI);
12095     }
12096   }
12097 
12098   return false;
12099 }
12100 
12101 /// This function is called when we have proved that a SETCC node can be replaced
12102 /// by subtraction (and other supporting instructions) so that the result of
12103 /// comparison is kept in a GPR instead of CR. This function is purely for
12104 /// codegen purposes and has some flags to guide the codegen process.
12105 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12106                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12107   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12108 
12109   // Zero extend the operands to the largest legal integer. Originally, they
12110   // must be of a strictly smaller size.
12111   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12112                          DAG.getConstant(Size, DL, MVT::i32));
12113   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12114                          DAG.getConstant(Size, DL, MVT::i32));
12115 
12116   // Swap if needed. Depends on the condition code.
12117   if (Swap)
12118     std::swap(Op0, Op1);
12119 
12120   // Subtract extended integers.
12121   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12122 
12123   // Move the sign bit to the least significant position and zero out the rest.
12124   // Now the least significant bit carries the result of original comparison.
12125   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12126                              DAG.getConstant(Size - 1, DL, MVT::i32));
12127   auto Final = Shifted;
12128 
12129   // Complement the result if needed. Based on the condition code.
12130   if (Complement)
12131     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12132                         DAG.getConstant(1, DL, MVT::i64));
12133 
12134   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12135 }
12136 
12137 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12138                                                   DAGCombinerInfo &DCI) const {
12139   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12140 
12141   SelectionDAG &DAG = DCI.DAG;
12142   SDLoc DL(N);
12143 
12144   // Size of integers being compared has a critical role in the following
12145   // analysis, so we prefer to do this when all types are legal.
12146   if (!DCI.isAfterLegalizeDAG())
12147     return SDValue();
12148 
12149   // If all users of SETCC extend its value to a legal integer type
12150   // then we replace SETCC with a subtraction
12151   for (SDNode::use_iterator UI = N->use_begin(),
12152        UE = N->use_end(); UI != UE; ++UI) {
12153     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12154       return SDValue();
12155   }
12156 
12157   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12158   auto OpSize = N->getOperand(0).getValueSizeInBits();
12159 
12160   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12161 
12162   if (OpSize < Size) {
12163     switch (CC) {
12164     default: break;
12165     case ISD::SETULT:
12166       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12167     case ISD::SETULE:
12168       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12169     case ISD::SETUGT:
12170       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12171     case ISD::SETUGE:
12172       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12173     }
12174   }
12175 
12176   return SDValue();
12177 }
12178 
12179 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12180                                                   DAGCombinerInfo &DCI) const {
12181   SelectionDAG &DAG = DCI.DAG;
12182   SDLoc dl(N);
12183 
12184   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12185   // If we're tracking CR bits, we need to be careful that we don't have:
12186   //   trunc(binary-ops(zext(x), zext(y)))
12187   // or
12188   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12189   // such that we're unnecessarily moving things into GPRs when it would be
12190   // better to keep them in CR bits.
12191 
12192   // Note that trunc here can be an actual i1 trunc, or can be the effective
12193   // truncation that comes from a setcc or select_cc.
12194   if (N->getOpcode() == ISD::TRUNCATE &&
12195       N->getValueType(0) != MVT::i1)
12196     return SDValue();
12197 
12198   if (N->getOperand(0).getValueType() != MVT::i32 &&
12199       N->getOperand(0).getValueType() != MVT::i64)
12200     return SDValue();
12201 
12202   if (N->getOpcode() == ISD::SETCC ||
12203       N->getOpcode() == ISD::SELECT_CC) {
12204     // If we're looking at a comparison, then we need to make sure that the
12205     // high bits (all except for the first) don't matter the result.
12206     ISD::CondCode CC =
12207       cast<CondCodeSDNode>(N->getOperand(
12208         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12209     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12210 
12211     if (ISD::isSignedIntSetCC(CC)) {
12212       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12213           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12214         return SDValue();
12215     } else if (ISD::isUnsignedIntSetCC(CC)) {
12216       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12217                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12218           !DAG.MaskedValueIsZero(N->getOperand(1),
12219                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12220         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12221                                              : SDValue());
12222     } else {
12223       // This is neither a signed nor an unsigned comparison, just make sure
12224       // that the high bits are equal.
12225       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12226       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12227 
12228       // We don't really care about what is known about the first bit (if
12229       // anything), so clear it in all masks prior to comparing them.
12230       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12231       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12232 
12233       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12234         return SDValue();
12235     }
12236   }
12237 
12238   // We now know that the higher-order bits are irrelevant, we just need to
12239   // make sure that all of the intermediate operations are bit operations, and
12240   // all inputs are extensions.
12241   if (N->getOperand(0).getOpcode() != ISD::AND &&
12242       N->getOperand(0).getOpcode() != ISD::OR  &&
12243       N->getOperand(0).getOpcode() != ISD::XOR &&
12244       N->getOperand(0).getOpcode() != ISD::SELECT &&
12245       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12246       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12247       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12248       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12249       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12250     return SDValue();
12251 
12252   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12253       N->getOperand(1).getOpcode() != ISD::AND &&
12254       N->getOperand(1).getOpcode() != ISD::OR  &&
12255       N->getOperand(1).getOpcode() != ISD::XOR &&
12256       N->getOperand(1).getOpcode() != ISD::SELECT &&
12257       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12258       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12259       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12260       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12261       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12262     return SDValue();
12263 
12264   SmallVector<SDValue, 4> Inputs;
12265   SmallVector<SDValue, 8> BinOps, PromOps;
12266   SmallPtrSet<SDNode *, 16> Visited;
12267 
12268   for (unsigned i = 0; i < 2; ++i) {
12269     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12270           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12271           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12272           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12273         isa<ConstantSDNode>(N->getOperand(i)))
12274       Inputs.push_back(N->getOperand(i));
12275     else
12276       BinOps.push_back(N->getOperand(i));
12277 
12278     if (N->getOpcode() == ISD::TRUNCATE)
12279       break;
12280   }
12281 
12282   // Visit all inputs, collect all binary operations (and, or, xor and
12283   // select) that are all fed by extensions.
12284   while (!BinOps.empty()) {
12285     SDValue BinOp = BinOps.back();
12286     BinOps.pop_back();
12287 
12288     if (!Visited.insert(BinOp.getNode()).second)
12289       continue;
12290 
12291     PromOps.push_back(BinOp);
12292 
12293     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12294       // The condition of the select is not promoted.
12295       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12296         continue;
12297       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12298         continue;
12299 
12300       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12301             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12302             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12303            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12304           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12305         Inputs.push_back(BinOp.getOperand(i));
12306       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12307                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12308                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12309                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12310                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12311                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12312                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12313                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12314                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12315         BinOps.push_back(BinOp.getOperand(i));
12316       } else {
12317         // We have an input that is not an extension or another binary
12318         // operation; we'll abort this transformation.
12319         return SDValue();
12320       }
12321     }
12322   }
12323 
12324   // Make sure that this is a self-contained cluster of operations (which
12325   // is not quite the same thing as saying that everything has only one
12326   // use).
12327   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12328     if (isa<ConstantSDNode>(Inputs[i]))
12329       continue;
12330 
12331     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12332                               UE = Inputs[i].getNode()->use_end();
12333          UI != UE; ++UI) {
12334       SDNode *User = *UI;
12335       if (User != N && !Visited.count(User))
12336         return SDValue();
12337 
12338       // Make sure that we're not going to promote the non-output-value
12339       // operand(s) or SELECT or SELECT_CC.
12340       // FIXME: Although we could sometimes handle this, and it does occur in
12341       // practice that one of the condition inputs to the select is also one of
12342       // the outputs, we currently can't deal with this.
12343       if (User->getOpcode() == ISD::SELECT) {
12344         if (User->getOperand(0) == Inputs[i])
12345           return SDValue();
12346       } else if (User->getOpcode() == ISD::SELECT_CC) {
12347         if (User->getOperand(0) == Inputs[i] ||
12348             User->getOperand(1) == Inputs[i])
12349           return SDValue();
12350       }
12351     }
12352   }
12353 
12354   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12355     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12356                               UE = PromOps[i].getNode()->use_end();
12357          UI != UE; ++UI) {
12358       SDNode *User = *UI;
12359       if (User != N && !Visited.count(User))
12360         return SDValue();
12361 
12362       // Make sure that we're not going to promote the non-output-value
12363       // operand(s) or SELECT or SELECT_CC.
12364       // FIXME: Although we could sometimes handle this, and it does occur in
12365       // practice that one of the condition inputs to the select is also one of
12366       // the outputs, we currently can't deal with this.
12367       if (User->getOpcode() == ISD::SELECT) {
12368         if (User->getOperand(0) == PromOps[i])
12369           return SDValue();
12370       } else if (User->getOpcode() == ISD::SELECT_CC) {
12371         if (User->getOperand(0) == PromOps[i] ||
12372             User->getOperand(1) == PromOps[i])
12373           return SDValue();
12374       }
12375     }
12376   }
12377 
12378   // Replace all inputs with the extension operand.
12379   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12380     // Constants may have users outside the cluster of to-be-promoted nodes,
12381     // and so we need to replace those as we do the promotions.
12382     if (isa<ConstantSDNode>(Inputs[i]))
12383       continue;
12384     else
12385       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12386   }
12387 
12388   std::list<HandleSDNode> PromOpHandles;
12389   for (auto &PromOp : PromOps)
12390     PromOpHandles.emplace_back(PromOp);
12391 
12392   // Replace all operations (these are all the same, but have a different
12393   // (i1) return type). DAG.getNode will validate that the types of
12394   // a binary operator match, so go through the list in reverse so that
12395   // we've likely promoted both operands first. Any intermediate truncations or
12396   // extensions disappear.
12397   while (!PromOpHandles.empty()) {
12398     SDValue PromOp = PromOpHandles.back().getValue();
12399     PromOpHandles.pop_back();
12400 
12401     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12402         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12403         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12404         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12405       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12406           PromOp.getOperand(0).getValueType() != MVT::i1) {
12407         // The operand is not yet ready (see comment below).
12408         PromOpHandles.emplace_front(PromOp);
12409         continue;
12410       }
12411 
12412       SDValue RepValue = PromOp.getOperand(0);
12413       if (isa<ConstantSDNode>(RepValue))
12414         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12415 
12416       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12417       continue;
12418     }
12419 
12420     unsigned C;
12421     switch (PromOp.getOpcode()) {
12422     default:             C = 0; break;
12423     case ISD::SELECT:    C = 1; break;
12424     case ISD::SELECT_CC: C = 2; break;
12425     }
12426 
12427     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12428          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12429         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12430          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12431       // The to-be-promoted operands of this node have not yet been
12432       // promoted (this should be rare because we're going through the
12433       // list backward, but if one of the operands has several users in
12434       // this cluster of to-be-promoted nodes, it is possible).
12435       PromOpHandles.emplace_front(PromOp);
12436       continue;
12437     }
12438 
12439     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12440                                 PromOp.getNode()->op_end());
12441 
12442     // If there are any constant inputs, make sure they're replaced now.
12443     for (unsigned i = 0; i < 2; ++i)
12444       if (isa<ConstantSDNode>(Ops[C+i]))
12445         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12446 
12447     DAG.ReplaceAllUsesOfValueWith(PromOp,
12448       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12449   }
12450 
12451   // Now we're left with the initial truncation itself.
12452   if (N->getOpcode() == ISD::TRUNCATE)
12453     return N->getOperand(0);
12454 
12455   // Otherwise, this is a comparison. The operands to be compared have just
12456   // changed type (to i1), but everything else is the same.
12457   return SDValue(N, 0);
12458 }
12459 
12460 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12461                                                   DAGCombinerInfo &DCI) const {
12462   SelectionDAG &DAG = DCI.DAG;
12463   SDLoc dl(N);
12464 
12465   // If we're tracking CR bits, we need to be careful that we don't have:
12466   //   zext(binary-ops(trunc(x), trunc(y)))
12467   // or
12468   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12469   // such that we're unnecessarily moving things into CR bits that can more
12470   // efficiently stay in GPRs. Note that if we're not certain that the high
12471   // bits are set as required by the final extension, we still may need to do
12472   // some masking to get the proper behavior.
12473 
12474   // This same functionality is important on PPC64 when dealing with
12475   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12476   // the return values of functions. Because it is so similar, it is handled
12477   // here as well.
12478 
12479   if (N->getValueType(0) != MVT::i32 &&
12480       N->getValueType(0) != MVT::i64)
12481     return SDValue();
12482 
12483   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12484         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12485     return SDValue();
12486 
12487   if (N->getOperand(0).getOpcode() != ISD::AND &&
12488       N->getOperand(0).getOpcode() != ISD::OR  &&
12489       N->getOperand(0).getOpcode() != ISD::XOR &&
12490       N->getOperand(0).getOpcode() != ISD::SELECT &&
12491       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12492     return SDValue();
12493 
12494   SmallVector<SDValue, 4> Inputs;
12495   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12496   SmallPtrSet<SDNode *, 16> Visited;
12497 
12498   // Visit all inputs, collect all binary operations (and, or, xor and
12499   // select) that are all fed by truncations.
12500   while (!BinOps.empty()) {
12501     SDValue BinOp = BinOps.back();
12502     BinOps.pop_back();
12503 
12504     if (!Visited.insert(BinOp.getNode()).second)
12505       continue;
12506 
12507     PromOps.push_back(BinOp);
12508 
12509     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12510       // The condition of the select is not promoted.
12511       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12512         continue;
12513       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12514         continue;
12515 
12516       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12517           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12518         Inputs.push_back(BinOp.getOperand(i));
12519       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12520                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12521                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12522                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12523                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12524         BinOps.push_back(BinOp.getOperand(i));
12525       } else {
12526         // We have an input that is not a truncation or another binary
12527         // operation; we'll abort this transformation.
12528         return SDValue();
12529       }
12530     }
12531   }
12532 
12533   // The operands of a select that must be truncated when the select is
12534   // promoted because the operand is actually part of the to-be-promoted set.
12535   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12536 
12537   // Make sure that this is a self-contained cluster of operations (which
12538   // is not quite the same thing as saying that everything has only one
12539   // use).
12540   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12541     if (isa<ConstantSDNode>(Inputs[i]))
12542       continue;
12543 
12544     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12545                               UE = Inputs[i].getNode()->use_end();
12546          UI != UE; ++UI) {
12547       SDNode *User = *UI;
12548       if (User != N && !Visited.count(User))
12549         return SDValue();
12550 
12551       // If we're going to promote the non-output-value operand(s) or SELECT or
12552       // SELECT_CC, record them for truncation.
12553       if (User->getOpcode() == ISD::SELECT) {
12554         if (User->getOperand(0) == Inputs[i])
12555           SelectTruncOp[0].insert(std::make_pair(User,
12556                                     User->getOperand(0).getValueType()));
12557       } else if (User->getOpcode() == ISD::SELECT_CC) {
12558         if (User->getOperand(0) == Inputs[i])
12559           SelectTruncOp[0].insert(std::make_pair(User,
12560                                     User->getOperand(0).getValueType()));
12561         if (User->getOperand(1) == Inputs[i])
12562           SelectTruncOp[1].insert(std::make_pair(User,
12563                                     User->getOperand(1).getValueType()));
12564       }
12565     }
12566   }
12567 
12568   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12569     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12570                               UE = PromOps[i].getNode()->use_end();
12571          UI != UE; ++UI) {
12572       SDNode *User = *UI;
12573       if (User != N && !Visited.count(User))
12574         return SDValue();
12575 
12576       // If we're going to promote the non-output-value operand(s) or SELECT or
12577       // SELECT_CC, record them for truncation.
12578       if (User->getOpcode() == ISD::SELECT) {
12579         if (User->getOperand(0) == PromOps[i])
12580           SelectTruncOp[0].insert(std::make_pair(User,
12581                                     User->getOperand(0).getValueType()));
12582       } else if (User->getOpcode() == ISD::SELECT_CC) {
12583         if (User->getOperand(0) == PromOps[i])
12584           SelectTruncOp[0].insert(std::make_pair(User,
12585                                     User->getOperand(0).getValueType()));
12586         if (User->getOperand(1) == PromOps[i])
12587           SelectTruncOp[1].insert(std::make_pair(User,
12588                                     User->getOperand(1).getValueType()));
12589       }
12590     }
12591   }
12592 
12593   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12594   bool ReallyNeedsExt = false;
12595   if (N->getOpcode() != ISD::ANY_EXTEND) {
12596     // If all of the inputs are not already sign/zero extended, then
12597     // we'll still need to do that at the end.
12598     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12599       if (isa<ConstantSDNode>(Inputs[i]))
12600         continue;
12601 
12602       unsigned OpBits =
12603         Inputs[i].getOperand(0).getValueSizeInBits();
12604       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12605 
12606       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12607            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12608                                   APInt::getHighBitsSet(OpBits,
12609                                                         OpBits-PromBits))) ||
12610           (N->getOpcode() == ISD::SIGN_EXTEND &&
12611            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12612              (OpBits-(PromBits-1)))) {
12613         ReallyNeedsExt = true;
12614         break;
12615       }
12616     }
12617   }
12618 
12619   // Replace all inputs, either with the truncation operand, or a
12620   // truncation or extension to the final output type.
12621   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12622     // Constant inputs need to be replaced with the to-be-promoted nodes that
12623     // use them because they might have users outside of the cluster of
12624     // promoted nodes.
12625     if (isa<ConstantSDNode>(Inputs[i]))
12626       continue;
12627 
12628     SDValue InSrc = Inputs[i].getOperand(0);
12629     if (Inputs[i].getValueType() == N->getValueType(0))
12630       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12631     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12632       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12633         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12634     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12635       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12636         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12637     else
12638       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12639         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12640   }
12641 
12642   std::list<HandleSDNode> PromOpHandles;
12643   for (auto &PromOp : PromOps)
12644     PromOpHandles.emplace_back(PromOp);
12645 
12646   // Replace all operations (these are all the same, but have a different
12647   // (promoted) return type). DAG.getNode will validate that the types of
12648   // a binary operator match, so go through the list in reverse so that
12649   // we've likely promoted both operands first.
12650   while (!PromOpHandles.empty()) {
12651     SDValue PromOp = PromOpHandles.back().getValue();
12652     PromOpHandles.pop_back();
12653 
12654     unsigned C;
12655     switch (PromOp.getOpcode()) {
12656     default:             C = 0; break;
12657     case ISD::SELECT:    C = 1; break;
12658     case ISD::SELECT_CC: C = 2; break;
12659     }
12660 
12661     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12662          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12663         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12664          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12665       // The to-be-promoted operands of this node have not yet been
12666       // promoted (this should be rare because we're going through the
12667       // list backward, but if one of the operands has several users in
12668       // this cluster of to-be-promoted nodes, it is possible).
12669       PromOpHandles.emplace_front(PromOp);
12670       continue;
12671     }
12672 
12673     // For SELECT and SELECT_CC nodes, we do a similar check for any
12674     // to-be-promoted comparison inputs.
12675     if (PromOp.getOpcode() == ISD::SELECT ||
12676         PromOp.getOpcode() == ISD::SELECT_CC) {
12677       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12678            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12679           (SelectTruncOp[1].count(PromOp.getNode()) &&
12680            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12681         PromOpHandles.emplace_front(PromOp);
12682         continue;
12683       }
12684     }
12685 
12686     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12687                                 PromOp.getNode()->op_end());
12688 
12689     // If this node has constant inputs, then they'll need to be promoted here.
12690     for (unsigned i = 0; i < 2; ++i) {
12691       if (!isa<ConstantSDNode>(Ops[C+i]))
12692         continue;
12693       if (Ops[C+i].getValueType() == N->getValueType(0))
12694         continue;
12695 
12696       if (N->getOpcode() == ISD::SIGN_EXTEND)
12697         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12698       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12699         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12700       else
12701         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12702     }
12703 
12704     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12705     // truncate them again to the original value type.
12706     if (PromOp.getOpcode() == ISD::SELECT ||
12707         PromOp.getOpcode() == ISD::SELECT_CC) {
12708       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12709       if (SI0 != SelectTruncOp[0].end())
12710         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12711       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12712       if (SI1 != SelectTruncOp[1].end())
12713         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12714     }
12715 
12716     DAG.ReplaceAllUsesOfValueWith(PromOp,
12717       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12718   }
12719 
12720   // Now we're left with the initial extension itself.
12721   if (!ReallyNeedsExt)
12722     return N->getOperand(0);
12723 
12724   // To zero extend, just mask off everything except for the first bit (in the
12725   // i1 case).
12726   if (N->getOpcode() == ISD::ZERO_EXTEND)
12727     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12728                        DAG.getConstant(APInt::getLowBitsSet(
12729                                          N->getValueSizeInBits(0), PromBits),
12730                                        dl, N->getValueType(0)));
12731 
12732   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12733          "Invalid extension type");
12734   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12735   SDValue ShiftCst =
12736       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12737   return DAG.getNode(
12738       ISD::SRA, dl, N->getValueType(0),
12739       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12740       ShiftCst);
12741 }
12742 
12743 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12744                                         DAGCombinerInfo &DCI) const {
12745   assert(N->getOpcode() == ISD::SETCC &&
12746          "Should be called with a SETCC node");
12747 
12748   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12749   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12750     SDValue LHS = N->getOperand(0);
12751     SDValue RHS = N->getOperand(1);
12752 
12753     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12754     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12755         LHS.hasOneUse())
12756       std::swap(LHS, RHS);
12757 
12758     // x == 0-y --> x+y == 0
12759     // x != 0-y --> x+y != 0
12760     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12761         RHS.hasOneUse()) {
12762       SDLoc DL(N);
12763       SelectionDAG &DAG = DCI.DAG;
12764       EVT VT = N->getValueType(0);
12765       EVT OpVT = LHS.getValueType();
12766       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12767       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12768     }
12769   }
12770 
12771   return DAGCombineTruncBoolExt(N, DCI);
12772 }
12773 
12774 // Is this an extending load from an f32 to an f64?
12775 static bool isFPExtLoad(SDValue Op) {
12776   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12777     return LD->getExtensionType() == ISD::EXTLOAD &&
12778       Op.getValueType() == MVT::f64;
12779   return false;
12780 }
12781 
12782 /// Reduces the number of fp-to-int conversion when building a vector.
12783 ///
12784 /// If this vector is built out of floating to integer conversions,
12785 /// transform it to a vector built out of floating point values followed by a
12786 /// single floating to integer conversion of the vector.
12787 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12788 /// becomes (fptosi (build_vector ($A, $B, ...)))
12789 SDValue PPCTargetLowering::
12790 combineElementTruncationToVectorTruncation(SDNode *N,
12791                                            DAGCombinerInfo &DCI) const {
12792   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12793          "Should be called with a BUILD_VECTOR node");
12794 
12795   SelectionDAG &DAG = DCI.DAG;
12796   SDLoc dl(N);
12797 
12798   SDValue FirstInput = N->getOperand(0);
12799   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12800          "The input operand must be an fp-to-int conversion.");
12801 
12802   // This combine happens after legalization so the fp_to_[su]i nodes are
12803   // already converted to PPCSISD nodes.
12804   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12805   if (FirstConversion == PPCISD::FCTIDZ ||
12806       FirstConversion == PPCISD::FCTIDUZ ||
12807       FirstConversion == PPCISD::FCTIWZ ||
12808       FirstConversion == PPCISD::FCTIWUZ) {
12809     bool IsSplat = true;
12810     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12811       FirstConversion == PPCISD::FCTIWUZ;
12812     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12813     SmallVector<SDValue, 4> Ops;
12814     EVT TargetVT = N->getValueType(0);
12815     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12816       SDValue NextOp = N->getOperand(i);
12817       if (NextOp.getOpcode() != PPCISD::MFVSR)
12818         return SDValue();
12819       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12820       if (NextConversion != FirstConversion)
12821         return SDValue();
12822       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12823       // This is not valid if the input was originally double precision. It is
12824       // also not profitable to do unless this is an extending load in which
12825       // case doing this combine will allow us to combine consecutive loads.
12826       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12827         return SDValue();
12828       if (N->getOperand(i) != FirstInput)
12829         IsSplat = false;
12830     }
12831 
12832     // If this is a splat, we leave it as-is since there will be only a single
12833     // fp-to-int conversion followed by a splat of the integer. This is better
12834     // for 32-bit and smaller ints and neutral for 64-bit ints.
12835     if (IsSplat)
12836       return SDValue();
12837 
12838     // Now that we know we have the right type of node, get its operands
12839     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12840       SDValue In = N->getOperand(i).getOperand(0);
12841       if (Is32Bit) {
12842         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12843         // here, we know that all inputs are extending loads so this is safe).
12844         if (In.isUndef())
12845           Ops.push_back(DAG.getUNDEF(SrcVT));
12846         else {
12847           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12848                                       MVT::f32, In.getOperand(0),
12849                                       DAG.getIntPtrConstant(1, dl));
12850           Ops.push_back(Trunc);
12851         }
12852       } else
12853         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12854     }
12855 
12856     unsigned Opcode;
12857     if (FirstConversion == PPCISD::FCTIDZ ||
12858         FirstConversion == PPCISD::FCTIWZ)
12859       Opcode = ISD::FP_TO_SINT;
12860     else
12861       Opcode = ISD::FP_TO_UINT;
12862 
12863     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12864     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12865     return DAG.getNode(Opcode, dl, TargetVT, BV);
12866   }
12867   return SDValue();
12868 }
12869 
12870 /// Reduce the number of loads when building a vector.
12871 ///
12872 /// Building a vector out of multiple loads can be converted to a load
12873 /// of the vector type if the loads are consecutive. If the loads are
12874 /// consecutive but in descending order, a shuffle is added at the end
12875 /// to reorder the vector.
12876 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12877   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12878          "Should be called with a BUILD_VECTOR node");
12879 
12880   SDLoc dl(N);
12881 
12882   // Return early for non byte-sized type, as they can't be consecutive.
12883   if (!N->getValueType(0).getVectorElementType().isByteSized())
12884     return SDValue();
12885 
12886   bool InputsAreConsecutiveLoads = true;
12887   bool InputsAreReverseConsecutive = true;
12888   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12889   SDValue FirstInput = N->getOperand(0);
12890   bool IsRoundOfExtLoad = false;
12891 
12892   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12893       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12894     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12895     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12896   }
12897   // Not a build vector of (possibly fp_rounded) loads.
12898   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12899       N->getNumOperands() == 1)
12900     return SDValue();
12901 
12902   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12903     // If any inputs are fp_round(extload), they all must be.
12904     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12905       return SDValue();
12906 
12907     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12908       N->getOperand(i);
12909     if (NextInput.getOpcode() != ISD::LOAD)
12910       return SDValue();
12911 
12912     SDValue PreviousInput =
12913       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12914     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12915     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12916 
12917     // If any inputs are fp_round(extload), they all must be.
12918     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12919       return SDValue();
12920 
12921     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12922       InputsAreConsecutiveLoads = false;
12923     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12924       InputsAreReverseConsecutive = false;
12925 
12926     // Exit early if the loads are neither consecutive nor reverse consecutive.
12927     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12928       return SDValue();
12929   }
12930 
12931   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12932          "The loads cannot be both consecutive and reverse consecutive.");
12933 
12934   SDValue FirstLoadOp =
12935     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12936   SDValue LastLoadOp =
12937     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12938                        N->getOperand(N->getNumOperands()-1);
12939 
12940   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12941   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12942   if (InputsAreConsecutiveLoads) {
12943     assert(LD1 && "Input needs to be a LoadSDNode.");
12944     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12945                        LD1->getBasePtr(), LD1->getPointerInfo(),
12946                        LD1->getAlignment());
12947   }
12948   if (InputsAreReverseConsecutive) {
12949     assert(LDL && "Input needs to be a LoadSDNode.");
12950     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12951                                LDL->getBasePtr(), LDL->getPointerInfo(),
12952                                LDL->getAlignment());
12953     SmallVector<int, 16> Ops;
12954     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12955       Ops.push_back(i);
12956 
12957     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12958                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12959   }
12960   return SDValue();
12961 }
12962 
12963 // This function adds the required vector_shuffle needed to get
12964 // the elements of the vector extract in the correct position
12965 // as specified by the CorrectElems encoding.
12966 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12967                                       SDValue Input, uint64_t Elems,
12968                                       uint64_t CorrectElems) {
12969   SDLoc dl(N);
12970 
12971   unsigned NumElems = Input.getValueType().getVectorNumElements();
12972   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12973 
12974   // Knowing the element indices being extracted from the original
12975   // vector and the order in which they're being inserted, just put
12976   // them at element indices required for the instruction.
12977   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12978     if (DAG.getDataLayout().isLittleEndian())
12979       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12980     else
12981       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12982     CorrectElems = CorrectElems >> 8;
12983     Elems = Elems >> 8;
12984   }
12985 
12986   SDValue Shuffle =
12987       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12988                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12989 
12990   EVT Ty = N->getValueType(0);
12991   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12992   return BV;
12993 }
12994 
12995 // Look for build vector patterns where input operands come from sign
12996 // extended vector_extract elements of specific indices. If the correct indices
12997 // aren't used, add a vector shuffle to fix up the indices and create a new
12998 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12999 // during instruction selection.
13000 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13001   // This array encodes the indices that the vector sign extend instructions
13002   // extract from when extending from one type to another for both BE and LE.
13003   // The right nibble of each byte corresponds to the LE incides.
13004   // and the left nibble of each byte corresponds to the BE incides.
13005   // For example: 0x3074B8FC  byte->word
13006   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13007   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13008   // For example: 0x000070F8  byte->double word
13009   // For LE: the allowed indices are: 0x0,0x8
13010   // For BE: the allowed indices are: 0x7,0xF
13011   uint64_t TargetElems[] = {
13012       0x3074B8FC, // b->w
13013       0x000070F8, // b->d
13014       0x10325476, // h->w
13015       0x00003074, // h->d
13016       0x00001032, // w->d
13017   };
13018 
13019   uint64_t Elems = 0;
13020   int Index;
13021   SDValue Input;
13022 
13023   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13024     if (!Op)
13025       return false;
13026     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13027         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13028       return false;
13029 
13030     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13031     // of the right width.
13032     SDValue Extract = Op.getOperand(0);
13033     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13034       Extract = Extract.getOperand(0);
13035     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13036       return false;
13037 
13038     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13039     if (!ExtOp)
13040       return false;
13041 
13042     Index = ExtOp->getZExtValue();
13043     if (Input && Input != Extract.getOperand(0))
13044       return false;
13045 
13046     if (!Input)
13047       Input = Extract.getOperand(0);
13048 
13049     Elems = Elems << 8;
13050     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13051     Elems |= Index;
13052 
13053     return true;
13054   };
13055 
13056   // If the build vector operands aren't sign extended vector extracts,
13057   // of the same input vector, then return.
13058   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13059     if (!isSExtOfVecExtract(N->getOperand(i))) {
13060       return SDValue();
13061     }
13062   }
13063 
13064   // If the vector extract indicies are not correct, add the appropriate
13065   // vector_shuffle.
13066   int TgtElemArrayIdx;
13067   int InputSize = Input.getValueType().getScalarSizeInBits();
13068   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13069   if (InputSize + OutputSize == 40)
13070     TgtElemArrayIdx = 0;
13071   else if (InputSize + OutputSize == 72)
13072     TgtElemArrayIdx = 1;
13073   else if (InputSize + OutputSize == 48)
13074     TgtElemArrayIdx = 2;
13075   else if (InputSize + OutputSize == 80)
13076     TgtElemArrayIdx = 3;
13077   else if (InputSize + OutputSize == 96)
13078     TgtElemArrayIdx = 4;
13079   else
13080     return SDValue();
13081 
13082   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13083   CorrectElems = DAG.getDataLayout().isLittleEndian()
13084                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13085                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13086   if (Elems != CorrectElems) {
13087     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13088   }
13089 
13090   // Regular lowering will catch cases where a shuffle is not needed.
13091   return SDValue();
13092 }
13093 
13094 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13095                                                  DAGCombinerInfo &DCI) const {
13096   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13097          "Should be called with a BUILD_VECTOR node");
13098 
13099   SelectionDAG &DAG = DCI.DAG;
13100   SDLoc dl(N);
13101 
13102   if (!Subtarget.hasVSX())
13103     return SDValue();
13104 
13105   // The target independent DAG combiner will leave a build_vector of
13106   // float-to-int conversions intact. We can generate MUCH better code for
13107   // a float-to-int conversion of a vector of floats.
13108   SDValue FirstInput = N->getOperand(0);
13109   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13110     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13111     if (Reduced)
13112       return Reduced;
13113   }
13114 
13115   // If we're building a vector out of consecutive loads, just load that
13116   // vector type.
13117   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13118   if (Reduced)
13119     return Reduced;
13120 
13121   // If we're building a vector out of extended elements from another vector
13122   // we have P9 vector integer extend instructions. The code assumes legal
13123   // input types (i.e. it can't handle things like v4i16) so do not run before
13124   // legalization.
13125   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13126     Reduced = combineBVOfVecSExt(N, DAG);
13127     if (Reduced)
13128       return Reduced;
13129   }
13130 
13131 
13132   if (N->getValueType(0) != MVT::v2f64)
13133     return SDValue();
13134 
13135   // Looking for:
13136   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13137   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13138       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13139     return SDValue();
13140   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13141       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13142     return SDValue();
13143   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13144     return SDValue();
13145 
13146   SDValue Ext1 = FirstInput.getOperand(0);
13147   SDValue Ext2 = N->getOperand(1).getOperand(0);
13148   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13149      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13150     return SDValue();
13151 
13152   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13153   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13154   if (!Ext1Op || !Ext2Op)
13155     return SDValue();
13156   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13157       Ext1.getOperand(0) != Ext2.getOperand(0))
13158     return SDValue();
13159 
13160   int FirstElem = Ext1Op->getZExtValue();
13161   int SecondElem = Ext2Op->getZExtValue();
13162   int SubvecIdx;
13163   if (FirstElem == 0 && SecondElem == 1)
13164     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13165   else if (FirstElem == 2 && SecondElem == 3)
13166     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13167   else
13168     return SDValue();
13169 
13170   SDValue SrcVec = Ext1.getOperand(0);
13171   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13172     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13173   return DAG.getNode(NodeType, dl, MVT::v2f64,
13174                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13175 }
13176 
13177 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13178                                               DAGCombinerInfo &DCI) const {
13179   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13180           N->getOpcode() == ISD::UINT_TO_FP) &&
13181          "Need an int -> FP conversion node here");
13182 
13183   if (useSoftFloat() || !Subtarget.has64BitSupport())
13184     return SDValue();
13185 
13186   SelectionDAG &DAG = DCI.DAG;
13187   SDLoc dl(N);
13188   SDValue Op(N, 0);
13189 
13190   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13191   // from the hardware.
13192   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13193     return SDValue();
13194   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13195       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13196     return SDValue();
13197 
13198   SDValue FirstOperand(Op.getOperand(0));
13199   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13200     (FirstOperand.getValueType() == MVT::i8 ||
13201      FirstOperand.getValueType() == MVT::i16);
13202   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13203     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13204     bool DstDouble = Op.getValueType() == MVT::f64;
13205     unsigned ConvOp = Signed ?
13206       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13207       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13208     SDValue WidthConst =
13209       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13210                             dl, false);
13211     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13212     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13213     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13214                                          DAG.getVTList(MVT::f64, MVT::Other),
13215                                          Ops, MVT::i8, LDN->getMemOperand());
13216 
13217     // For signed conversion, we need to sign-extend the value in the VSR
13218     if (Signed) {
13219       SDValue ExtOps[] = { Ld, WidthConst };
13220       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13221       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13222     } else
13223       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13224   }
13225 
13226 
13227   // For i32 intermediate values, unfortunately, the conversion functions
13228   // leave the upper 32 bits of the value are undefined. Within the set of
13229   // scalar instructions, we have no method for zero- or sign-extending the
13230   // value. Thus, we cannot handle i32 intermediate values here.
13231   if (Op.getOperand(0).getValueType() == MVT::i32)
13232     return SDValue();
13233 
13234   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13235          "UINT_TO_FP is supported only with FPCVT");
13236 
13237   // If we have FCFIDS, then use it when converting to single-precision.
13238   // Otherwise, convert to double-precision and then round.
13239   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13240                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13241                                                             : PPCISD::FCFIDS)
13242                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13243                                                             : PPCISD::FCFID);
13244   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13245                   ? MVT::f32
13246                   : MVT::f64;
13247 
13248   // If we're converting from a float, to an int, and back to a float again,
13249   // then we don't need the store/load pair at all.
13250   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13251        Subtarget.hasFPCVT()) ||
13252       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13253     SDValue Src = Op.getOperand(0).getOperand(0);
13254     if (Src.getValueType() == MVT::f32) {
13255       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13256       DCI.AddToWorklist(Src.getNode());
13257     } else if (Src.getValueType() != MVT::f64) {
13258       // Make sure that we don't pick up a ppc_fp128 source value.
13259       return SDValue();
13260     }
13261 
13262     unsigned FCTOp =
13263       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13264                                                         PPCISD::FCTIDUZ;
13265 
13266     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13267     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13268 
13269     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13270       FP = DAG.getNode(ISD::FP_ROUND, dl,
13271                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13272       DCI.AddToWorklist(FP.getNode());
13273     }
13274 
13275     return FP;
13276   }
13277 
13278   return SDValue();
13279 }
13280 
13281 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13282 // builtins) into loads with swaps.
13283 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13284                                               DAGCombinerInfo &DCI) const {
13285   SelectionDAG &DAG = DCI.DAG;
13286   SDLoc dl(N);
13287   SDValue Chain;
13288   SDValue Base;
13289   MachineMemOperand *MMO;
13290 
13291   switch (N->getOpcode()) {
13292   default:
13293     llvm_unreachable("Unexpected opcode for little endian VSX load");
13294   case ISD::LOAD: {
13295     LoadSDNode *LD = cast<LoadSDNode>(N);
13296     Chain = LD->getChain();
13297     Base = LD->getBasePtr();
13298     MMO = LD->getMemOperand();
13299     // If the MMO suggests this isn't a load of a full vector, leave
13300     // things alone.  For a built-in, we have to make the change for
13301     // correctness, so if there is a size problem that will be a bug.
13302     if (MMO->getSize() < 16)
13303       return SDValue();
13304     break;
13305   }
13306   case ISD::INTRINSIC_W_CHAIN: {
13307     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13308     Chain = Intrin->getChain();
13309     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13310     // us what we want. Get operand 2 instead.
13311     Base = Intrin->getOperand(2);
13312     MMO = Intrin->getMemOperand();
13313     break;
13314   }
13315   }
13316 
13317   MVT VecTy = N->getValueType(0).getSimpleVT();
13318 
13319   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13320   // aligned and the type is a vector with elements up to 4 bytes
13321   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13322       && VecTy.getScalarSizeInBits() <= 32 ) {
13323     return SDValue();
13324   }
13325 
13326   SDValue LoadOps[] = { Chain, Base };
13327   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13328                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13329                                          LoadOps, MVT::v2f64, MMO);
13330 
13331   DCI.AddToWorklist(Load.getNode());
13332   Chain = Load.getValue(1);
13333   SDValue Swap = DAG.getNode(
13334       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13335   DCI.AddToWorklist(Swap.getNode());
13336 
13337   // Add a bitcast if the resulting load type doesn't match v2f64.
13338   if (VecTy != MVT::v2f64) {
13339     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13340     DCI.AddToWorklist(N.getNode());
13341     // Package {bitcast value, swap's chain} to match Load's shape.
13342     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13343                        N, Swap.getValue(1));
13344   }
13345 
13346   return Swap;
13347 }
13348 
13349 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13350 // builtins) into stores with swaps.
13351 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13352                                                DAGCombinerInfo &DCI) const {
13353   SelectionDAG &DAG = DCI.DAG;
13354   SDLoc dl(N);
13355   SDValue Chain;
13356   SDValue Base;
13357   unsigned SrcOpnd;
13358   MachineMemOperand *MMO;
13359 
13360   switch (N->getOpcode()) {
13361   default:
13362     llvm_unreachable("Unexpected opcode for little endian VSX store");
13363   case ISD::STORE: {
13364     StoreSDNode *ST = cast<StoreSDNode>(N);
13365     Chain = ST->getChain();
13366     Base = ST->getBasePtr();
13367     MMO = ST->getMemOperand();
13368     SrcOpnd = 1;
13369     // If the MMO suggests this isn't a store of a full vector, leave
13370     // things alone.  For a built-in, we have to make the change for
13371     // correctness, so if there is a size problem that will be a bug.
13372     if (MMO->getSize() < 16)
13373       return SDValue();
13374     break;
13375   }
13376   case ISD::INTRINSIC_VOID: {
13377     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13378     Chain = Intrin->getChain();
13379     // Intrin->getBasePtr() oddly does not get what we want.
13380     Base = Intrin->getOperand(3);
13381     MMO = Intrin->getMemOperand();
13382     SrcOpnd = 2;
13383     break;
13384   }
13385   }
13386 
13387   SDValue Src = N->getOperand(SrcOpnd);
13388   MVT VecTy = Src.getValueType().getSimpleVT();
13389 
13390   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13391   // aligned and the type is a vector with elements up to 4 bytes
13392   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13393       && VecTy.getScalarSizeInBits() <= 32 ) {
13394     return SDValue();
13395   }
13396 
13397   // All stores are done as v2f64 and possible bit cast.
13398   if (VecTy != MVT::v2f64) {
13399     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13400     DCI.AddToWorklist(Src.getNode());
13401   }
13402 
13403   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13404                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13405   DCI.AddToWorklist(Swap.getNode());
13406   Chain = Swap.getValue(1);
13407   SDValue StoreOps[] = { Chain, Swap, Base };
13408   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13409                                           DAG.getVTList(MVT::Other),
13410                                           StoreOps, VecTy, MMO);
13411   DCI.AddToWorklist(Store.getNode());
13412   return Store;
13413 }
13414 
13415 // Handle DAG combine for STORE (FP_TO_INT F).
13416 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13417                                                DAGCombinerInfo &DCI) const {
13418 
13419   SelectionDAG &DAG = DCI.DAG;
13420   SDLoc dl(N);
13421   unsigned Opcode = N->getOperand(1).getOpcode();
13422 
13423   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13424          && "Not a FP_TO_INT Instruction!");
13425 
13426   SDValue Val = N->getOperand(1).getOperand(0);
13427   EVT Op1VT = N->getOperand(1).getValueType();
13428   EVT ResVT = Val.getValueType();
13429 
13430   // Floating point types smaller than 32 bits are not legal on Power.
13431   if (ResVT.getScalarSizeInBits() < 32)
13432     return SDValue();
13433 
13434   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13435   bool ValidTypeForStoreFltAsInt =
13436         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13437          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13438 
13439   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13440       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13441     return SDValue();
13442 
13443   // Extend f32 values to f64
13444   if (ResVT.getScalarSizeInBits() == 32) {
13445     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13446     DCI.AddToWorklist(Val.getNode());
13447   }
13448 
13449   // Set signed or unsigned conversion opcode.
13450   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13451                           PPCISD::FP_TO_SINT_IN_VSR :
13452                           PPCISD::FP_TO_UINT_IN_VSR;
13453 
13454   Val = DAG.getNode(ConvOpcode,
13455                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13456   DCI.AddToWorklist(Val.getNode());
13457 
13458   // Set number of bytes being converted.
13459   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13460   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13461                     DAG.getIntPtrConstant(ByteSize, dl, false),
13462                     DAG.getValueType(Op1VT) };
13463 
13464   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13465           DAG.getVTList(MVT::Other), Ops,
13466           cast<StoreSDNode>(N)->getMemoryVT(),
13467           cast<StoreSDNode>(N)->getMemOperand());
13468 
13469   DCI.AddToWorklist(Val.getNode());
13470   return Val;
13471 }
13472 
13473 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13474                                                 LSBaseSDNode *LSBase,
13475                                                 DAGCombinerInfo &DCI) const {
13476   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13477         "Not a reverse memop pattern!");
13478 
13479   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13480     auto Mask = SVN->getMask();
13481     int i = 0;
13482     auto I = Mask.rbegin();
13483     auto E = Mask.rend();
13484 
13485     for (; I != E; ++I) {
13486       if (*I != i)
13487         return false;
13488       i++;
13489     }
13490     return true;
13491   };
13492 
13493   SelectionDAG &DAG = DCI.DAG;
13494   EVT VT = SVN->getValueType(0);
13495 
13496   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13497     return SDValue();
13498 
13499   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13500   // See comment in PPCVSXSwapRemoval.cpp.
13501   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13502   if (!Subtarget.hasP9Vector())
13503     return SDValue();
13504 
13505   if(!IsElementReverse(SVN))
13506     return SDValue();
13507 
13508   if (LSBase->getOpcode() == ISD::LOAD) {
13509     SDLoc dl(SVN);
13510     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13511     return DAG.getMemIntrinsicNode(
13512         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13513         LSBase->getMemoryVT(), LSBase->getMemOperand());
13514   }
13515 
13516   if (LSBase->getOpcode() == ISD::STORE) {
13517     SDLoc dl(LSBase);
13518     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13519                           LSBase->getBasePtr()};
13520     return DAG.getMemIntrinsicNode(
13521         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13522         LSBase->getMemoryVT(), LSBase->getMemOperand());
13523   }
13524 
13525   llvm_unreachable("Expected a load or store node here");
13526 }
13527 
13528 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13529                                              DAGCombinerInfo &DCI) const {
13530   SelectionDAG &DAG = DCI.DAG;
13531   SDLoc dl(N);
13532   switch (N->getOpcode()) {
13533   default: break;
13534   case ISD::ADD:
13535     return combineADD(N, DCI);
13536   case ISD::SHL:
13537     return combineSHL(N, DCI);
13538   case ISD::SRA:
13539     return combineSRA(N, DCI);
13540   case ISD::SRL:
13541     return combineSRL(N, DCI);
13542   case ISD::MUL:
13543     return combineMUL(N, DCI);
13544   case PPCISD::SHL:
13545     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13546         return N->getOperand(0);
13547     break;
13548   case PPCISD::SRL:
13549     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13550         return N->getOperand(0);
13551     break;
13552   case PPCISD::SRA:
13553     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13554       if (C->isNullValue() ||   //  0 >>s V -> 0.
13555           C->isAllOnesValue())    // -1 >>s V -> -1.
13556         return N->getOperand(0);
13557     }
13558     break;
13559   case ISD::SIGN_EXTEND:
13560   case ISD::ZERO_EXTEND:
13561   case ISD::ANY_EXTEND:
13562     return DAGCombineExtBoolTrunc(N, DCI);
13563   case ISD::TRUNCATE:
13564     return combineTRUNCATE(N, DCI);
13565   case ISD::SETCC:
13566     if (SDValue CSCC = combineSetCC(N, DCI))
13567       return CSCC;
13568     LLVM_FALLTHROUGH;
13569   case ISD::SELECT_CC:
13570     return DAGCombineTruncBoolExt(N, DCI);
13571   case ISD::SINT_TO_FP:
13572   case ISD::UINT_TO_FP:
13573     return combineFPToIntToFP(N, DCI);
13574   case ISD::VECTOR_SHUFFLE:
13575     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13576       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13577       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13578     }
13579     break;
13580   case ISD::STORE: {
13581 
13582     EVT Op1VT = N->getOperand(1).getValueType();
13583     unsigned Opcode = N->getOperand(1).getOpcode();
13584 
13585     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13586       SDValue Val= combineStoreFPToInt(N, DCI);
13587       if (Val)
13588         return Val;
13589     }
13590 
13591     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13592       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13593       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13594       if (Val)
13595         return Val;
13596     }
13597 
13598     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13599     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13600         N->getOperand(1).getNode()->hasOneUse() &&
13601         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13602          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13603 
13604       // STBRX can only handle simple types and it makes no sense to store less
13605       // two bytes in byte-reversed order.
13606       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13607       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13608         break;
13609 
13610       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13611       // Do an any-extend to 32-bits if this is a half-word input.
13612       if (BSwapOp.getValueType() == MVT::i16)
13613         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13614 
13615       // If the type of BSWAP operand is wider than stored memory width
13616       // it need to be shifted to the right side before STBRX.
13617       if (Op1VT.bitsGT(mVT)) {
13618         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13619         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13620                               DAG.getConstant(Shift, dl, MVT::i32));
13621         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13622         if (Op1VT == MVT::i64)
13623           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13624       }
13625 
13626       SDValue Ops[] = {
13627         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13628       };
13629       return
13630         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13631                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13632                                 cast<StoreSDNode>(N)->getMemOperand());
13633     }
13634 
13635     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13636     // So it can increase the chance of CSE constant construction.
13637     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13638         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13639       // Need to sign-extended to 64-bits to handle negative values.
13640       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13641       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13642                                     MemVT.getSizeInBits());
13643       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13644 
13645       // DAG.getTruncStore() can't be used here because it doesn't accept
13646       // the general (base + offset) addressing mode.
13647       // So we use UpdateNodeOperands and setTruncatingStore instead.
13648       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13649                              N->getOperand(3));
13650       cast<StoreSDNode>(N)->setTruncatingStore(true);
13651       return SDValue(N, 0);
13652     }
13653 
13654     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13655     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13656     if (Op1VT.isSimple()) {
13657       MVT StoreVT = Op1VT.getSimpleVT();
13658       if (Subtarget.needsSwapsForVSXMemOps() &&
13659           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13660            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13661         return expandVSXStoreForLE(N, DCI);
13662     }
13663     break;
13664   }
13665   case ISD::LOAD: {
13666     LoadSDNode *LD = cast<LoadSDNode>(N);
13667     EVT VT = LD->getValueType(0);
13668 
13669     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13670     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13671     if (VT.isSimple()) {
13672       MVT LoadVT = VT.getSimpleVT();
13673       if (Subtarget.needsSwapsForVSXMemOps() &&
13674           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13675            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13676         return expandVSXLoadForLE(N, DCI);
13677     }
13678 
13679     // We sometimes end up with a 64-bit integer load, from which we extract
13680     // two single-precision floating-point numbers. This happens with
13681     // std::complex<float>, and other similar structures, because of the way we
13682     // canonicalize structure copies. However, if we lack direct moves,
13683     // then the final bitcasts from the extracted integer values to the
13684     // floating-point numbers turn into store/load pairs. Even with direct moves,
13685     // just loading the two floating-point numbers is likely better.
13686     auto ReplaceTwoFloatLoad = [&]() {
13687       if (VT != MVT::i64)
13688         return false;
13689 
13690       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13691           LD->isVolatile())
13692         return false;
13693 
13694       //  We're looking for a sequence like this:
13695       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13696       //      t16: i64 = srl t13, Constant:i32<32>
13697       //    t17: i32 = truncate t16
13698       //  t18: f32 = bitcast t17
13699       //    t19: i32 = truncate t13
13700       //  t20: f32 = bitcast t19
13701 
13702       if (!LD->hasNUsesOfValue(2, 0))
13703         return false;
13704 
13705       auto UI = LD->use_begin();
13706       while (UI.getUse().getResNo() != 0) ++UI;
13707       SDNode *Trunc = *UI++;
13708       while (UI.getUse().getResNo() != 0) ++UI;
13709       SDNode *RightShift = *UI;
13710       if (Trunc->getOpcode() != ISD::TRUNCATE)
13711         std::swap(Trunc, RightShift);
13712 
13713       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13714           Trunc->getValueType(0) != MVT::i32 ||
13715           !Trunc->hasOneUse())
13716         return false;
13717       if (RightShift->getOpcode() != ISD::SRL ||
13718           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13719           RightShift->getConstantOperandVal(1) != 32 ||
13720           !RightShift->hasOneUse())
13721         return false;
13722 
13723       SDNode *Trunc2 = *RightShift->use_begin();
13724       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13725           Trunc2->getValueType(0) != MVT::i32 ||
13726           !Trunc2->hasOneUse())
13727         return false;
13728 
13729       SDNode *Bitcast = *Trunc->use_begin();
13730       SDNode *Bitcast2 = *Trunc2->use_begin();
13731 
13732       if (Bitcast->getOpcode() != ISD::BITCAST ||
13733           Bitcast->getValueType(0) != MVT::f32)
13734         return false;
13735       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13736           Bitcast2->getValueType(0) != MVT::f32)
13737         return false;
13738 
13739       if (Subtarget.isLittleEndian())
13740         std::swap(Bitcast, Bitcast2);
13741 
13742       // Bitcast has the second float (in memory-layout order) and Bitcast2
13743       // has the first one.
13744 
13745       SDValue BasePtr = LD->getBasePtr();
13746       if (LD->isIndexed()) {
13747         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13748                "Non-pre-inc AM on PPC?");
13749         BasePtr =
13750           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13751                       LD->getOffset());
13752       }
13753 
13754       auto MMOFlags =
13755           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13756       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13757                                       LD->getPointerInfo(), LD->getAlignment(),
13758                                       MMOFlags, LD->getAAInfo());
13759       SDValue AddPtr =
13760         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13761                     BasePtr, DAG.getIntPtrConstant(4, dl));
13762       SDValue FloatLoad2 = DAG.getLoad(
13763           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13764           LD->getPointerInfo().getWithOffset(4),
13765           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13766 
13767       if (LD->isIndexed()) {
13768         // Note that DAGCombine should re-form any pre-increment load(s) from
13769         // what is produced here if that makes sense.
13770         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13771       }
13772 
13773       DCI.CombineTo(Bitcast2, FloatLoad);
13774       DCI.CombineTo(Bitcast, FloatLoad2);
13775 
13776       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13777                                     SDValue(FloatLoad2.getNode(), 1));
13778       return true;
13779     };
13780 
13781     if (ReplaceTwoFloatLoad())
13782       return SDValue(N, 0);
13783 
13784     EVT MemVT = LD->getMemoryVT();
13785     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13786     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13787     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13788     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13789     if (LD->isUnindexed() && VT.isVector() &&
13790         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13791           // P8 and later hardware should just use LOAD.
13792           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13793                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13794          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13795           LD->getAlignment() >= ScalarABIAlignment)) &&
13796         LD->getAlignment() < ABIAlignment) {
13797       // This is a type-legal unaligned Altivec or QPX load.
13798       SDValue Chain = LD->getChain();
13799       SDValue Ptr = LD->getBasePtr();
13800       bool isLittleEndian = Subtarget.isLittleEndian();
13801 
13802       // This implements the loading of unaligned vectors as described in
13803       // the venerable Apple Velocity Engine overview. Specifically:
13804       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13805       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13806       //
13807       // The general idea is to expand a sequence of one or more unaligned
13808       // loads into an alignment-based permutation-control instruction (lvsl
13809       // or lvsr), a series of regular vector loads (which always truncate
13810       // their input address to an aligned address), and a series of
13811       // permutations.  The results of these permutations are the requested
13812       // loaded values.  The trick is that the last "extra" load is not taken
13813       // from the address you might suspect (sizeof(vector) bytes after the
13814       // last requested load), but rather sizeof(vector) - 1 bytes after the
13815       // last requested vector. The point of this is to avoid a page fault if
13816       // the base address happened to be aligned. This works because if the
13817       // base address is aligned, then adding less than a full vector length
13818       // will cause the last vector in the sequence to be (re)loaded.
13819       // Otherwise, the next vector will be fetched as you might suspect was
13820       // necessary.
13821 
13822       // We might be able to reuse the permutation generation from
13823       // a different base address offset from this one by an aligned amount.
13824       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13825       // optimization later.
13826       Intrinsic::ID Intr, IntrLD, IntrPerm;
13827       MVT PermCntlTy, PermTy, LDTy;
13828       if (Subtarget.hasAltivec()) {
13829         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13830                                  Intrinsic::ppc_altivec_lvsl;
13831         IntrLD = Intrinsic::ppc_altivec_lvx;
13832         IntrPerm = Intrinsic::ppc_altivec_vperm;
13833         PermCntlTy = MVT::v16i8;
13834         PermTy = MVT::v4i32;
13835         LDTy = MVT::v4i32;
13836       } else {
13837         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13838                                        Intrinsic::ppc_qpx_qvlpcls;
13839         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13840                                        Intrinsic::ppc_qpx_qvlfs;
13841         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13842         PermCntlTy = MVT::v4f64;
13843         PermTy = MVT::v4f64;
13844         LDTy = MemVT.getSimpleVT();
13845       }
13846 
13847       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13848 
13849       // Create the new MMO for the new base load. It is like the original MMO,
13850       // but represents an area in memory almost twice the vector size centered
13851       // on the original address. If the address is unaligned, we might start
13852       // reading up to (sizeof(vector)-1) bytes below the address of the
13853       // original unaligned load.
13854       MachineFunction &MF = DAG.getMachineFunction();
13855       MachineMemOperand *BaseMMO =
13856         MF.getMachineMemOperand(LD->getMemOperand(),
13857                                 -(long)MemVT.getStoreSize()+1,
13858                                 2*MemVT.getStoreSize()-1);
13859 
13860       // Create the new base load.
13861       SDValue LDXIntID =
13862           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13863       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13864       SDValue BaseLoad =
13865         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13866                                 DAG.getVTList(PermTy, MVT::Other),
13867                                 BaseLoadOps, LDTy, BaseMMO);
13868 
13869       // Note that the value of IncOffset (which is provided to the next
13870       // load's pointer info offset value, and thus used to calculate the
13871       // alignment), and the value of IncValue (which is actually used to
13872       // increment the pointer value) are different! This is because we
13873       // require the next load to appear to be aligned, even though it
13874       // is actually offset from the base pointer by a lesser amount.
13875       int IncOffset = VT.getSizeInBits() / 8;
13876       int IncValue = IncOffset;
13877 
13878       // Walk (both up and down) the chain looking for another load at the real
13879       // (aligned) offset (the alignment of the other load does not matter in
13880       // this case). If found, then do not use the offset reduction trick, as
13881       // that will prevent the loads from being later combined (as they would
13882       // otherwise be duplicates).
13883       if (!findConsecutiveLoad(LD, DAG))
13884         --IncValue;
13885 
13886       SDValue Increment =
13887           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13888       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13889 
13890       MachineMemOperand *ExtraMMO =
13891         MF.getMachineMemOperand(LD->getMemOperand(),
13892                                 1, 2*MemVT.getStoreSize()-1);
13893       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13894       SDValue ExtraLoad =
13895         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13896                                 DAG.getVTList(PermTy, MVT::Other),
13897                                 ExtraLoadOps, LDTy, ExtraMMO);
13898 
13899       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13900         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13901 
13902       // Because vperm has a big-endian bias, we must reverse the order
13903       // of the input vectors and complement the permute control vector
13904       // when generating little endian code.  We have already handled the
13905       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13906       // and ExtraLoad here.
13907       SDValue Perm;
13908       if (isLittleEndian)
13909         Perm = BuildIntrinsicOp(IntrPerm,
13910                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13911       else
13912         Perm = BuildIntrinsicOp(IntrPerm,
13913                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13914 
13915       if (VT != PermTy)
13916         Perm = Subtarget.hasAltivec() ?
13917                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13918                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13919                                DAG.getTargetConstant(1, dl, MVT::i64));
13920                                // second argument is 1 because this rounding
13921                                // is always exact.
13922 
13923       // The output of the permutation is our loaded result, the TokenFactor is
13924       // our new chain.
13925       DCI.CombineTo(N, Perm, TF);
13926       return SDValue(N, 0);
13927     }
13928     }
13929     break;
13930     case ISD::INTRINSIC_WO_CHAIN: {
13931       bool isLittleEndian = Subtarget.isLittleEndian();
13932       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13933       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13934                                            : Intrinsic::ppc_altivec_lvsl);
13935       if ((IID == Intr ||
13936            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13937            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13938         N->getOperand(1)->getOpcode() == ISD::ADD) {
13939         SDValue Add = N->getOperand(1);
13940 
13941         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13942                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13943 
13944         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13945                                   APInt::getAllOnesValue(Bits /* alignment */)
13946                                       .zext(Add.getScalarValueSizeInBits()))) {
13947           SDNode *BasePtr = Add->getOperand(0).getNode();
13948           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13949                                     UE = BasePtr->use_end();
13950                UI != UE; ++UI) {
13951             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13952                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13953               // We've found another LVSL/LVSR, and this address is an aligned
13954               // multiple of that one. The results will be the same, so use the
13955               // one we've just found instead.
13956 
13957               return SDValue(*UI, 0);
13958             }
13959           }
13960         }
13961 
13962         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13963           SDNode *BasePtr = Add->getOperand(0).getNode();
13964           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13965                UE = BasePtr->use_end(); UI != UE; ++UI) {
13966             if (UI->getOpcode() == ISD::ADD &&
13967                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13968                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13969                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13970                 (1ULL << Bits) == 0) {
13971               SDNode *OtherAdd = *UI;
13972               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13973                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13974                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13975                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13976                   return SDValue(*VI, 0);
13977                 }
13978               }
13979             }
13980           }
13981         }
13982       }
13983 
13984       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13985       // Expose the vabsduw/h/b opportunity for down stream
13986       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13987           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13988            IID == Intrinsic::ppc_altivec_vmaxsh ||
13989            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13990         SDValue V1 = N->getOperand(1);
13991         SDValue V2 = N->getOperand(2);
13992         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13993              V1.getSimpleValueType() == MVT::v8i16 ||
13994              V1.getSimpleValueType() == MVT::v16i8) &&
13995             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13996           // (0-a, a)
13997           if (V1.getOpcode() == ISD::SUB &&
13998               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13999               V1.getOperand(1) == V2) {
14000             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14001           }
14002           // (a, 0-a)
14003           if (V2.getOpcode() == ISD::SUB &&
14004               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14005               V2.getOperand(1) == V1) {
14006             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14007           }
14008           // (x-y, y-x)
14009           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14010               V1.getOperand(0) == V2.getOperand(1) &&
14011               V1.getOperand(1) == V2.getOperand(0)) {
14012             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14013           }
14014         }
14015       }
14016     }
14017 
14018     break;
14019   case ISD::INTRINSIC_W_CHAIN:
14020     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14021     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14022     if (Subtarget.needsSwapsForVSXMemOps()) {
14023       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14024       default:
14025         break;
14026       case Intrinsic::ppc_vsx_lxvw4x:
14027       case Intrinsic::ppc_vsx_lxvd2x:
14028         return expandVSXLoadForLE(N, DCI);
14029       }
14030     }
14031     break;
14032   case ISD::INTRINSIC_VOID:
14033     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14034     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14035     if (Subtarget.needsSwapsForVSXMemOps()) {
14036       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14037       default:
14038         break;
14039       case Intrinsic::ppc_vsx_stxvw4x:
14040       case Intrinsic::ppc_vsx_stxvd2x:
14041         return expandVSXStoreForLE(N, DCI);
14042       }
14043     }
14044     break;
14045   case ISD::BSWAP:
14046     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14047     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14048         N->getOperand(0).hasOneUse() &&
14049         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14050          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14051           N->getValueType(0) == MVT::i64))) {
14052       SDValue Load = N->getOperand(0);
14053       LoadSDNode *LD = cast<LoadSDNode>(Load);
14054       // Create the byte-swapping load.
14055       SDValue Ops[] = {
14056         LD->getChain(),    // Chain
14057         LD->getBasePtr(),  // Ptr
14058         DAG.getValueType(N->getValueType(0)) // VT
14059       };
14060       SDValue BSLoad =
14061         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14062                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14063                                               MVT::i64 : MVT::i32, MVT::Other),
14064                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14065 
14066       // If this is an i16 load, insert the truncate.
14067       SDValue ResVal = BSLoad;
14068       if (N->getValueType(0) == MVT::i16)
14069         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14070 
14071       // First, combine the bswap away.  This makes the value produced by the
14072       // load dead.
14073       DCI.CombineTo(N, ResVal);
14074 
14075       // Next, combine the load away, we give it a bogus result value but a real
14076       // chain result.  The result value is dead because the bswap is dead.
14077       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14078 
14079       // Return N so it doesn't get rechecked!
14080       return SDValue(N, 0);
14081     }
14082     break;
14083   case PPCISD::VCMP:
14084     // If a VCMPo node already exists with exactly the same operands as this
14085     // node, use its result instead of this node (VCMPo computes both a CR6 and
14086     // a normal output).
14087     //
14088     if (!N->getOperand(0).hasOneUse() &&
14089         !N->getOperand(1).hasOneUse() &&
14090         !N->getOperand(2).hasOneUse()) {
14091 
14092       // Scan all of the users of the LHS, looking for VCMPo's that match.
14093       SDNode *VCMPoNode = nullptr;
14094 
14095       SDNode *LHSN = N->getOperand(0).getNode();
14096       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14097            UI != E; ++UI)
14098         if (UI->getOpcode() == PPCISD::VCMPo &&
14099             UI->getOperand(1) == N->getOperand(1) &&
14100             UI->getOperand(2) == N->getOperand(2) &&
14101             UI->getOperand(0) == N->getOperand(0)) {
14102           VCMPoNode = *UI;
14103           break;
14104         }
14105 
14106       // If there is no VCMPo node, or if the flag value has a single use, don't
14107       // transform this.
14108       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14109         break;
14110 
14111       // Look at the (necessarily single) use of the flag value.  If it has a
14112       // chain, this transformation is more complex.  Note that multiple things
14113       // could use the value result, which we should ignore.
14114       SDNode *FlagUser = nullptr;
14115       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14116            FlagUser == nullptr; ++UI) {
14117         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14118         SDNode *User = *UI;
14119         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14120           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14121             FlagUser = User;
14122             break;
14123           }
14124         }
14125       }
14126 
14127       // If the user is a MFOCRF instruction, we know this is safe.
14128       // Otherwise we give up for right now.
14129       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14130         return SDValue(VCMPoNode, 0);
14131     }
14132     break;
14133   case ISD::BRCOND: {
14134     SDValue Cond = N->getOperand(1);
14135     SDValue Target = N->getOperand(2);
14136 
14137     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14138         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14139           Intrinsic::loop_decrement) {
14140 
14141       // We now need to make the intrinsic dead (it cannot be instruction
14142       // selected).
14143       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14144       assert(Cond.getNode()->hasOneUse() &&
14145              "Counter decrement has more than one use");
14146 
14147       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14148                          N->getOperand(0), Target);
14149     }
14150   }
14151   break;
14152   case ISD::BR_CC: {
14153     // If this is a branch on an altivec predicate comparison, lower this so
14154     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14155     // lowering is done pre-legalize, because the legalizer lowers the predicate
14156     // compare down to code that is difficult to reassemble.
14157     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14158     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14159 
14160     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14161     // value. If so, pass-through the AND to get to the intrinsic.
14162     if (LHS.getOpcode() == ISD::AND &&
14163         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14164         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14165           Intrinsic::loop_decrement &&
14166         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14167         !isNullConstant(LHS.getOperand(1)))
14168       LHS = LHS.getOperand(0);
14169 
14170     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14171         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14172           Intrinsic::loop_decrement &&
14173         isa<ConstantSDNode>(RHS)) {
14174       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14175              "Counter decrement comparison is not EQ or NE");
14176 
14177       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14178       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14179                     (CC == ISD::SETNE && !Val);
14180 
14181       // We now need to make the intrinsic dead (it cannot be instruction
14182       // selected).
14183       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14184       assert(LHS.getNode()->hasOneUse() &&
14185              "Counter decrement has more than one use");
14186 
14187       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14188                          N->getOperand(0), N->getOperand(4));
14189     }
14190 
14191     int CompareOpc;
14192     bool isDot;
14193 
14194     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14195         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14196         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14197       assert(isDot && "Can't compare against a vector result!");
14198 
14199       // If this is a comparison against something other than 0/1, then we know
14200       // that the condition is never/always true.
14201       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14202       if (Val != 0 && Val != 1) {
14203         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14204           return N->getOperand(0);
14205         // Always !=, turn it into an unconditional branch.
14206         return DAG.getNode(ISD::BR, dl, MVT::Other,
14207                            N->getOperand(0), N->getOperand(4));
14208       }
14209 
14210       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14211 
14212       // Create the PPCISD altivec 'dot' comparison node.
14213       SDValue Ops[] = {
14214         LHS.getOperand(2),  // LHS of compare
14215         LHS.getOperand(3),  // RHS of compare
14216         DAG.getConstant(CompareOpc, dl, MVT::i32)
14217       };
14218       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14219       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14220 
14221       // Unpack the result based on how the target uses it.
14222       PPC::Predicate CompOpc;
14223       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14224       default:  // Can't happen, don't crash on invalid number though.
14225       case 0:   // Branch on the value of the EQ bit of CR6.
14226         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14227         break;
14228       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14229         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14230         break;
14231       case 2:   // Branch on the value of the LT bit of CR6.
14232         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14233         break;
14234       case 3:   // Branch on the inverted value of the LT bit of CR6.
14235         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14236         break;
14237       }
14238 
14239       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14240                          DAG.getConstant(CompOpc, dl, MVT::i32),
14241                          DAG.getRegister(PPC::CR6, MVT::i32),
14242                          N->getOperand(4), CompNode.getValue(1));
14243     }
14244     break;
14245   }
14246   case ISD::BUILD_VECTOR:
14247     return DAGCombineBuildVector(N, DCI);
14248   case ISD::ABS:
14249     return combineABS(N, DCI);
14250   case ISD::VSELECT:
14251     return combineVSelect(N, DCI);
14252   }
14253 
14254   return SDValue();
14255 }
14256 
14257 SDValue
14258 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14259                                  SelectionDAG &DAG,
14260                                  SmallVectorImpl<SDNode *> &Created) const {
14261   // fold (sdiv X, pow2)
14262   EVT VT = N->getValueType(0);
14263   if (VT == MVT::i64 && !Subtarget.isPPC64())
14264     return SDValue();
14265   if ((VT != MVT::i32 && VT != MVT::i64) ||
14266       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14267     return SDValue();
14268 
14269   SDLoc DL(N);
14270   SDValue N0 = N->getOperand(0);
14271 
14272   bool IsNegPow2 = (-Divisor).isPowerOf2();
14273   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14274   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14275 
14276   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14277   Created.push_back(Op.getNode());
14278 
14279   if (IsNegPow2) {
14280     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14281     Created.push_back(Op.getNode());
14282   }
14283 
14284   return Op;
14285 }
14286 
14287 //===----------------------------------------------------------------------===//
14288 // Inline Assembly Support
14289 //===----------------------------------------------------------------------===//
14290 
14291 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14292                                                       KnownBits &Known,
14293                                                       const APInt &DemandedElts,
14294                                                       const SelectionDAG &DAG,
14295                                                       unsigned Depth) const {
14296   Known.resetAll();
14297   switch (Op.getOpcode()) {
14298   default: break;
14299   case PPCISD::LBRX: {
14300     // lhbrx is known to have the top bits cleared out.
14301     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14302       Known.Zero = 0xFFFF0000;
14303     break;
14304   }
14305   case ISD::INTRINSIC_WO_CHAIN: {
14306     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14307     default: break;
14308     case Intrinsic::ppc_altivec_vcmpbfp_p:
14309     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14310     case Intrinsic::ppc_altivec_vcmpequb_p:
14311     case Intrinsic::ppc_altivec_vcmpequh_p:
14312     case Intrinsic::ppc_altivec_vcmpequw_p:
14313     case Intrinsic::ppc_altivec_vcmpequd_p:
14314     case Intrinsic::ppc_altivec_vcmpgefp_p:
14315     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14316     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14317     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14318     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14319     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14320     case Intrinsic::ppc_altivec_vcmpgtub_p:
14321     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14322     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14323     case Intrinsic::ppc_altivec_vcmpgtud_p:
14324       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14325       break;
14326     }
14327   }
14328   }
14329 }
14330 
14331 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14332   switch (Subtarget.getCPUDirective()) {
14333   default: break;
14334   case PPC::DIR_970:
14335   case PPC::DIR_PWR4:
14336   case PPC::DIR_PWR5:
14337   case PPC::DIR_PWR5X:
14338   case PPC::DIR_PWR6:
14339   case PPC::DIR_PWR6X:
14340   case PPC::DIR_PWR7:
14341   case PPC::DIR_PWR8:
14342   case PPC::DIR_PWR9:
14343   case PPC::DIR_PWR_FUTURE: {
14344     if (!ML)
14345       break;
14346 
14347     if (!DisableInnermostLoopAlign32) {
14348       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14349       // so that we can decrease cache misses and branch-prediction misses.
14350       // Actual alignment of the loop will depend on the hotness check and other
14351       // logic in alignBlocks.
14352       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14353         return Align(32);
14354     }
14355 
14356     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14357 
14358     // For small loops (between 5 and 8 instructions), align to a 32-byte
14359     // boundary so that the entire loop fits in one instruction-cache line.
14360     uint64_t LoopSize = 0;
14361     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14362       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14363         LoopSize += TII->getInstSizeInBytes(*J);
14364         if (LoopSize > 32)
14365           break;
14366       }
14367 
14368     if (LoopSize > 16 && LoopSize <= 32)
14369       return Align(32);
14370 
14371     break;
14372   }
14373   }
14374 
14375   return TargetLowering::getPrefLoopAlignment(ML);
14376 }
14377 
14378 /// getConstraintType - Given a constraint, return the type of
14379 /// constraint it is for this target.
14380 PPCTargetLowering::ConstraintType
14381 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14382   if (Constraint.size() == 1) {
14383     switch (Constraint[0]) {
14384     default: break;
14385     case 'b':
14386     case 'r':
14387     case 'f':
14388     case 'd':
14389     case 'v':
14390     case 'y':
14391       return C_RegisterClass;
14392     case 'Z':
14393       // FIXME: While Z does indicate a memory constraint, it specifically
14394       // indicates an r+r address (used in conjunction with the 'y' modifier
14395       // in the replacement string). Currently, we're forcing the base
14396       // register to be r0 in the asm printer (which is interpreted as zero)
14397       // and forming the complete address in the second register. This is
14398       // suboptimal.
14399       return C_Memory;
14400     }
14401   } else if (Constraint == "wc") { // individual CR bits.
14402     return C_RegisterClass;
14403   } else if (Constraint == "wa" || Constraint == "wd" ||
14404              Constraint == "wf" || Constraint == "ws" ||
14405              Constraint == "wi" || Constraint == "ww") {
14406     return C_RegisterClass; // VSX registers.
14407   }
14408   return TargetLowering::getConstraintType(Constraint);
14409 }
14410 
14411 /// Examine constraint type and operand type and determine a weight value.
14412 /// This object must already have been set up with the operand type
14413 /// and the current alternative constraint selected.
14414 TargetLowering::ConstraintWeight
14415 PPCTargetLowering::getSingleConstraintMatchWeight(
14416     AsmOperandInfo &info, const char *constraint) const {
14417   ConstraintWeight weight = CW_Invalid;
14418   Value *CallOperandVal = info.CallOperandVal;
14419     // If we don't have a value, we can't do a match,
14420     // but allow it at the lowest weight.
14421   if (!CallOperandVal)
14422     return CW_Default;
14423   Type *type = CallOperandVal->getType();
14424 
14425   // Look at the constraint type.
14426   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14427     return CW_Register; // an individual CR bit.
14428   else if ((StringRef(constraint) == "wa" ||
14429             StringRef(constraint) == "wd" ||
14430             StringRef(constraint) == "wf") &&
14431            type->isVectorTy())
14432     return CW_Register;
14433   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14434     return CW_Register; // just hold 64-bit integers data.
14435   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14436     return CW_Register;
14437   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14438     return CW_Register;
14439 
14440   switch (*constraint) {
14441   default:
14442     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14443     break;
14444   case 'b':
14445     if (type->isIntegerTy())
14446       weight = CW_Register;
14447     break;
14448   case 'f':
14449     if (type->isFloatTy())
14450       weight = CW_Register;
14451     break;
14452   case 'd':
14453     if (type->isDoubleTy())
14454       weight = CW_Register;
14455     break;
14456   case 'v':
14457     if (type->isVectorTy())
14458       weight = CW_Register;
14459     break;
14460   case 'y':
14461     weight = CW_Register;
14462     break;
14463   case 'Z':
14464     weight = CW_Memory;
14465     break;
14466   }
14467   return weight;
14468 }
14469 
14470 std::pair<unsigned, const TargetRegisterClass *>
14471 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14472                                                 StringRef Constraint,
14473                                                 MVT VT) const {
14474   if (Constraint.size() == 1) {
14475     // GCC RS6000 Constraint Letters
14476     switch (Constraint[0]) {
14477     case 'b':   // R1-R31
14478       if (VT == MVT::i64 && Subtarget.isPPC64())
14479         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14480       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14481     case 'r':   // R0-R31
14482       if (VT == MVT::i64 && Subtarget.isPPC64())
14483         return std::make_pair(0U, &PPC::G8RCRegClass);
14484       return std::make_pair(0U, &PPC::GPRCRegClass);
14485     // 'd' and 'f' constraints are both defined to be "the floating point
14486     // registers", where one is for 32-bit and the other for 64-bit. We don't
14487     // really care overly much here so just give them all the same reg classes.
14488     case 'd':
14489     case 'f':
14490       if (Subtarget.hasSPE()) {
14491         if (VT == MVT::f32 || VT == MVT::i32)
14492           return std::make_pair(0U, &PPC::GPRCRegClass);
14493         if (VT == MVT::f64 || VT == MVT::i64)
14494           return std::make_pair(0U, &PPC::SPERCRegClass);
14495       } else {
14496         if (VT == MVT::f32 || VT == MVT::i32)
14497           return std::make_pair(0U, &PPC::F4RCRegClass);
14498         if (VT == MVT::f64 || VT == MVT::i64)
14499           return std::make_pair(0U, &PPC::F8RCRegClass);
14500         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14501           return std::make_pair(0U, &PPC::QFRCRegClass);
14502         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14503           return std::make_pair(0U, &PPC::QSRCRegClass);
14504       }
14505       break;
14506     case 'v':
14507       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14508         return std::make_pair(0U, &PPC::QFRCRegClass);
14509       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14510         return std::make_pair(0U, &PPC::QSRCRegClass);
14511       if (Subtarget.hasAltivec())
14512         return std::make_pair(0U, &PPC::VRRCRegClass);
14513       break;
14514     case 'y':   // crrc
14515       return std::make_pair(0U, &PPC::CRRCRegClass);
14516     }
14517   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14518     // An individual CR bit.
14519     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14520   } else if ((Constraint == "wa" || Constraint == "wd" ||
14521              Constraint == "wf" || Constraint == "wi") &&
14522              Subtarget.hasVSX()) {
14523     return std::make_pair(0U, &PPC::VSRCRegClass);
14524   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14525     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14526       return std::make_pair(0U, &PPC::VSSRCRegClass);
14527     else
14528       return std::make_pair(0U, &PPC::VSFRCRegClass);
14529   }
14530 
14531   // If we name a VSX register, we can't defer to the base class because it
14532   // will not recognize the correct register (their names will be VSL{0-31}
14533   // and V{0-31} so they won't match). So we match them here.
14534   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14535     int VSNum = atoi(Constraint.data() + 3);
14536     assert(VSNum >= 0 && VSNum <= 63 &&
14537            "Attempted to access a vsr out of range");
14538     if (VSNum < 32)
14539       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14540     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14541   }
14542   std::pair<unsigned, const TargetRegisterClass *> R =
14543       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14544 
14545   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14546   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14547   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14548   // register.
14549   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14550   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14551   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14552       PPC::GPRCRegClass.contains(R.first))
14553     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14554                             PPC::sub_32, &PPC::G8RCRegClass),
14555                           &PPC::G8RCRegClass);
14556 
14557   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14558   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14559     R.first = PPC::CR0;
14560     R.second = &PPC::CRRCRegClass;
14561   }
14562 
14563   return R;
14564 }
14565 
14566 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14567 /// vector.  If it is invalid, don't add anything to Ops.
14568 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14569                                                      std::string &Constraint,
14570                                                      std::vector<SDValue>&Ops,
14571                                                      SelectionDAG &DAG) const {
14572   SDValue Result;
14573 
14574   // Only support length 1 constraints.
14575   if (Constraint.length() > 1) return;
14576 
14577   char Letter = Constraint[0];
14578   switch (Letter) {
14579   default: break;
14580   case 'I':
14581   case 'J':
14582   case 'K':
14583   case 'L':
14584   case 'M':
14585   case 'N':
14586   case 'O':
14587   case 'P': {
14588     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14589     if (!CST) return; // Must be an immediate to match.
14590     SDLoc dl(Op);
14591     int64_t Value = CST->getSExtValue();
14592     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14593                          // numbers are printed as such.
14594     switch (Letter) {
14595     default: llvm_unreachable("Unknown constraint letter!");
14596     case 'I':  // "I" is a signed 16-bit constant.
14597       if (isInt<16>(Value))
14598         Result = DAG.getTargetConstant(Value, dl, TCVT);
14599       break;
14600     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14601       if (isShiftedUInt<16, 16>(Value))
14602         Result = DAG.getTargetConstant(Value, dl, TCVT);
14603       break;
14604     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14605       if (isShiftedInt<16, 16>(Value))
14606         Result = DAG.getTargetConstant(Value, dl, TCVT);
14607       break;
14608     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14609       if (isUInt<16>(Value))
14610         Result = DAG.getTargetConstant(Value, dl, TCVT);
14611       break;
14612     case 'M':  // "M" is a constant that is greater than 31.
14613       if (Value > 31)
14614         Result = DAG.getTargetConstant(Value, dl, TCVT);
14615       break;
14616     case 'N':  // "N" is a positive constant that is an exact power of two.
14617       if (Value > 0 && isPowerOf2_64(Value))
14618         Result = DAG.getTargetConstant(Value, dl, TCVT);
14619       break;
14620     case 'O':  // "O" is the constant zero.
14621       if (Value == 0)
14622         Result = DAG.getTargetConstant(Value, dl, TCVT);
14623       break;
14624     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14625       if (isInt<16>(-Value))
14626         Result = DAG.getTargetConstant(Value, dl, TCVT);
14627       break;
14628     }
14629     break;
14630   }
14631   }
14632 
14633   if (Result.getNode()) {
14634     Ops.push_back(Result);
14635     return;
14636   }
14637 
14638   // Handle standard constraint letters.
14639   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14640 }
14641 
14642 // isLegalAddressingMode - Return true if the addressing mode represented
14643 // by AM is legal for this target, for a load/store of the specified type.
14644 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14645                                               const AddrMode &AM, Type *Ty,
14646                                               unsigned AS, Instruction *I) const {
14647   // PPC does not allow r+i addressing modes for vectors!
14648   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14649     return false;
14650 
14651   // PPC allows a sign-extended 16-bit immediate field.
14652   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14653     return false;
14654 
14655   // No global is ever allowed as a base.
14656   if (AM.BaseGV)
14657     return false;
14658 
14659   // PPC only support r+r,
14660   switch (AM.Scale) {
14661   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14662     break;
14663   case 1:
14664     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14665       return false;
14666     // Otherwise we have r+r or r+i.
14667     break;
14668   case 2:
14669     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14670       return false;
14671     // Allow 2*r as r+r.
14672     break;
14673   default:
14674     // No other scales are supported.
14675     return false;
14676   }
14677 
14678   return true;
14679 }
14680 
14681 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14682                                            SelectionDAG &DAG) const {
14683   MachineFunction &MF = DAG.getMachineFunction();
14684   MachineFrameInfo &MFI = MF.getFrameInfo();
14685   MFI.setReturnAddressIsTaken(true);
14686 
14687   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14688     return SDValue();
14689 
14690   SDLoc dl(Op);
14691   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14692 
14693   // Make sure the function does not optimize away the store of the RA to
14694   // the stack.
14695   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14696   FuncInfo->setLRStoreRequired();
14697   bool isPPC64 = Subtarget.isPPC64();
14698   auto PtrVT = getPointerTy(MF.getDataLayout());
14699 
14700   if (Depth > 0) {
14701     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14702     SDValue Offset =
14703         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14704                         isPPC64 ? MVT::i64 : MVT::i32);
14705     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14706                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14707                        MachinePointerInfo());
14708   }
14709 
14710   // Just load the return address off the stack.
14711   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14712   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14713                      MachinePointerInfo());
14714 }
14715 
14716 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14717                                           SelectionDAG &DAG) const {
14718   SDLoc dl(Op);
14719   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14720 
14721   MachineFunction &MF = DAG.getMachineFunction();
14722   MachineFrameInfo &MFI = MF.getFrameInfo();
14723   MFI.setFrameAddressIsTaken(true);
14724 
14725   EVT PtrVT = getPointerTy(MF.getDataLayout());
14726   bool isPPC64 = PtrVT == MVT::i64;
14727 
14728   // Naked functions never have a frame pointer, and so we use r1. For all
14729   // other functions, this decision must be delayed until during PEI.
14730   unsigned FrameReg;
14731   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14732     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14733   else
14734     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14735 
14736   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14737                                          PtrVT);
14738   while (Depth--)
14739     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14740                             FrameAddr, MachinePointerInfo());
14741   return FrameAddr;
14742 }
14743 
14744 // FIXME? Maybe this could be a TableGen attribute on some registers and
14745 // this table could be generated automatically from RegInfo.
14746 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14747                                               const MachineFunction &MF) const {
14748   bool isPPC64 = Subtarget.isPPC64();
14749   bool IsDarwinABI = Subtarget.isDarwinABI();
14750 
14751   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14752       (!isPPC64 && VT != MVT::i32))
14753     report_fatal_error("Invalid register global variable type");
14754 
14755   bool is64Bit = isPPC64 && VT == MVT::i64;
14756   Register Reg = StringSwitch<Register>(RegName)
14757                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14758                    .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2)
14759                    .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() :
14760                                   (is64Bit ? PPC::X13 : PPC::R13))
14761                    .Default(Register());
14762 
14763   if (Reg)
14764     return Reg;
14765   report_fatal_error("Invalid register name global variable");
14766 }
14767 
14768 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14769   // 32-bit SVR4 ABI access everything as got-indirect.
14770   if (Subtarget.is32BitELFABI())
14771     return true;
14772 
14773   // AIX accesses everything indirectly through the TOC, which is similar to
14774   // the GOT.
14775   if (Subtarget.isAIXABI())
14776     return true;
14777 
14778   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14779   // If it is small or large code model, module locals are accessed
14780   // indirectly by loading their address from .toc/.got.
14781   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14782     return true;
14783 
14784   // JumpTable and BlockAddress are accessed as got-indirect.
14785   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14786     return true;
14787 
14788   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14789     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14790 
14791   return false;
14792 }
14793 
14794 bool
14795 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14796   // The PowerPC target isn't yet aware of offsets.
14797   return false;
14798 }
14799 
14800 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14801                                            const CallInst &I,
14802                                            MachineFunction &MF,
14803                                            unsigned Intrinsic) const {
14804   switch (Intrinsic) {
14805   case Intrinsic::ppc_qpx_qvlfd:
14806   case Intrinsic::ppc_qpx_qvlfs:
14807   case Intrinsic::ppc_qpx_qvlfcd:
14808   case Intrinsic::ppc_qpx_qvlfcs:
14809   case Intrinsic::ppc_qpx_qvlfiwa:
14810   case Intrinsic::ppc_qpx_qvlfiwz:
14811   case Intrinsic::ppc_altivec_lvx:
14812   case Intrinsic::ppc_altivec_lvxl:
14813   case Intrinsic::ppc_altivec_lvebx:
14814   case Intrinsic::ppc_altivec_lvehx:
14815   case Intrinsic::ppc_altivec_lvewx:
14816   case Intrinsic::ppc_vsx_lxvd2x:
14817   case Intrinsic::ppc_vsx_lxvw4x: {
14818     EVT VT;
14819     switch (Intrinsic) {
14820     case Intrinsic::ppc_altivec_lvebx:
14821       VT = MVT::i8;
14822       break;
14823     case Intrinsic::ppc_altivec_lvehx:
14824       VT = MVT::i16;
14825       break;
14826     case Intrinsic::ppc_altivec_lvewx:
14827       VT = MVT::i32;
14828       break;
14829     case Intrinsic::ppc_vsx_lxvd2x:
14830       VT = MVT::v2f64;
14831       break;
14832     case Intrinsic::ppc_qpx_qvlfd:
14833       VT = MVT::v4f64;
14834       break;
14835     case Intrinsic::ppc_qpx_qvlfs:
14836       VT = MVT::v4f32;
14837       break;
14838     case Intrinsic::ppc_qpx_qvlfcd:
14839       VT = MVT::v2f64;
14840       break;
14841     case Intrinsic::ppc_qpx_qvlfcs:
14842       VT = MVT::v2f32;
14843       break;
14844     default:
14845       VT = MVT::v4i32;
14846       break;
14847     }
14848 
14849     Info.opc = ISD::INTRINSIC_W_CHAIN;
14850     Info.memVT = VT;
14851     Info.ptrVal = I.getArgOperand(0);
14852     Info.offset = -VT.getStoreSize()+1;
14853     Info.size = 2*VT.getStoreSize()-1;
14854     Info.align = Align::None();
14855     Info.flags = MachineMemOperand::MOLoad;
14856     return true;
14857   }
14858   case Intrinsic::ppc_qpx_qvlfda:
14859   case Intrinsic::ppc_qpx_qvlfsa:
14860   case Intrinsic::ppc_qpx_qvlfcda:
14861   case Intrinsic::ppc_qpx_qvlfcsa:
14862   case Intrinsic::ppc_qpx_qvlfiwaa:
14863   case Intrinsic::ppc_qpx_qvlfiwza: {
14864     EVT VT;
14865     switch (Intrinsic) {
14866     case Intrinsic::ppc_qpx_qvlfda:
14867       VT = MVT::v4f64;
14868       break;
14869     case Intrinsic::ppc_qpx_qvlfsa:
14870       VT = MVT::v4f32;
14871       break;
14872     case Intrinsic::ppc_qpx_qvlfcda:
14873       VT = MVT::v2f64;
14874       break;
14875     case Intrinsic::ppc_qpx_qvlfcsa:
14876       VT = MVT::v2f32;
14877       break;
14878     default:
14879       VT = MVT::v4i32;
14880       break;
14881     }
14882 
14883     Info.opc = ISD::INTRINSIC_W_CHAIN;
14884     Info.memVT = VT;
14885     Info.ptrVal = I.getArgOperand(0);
14886     Info.offset = 0;
14887     Info.size = VT.getStoreSize();
14888     Info.align = Align::None();
14889     Info.flags = MachineMemOperand::MOLoad;
14890     return true;
14891   }
14892   case Intrinsic::ppc_qpx_qvstfd:
14893   case Intrinsic::ppc_qpx_qvstfs:
14894   case Intrinsic::ppc_qpx_qvstfcd:
14895   case Intrinsic::ppc_qpx_qvstfcs:
14896   case Intrinsic::ppc_qpx_qvstfiw:
14897   case Intrinsic::ppc_altivec_stvx:
14898   case Intrinsic::ppc_altivec_stvxl:
14899   case Intrinsic::ppc_altivec_stvebx:
14900   case Intrinsic::ppc_altivec_stvehx:
14901   case Intrinsic::ppc_altivec_stvewx:
14902   case Intrinsic::ppc_vsx_stxvd2x:
14903   case Intrinsic::ppc_vsx_stxvw4x: {
14904     EVT VT;
14905     switch (Intrinsic) {
14906     case Intrinsic::ppc_altivec_stvebx:
14907       VT = MVT::i8;
14908       break;
14909     case Intrinsic::ppc_altivec_stvehx:
14910       VT = MVT::i16;
14911       break;
14912     case Intrinsic::ppc_altivec_stvewx:
14913       VT = MVT::i32;
14914       break;
14915     case Intrinsic::ppc_vsx_stxvd2x:
14916       VT = MVT::v2f64;
14917       break;
14918     case Intrinsic::ppc_qpx_qvstfd:
14919       VT = MVT::v4f64;
14920       break;
14921     case Intrinsic::ppc_qpx_qvstfs:
14922       VT = MVT::v4f32;
14923       break;
14924     case Intrinsic::ppc_qpx_qvstfcd:
14925       VT = MVT::v2f64;
14926       break;
14927     case Intrinsic::ppc_qpx_qvstfcs:
14928       VT = MVT::v2f32;
14929       break;
14930     default:
14931       VT = MVT::v4i32;
14932       break;
14933     }
14934 
14935     Info.opc = ISD::INTRINSIC_VOID;
14936     Info.memVT = VT;
14937     Info.ptrVal = I.getArgOperand(1);
14938     Info.offset = -VT.getStoreSize()+1;
14939     Info.size = 2*VT.getStoreSize()-1;
14940     Info.align = Align::None();
14941     Info.flags = MachineMemOperand::MOStore;
14942     return true;
14943   }
14944   case Intrinsic::ppc_qpx_qvstfda:
14945   case Intrinsic::ppc_qpx_qvstfsa:
14946   case Intrinsic::ppc_qpx_qvstfcda:
14947   case Intrinsic::ppc_qpx_qvstfcsa:
14948   case Intrinsic::ppc_qpx_qvstfiwa: {
14949     EVT VT;
14950     switch (Intrinsic) {
14951     case Intrinsic::ppc_qpx_qvstfda:
14952       VT = MVT::v4f64;
14953       break;
14954     case Intrinsic::ppc_qpx_qvstfsa:
14955       VT = MVT::v4f32;
14956       break;
14957     case Intrinsic::ppc_qpx_qvstfcda:
14958       VT = MVT::v2f64;
14959       break;
14960     case Intrinsic::ppc_qpx_qvstfcsa:
14961       VT = MVT::v2f32;
14962       break;
14963     default:
14964       VT = MVT::v4i32;
14965       break;
14966     }
14967 
14968     Info.opc = ISD::INTRINSIC_VOID;
14969     Info.memVT = VT;
14970     Info.ptrVal = I.getArgOperand(1);
14971     Info.offset = 0;
14972     Info.size = VT.getStoreSize();
14973     Info.align = Align::None();
14974     Info.flags = MachineMemOperand::MOStore;
14975     return true;
14976   }
14977   default:
14978     break;
14979   }
14980 
14981   return false;
14982 }
14983 
14984 /// getOptimalMemOpType - Returns the target specific optimal type for load
14985 /// and store operations as a result of memset, memcpy, and memmove
14986 /// lowering. If DstAlign is zero that means it's safe to destination
14987 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14988 /// means there isn't a need to check it against alignment requirement,
14989 /// probably because the source does not need to be loaded. If 'IsMemset' is
14990 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14991 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14992 /// source is constant so it does not need to be loaded.
14993 /// It returns EVT::Other if the type should be determined using generic
14994 /// target-independent logic.
14995 EVT PPCTargetLowering::getOptimalMemOpType(
14996     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14997     bool ZeroMemset, bool MemcpyStrSrc,
14998     const AttributeList &FuncAttributes) const {
14999   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15000     // When expanding a memset, require at least two QPX instructions to cover
15001     // the cost of loading the value to be stored from the constant pool.
15002     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
15003        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
15004         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15005       return MVT::v4f64;
15006     }
15007 
15008     // We should use Altivec/VSX loads and stores when available. For unaligned
15009     // addresses, unaligned VSX loads are only fast starting with the P8.
15010     if (Subtarget.hasAltivec() && Size >= 16 &&
15011         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
15012          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15013       return MVT::v4i32;
15014   }
15015 
15016   if (Subtarget.isPPC64()) {
15017     return MVT::i64;
15018   }
15019 
15020   return MVT::i32;
15021 }
15022 
15023 /// Returns true if it is beneficial to convert a load of a constant
15024 /// to just the constant itself.
15025 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15026                                                           Type *Ty) const {
15027   assert(Ty->isIntegerTy());
15028 
15029   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15030   return !(BitSize == 0 || BitSize > 64);
15031 }
15032 
15033 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15034   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15035     return false;
15036   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15037   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15038   return NumBits1 == 64 && NumBits2 == 32;
15039 }
15040 
15041 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15042   if (!VT1.isInteger() || !VT2.isInteger())
15043     return false;
15044   unsigned NumBits1 = VT1.getSizeInBits();
15045   unsigned NumBits2 = VT2.getSizeInBits();
15046   return NumBits1 == 64 && NumBits2 == 32;
15047 }
15048 
15049 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15050   // Generally speaking, zexts are not free, but they are free when they can be
15051   // folded with other operations.
15052   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15053     EVT MemVT = LD->getMemoryVT();
15054     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15055          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15056         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15057          LD->getExtensionType() == ISD::ZEXTLOAD))
15058       return true;
15059   }
15060 
15061   // FIXME: Add other cases...
15062   //  - 32-bit shifts with a zext to i64
15063   //  - zext after ctlz, bswap, etc.
15064   //  - zext after and by a constant mask
15065 
15066   return TargetLowering::isZExtFree(Val, VT2);
15067 }
15068 
15069 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15070   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15071          "invalid fpext types");
15072   // Extending to float128 is not free.
15073   if (DestVT == MVT::f128)
15074     return false;
15075   return true;
15076 }
15077 
15078 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15079   return isInt<16>(Imm) || isUInt<16>(Imm);
15080 }
15081 
15082 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15083   return isInt<16>(Imm) || isUInt<16>(Imm);
15084 }
15085 
15086 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15087                                                        unsigned,
15088                                                        unsigned,
15089                                                        MachineMemOperand::Flags,
15090                                                        bool *Fast) const {
15091   if (DisablePPCUnaligned)
15092     return false;
15093 
15094   // PowerPC supports unaligned memory access for simple non-vector types.
15095   // Although accessing unaligned addresses is not as efficient as accessing
15096   // aligned addresses, it is generally more efficient than manual expansion,
15097   // and generally only traps for software emulation when crossing page
15098   // boundaries.
15099 
15100   if (!VT.isSimple())
15101     return false;
15102 
15103   if (VT.getSimpleVT().isVector()) {
15104     if (Subtarget.hasVSX()) {
15105       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15106           VT != MVT::v4f32 && VT != MVT::v4i32)
15107         return false;
15108     } else {
15109       return false;
15110     }
15111   }
15112 
15113   if (VT == MVT::ppcf128)
15114     return false;
15115 
15116   if (Fast)
15117     *Fast = true;
15118 
15119   return true;
15120 }
15121 
15122 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15123                                                    EVT VT) const {
15124   VT = VT.getScalarType();
15125 
15126   if (!VT.isSimple())
15127     return false;
15128 
15129   switch (VT.getSimpleVT().SimpleTy) {
15130   case MVT::f32:
15131   case MVT::f64:
15132     return true;
15133   case MVT::f128:
15134     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15135   default:
15136     break;
15137   }
15138 
15139   return false;
15140 }
15141 
15142 const MCPhysReg *
15143 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15144   // LR is a callee-save register, but we must treat it as clobbered by any call
15145   // site. Hence we include LR in the scratch registers, which are in turn added
15146   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15147   // to CTR, which is used by any indirect call.
15148   static const MCPhysReg ScratchRegs[] = {
15149     PPC::X12, PPC::LR8, PPC::CTR8, 0
15150   };
15151 
15152   return ScratchRegs;
15153 }
15154 
15155 unsigned PPCTargetLowering::getExceptionPointerRegister(
15156     const Constant *PersonalityFn) const {
15157   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15158 }
15159 
15160 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15161     const Constant *PersonalityFn) const {
15162   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15163 }
15164 
15165 bool
15166 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15167                      EVT VT , unsigned DefinedValues) const {
15168   if (VT == MVT::v2i64)
15169     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15170 
15171   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15172     return true;
15173 
15174   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15175 }
15176 
15177 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15178   if (DisableILPPref || Subtarget.enableMachineScheduler())
15179     return TargetLowering::getSchedulingPreference(N);
15180 
15181   return Sched::ILP;
15182 }
15183 
15184 // Create a fast isel object.
15185 FastISel *
15186 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15187                                   const TargetLibraryInfo *LibInfo) const {
15188   return PPC::createFastISel(FuncInfo, LibInfo);
15189 }
15190 
15191 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15192   if (Subtarget.isDarwinABI()) return;
15193   if (!Subtarget.isPPC64()) return;
15194 
15195   // Update IsSplitCSR in PPCFunctionInfo
15196   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15197   PFI->setIsSplitCSR(true);
15198 }
15199 
15200 void PPCTargetLowering::insertCopiesSplitCSR(
15201   MachineBasicBlock *Entry,
15202   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15203   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15204   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15205   if (!IStart)
15206     return;
15207 
15208   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15209   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15210   MachineBasicBlock::iterator MBBI = Entry->begin();
15211   for (const MCPhysReg *I = IStart; *I; ++I) {
15212     const TargetRegisterClass *RC = nullptr;
15213     if (PPC::G8RCRegClass.contains(*I))
15214       RC = &PPC::G8RCRegClass;
15215     else if (PPC::F8RCRegClass.contains(*I))
15216       RC = &PPC::F8RCRegClass;
15217     else if (PPC::CRRCRegClass.contains(*I))
15218       RC = &PPC::CRRCRegClass;
15219     else if (PPC::VRRCRegClass.contains(*I))
15220       RC = &PPC::VRRCRegClass;
15221     else
15222       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15223 
15224     Register NewVR = MRI->createVirtualRegister(RC);
15225     // Create copy from CSR to a virtual register.
15226     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15227     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15228     // nounwind. If we want to generalize this later, we may need to emit
15229     // CFI pseudo-instructions.
15230     assert(Entry->getParent()->getFunction().hasFnAttribute(
15231              Attribute::NoUnwind) &&
15232            "Function should be nounwind in insertCopiesSplitCSR!");
15233     Entry->addLiveIn(*I);
15234     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15235       .addReg(*I);
15236 
15237     // Insert the copy-back instructions right before the terminator.
15238     for (auto *Exit : Exits)
15239       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15240               TII->get(TargetOpcode::COPY), *I)
15241         .addReg(NewVR);
15242   }
15243 }
15244 
15245 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15246 bool PPCTargetLowering::useLoadStackGuardNode() const {
15247   if (!Subtarget.isTargetLinux())
15248     return TargetLowering::useLoadStackGuardNode();
15249   return true;
15250 }
15251 
15252 // Override to disable global variable loading on Linux.
15253 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15254   if (!Subtarget.isTargetLinux())
15255     return TargetLowering::insertSSPDeclarations(M);
15256 }
15257 
15258 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15259                                      bool ForCodeSize) const {
15260   if (!VT.isSimple() || !Subtarget.hasVSX())
15261     return false;
15262 
15263   switch(VT.getSimpleVT().SimpleTy) {
15264   default:
15265     // For FP types that are currently not supported by PPC backend, return
15266     // false. Examples: f16, f80.
15267     return false;
15268   case MVT::f32:
15269   case MVT::f64:
15270   case MVT::ppcf128:
15271     return Imm.isPosZero();
15272   }
15273 }
15274 
15275 // For vector shift operation op, fold
15276 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15277 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15278                                   SelectionDAG &DAG) {
15279   SDValue N0 = N->getOperand(0);
15280   SDValue N1 = N->getOperand(1);
15281   EVT VT = N0.getValueType();
15282   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15283   unsigned Opcode = N->getOpcode();
15284   unsigned TargetOpcode;
15285 
15286   switch (Opcode) {
15287   default:
15288     llvm_unreachable("Unexpected shift operation");
15289   case ISD::SHL:
15290     TargetOpcode = PPCISD::SHL;
15291     break;
15292   case ISD::SRL:
15293     TargetOpcode = PPCISD::SRL;
15294     break;
15295   case ISD::SRA:
15296     TargetOpcode = PPCISD::SRA;
15297     break;
15298   }
15299 
15300   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15301       N1->getOpcode() == ISD::AND)
15302     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15303       if (Mask->getZExtValue() == OpSizeInBits - 1)
15304         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15305 
15306   return SDValue();
15307 }
15308 
15309 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15310   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15311     return Value;
15312 
15313   SDValue N0 = N->getOperand(0);
15314   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15315   if (!Subtarget.isISA3_0() ||
15316       N0.getOpcode() != ISD::SIGN_EXTEND ||
15317       N0.getOperand(0).getValueType() != MVT::i32 ||
15318       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15319     return SDValue();
15320 
15321   // We can't save an operation here if the value is already extended, and
15322   // the existing shift is easier to combine.
15323   SDValue ExtsSrc = N0.getOperand(0);
15324   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15325       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15326     return SDValue();
15327 
15328   SDLoc DL(N0);
15329   SDValue ShiftBy = SDValue(CN1, 0);
15330   // We want the shift amount to be i32 on the extswli, but the shift could
15331   // have an i64.
15332   if (ShiftBy.getValueType() == MVT::i64)
15333     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15334 
15335   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15336                          ShiftBy);
15337 }
15338 
15339 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15340   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15341     return Value;
15342 
15343   return SDValue();
15344 }
15345 
15346 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15347   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15348     return Value;
15349 
15350   return SDValue();
15351 }
15352 
15353 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15354 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15355 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15356 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15357 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15358                                  const PPCSubtarget &Subtarget) {
15359   if (!Subtarget.isPPC64())
15360     return SDValue();
15361 
15362   SDValue LHS = N->getOperand(0);
15363   SDValue RHS = N->getOperand(1);
15364 
15365   auto isZextOfCompareWithConstant = [](SDValue Op) {
15366     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15367         Op.getValueType() != MVT::i64)
15368       return false;
15369 
15370     SDValue Cmp = Op.getOperand(0);
15371     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15372         Cmp.getOperand(0).getValueType() != MVT::i64)
15373       return false;
15374 
15375     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15376       int64_t NegConstant = 0 - Constant->getSExtValue();
15377       // Due to the limitations of the addi instruction,
15378       // -C is required to be [-32768, 32767].
15379       return isInt<16>(NegConstant);
15380     }
15381 
15382     return false;
15383   };
15384 
15385   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15386   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15387 
15388   // If there is a pattern, canonicalize a zext operand to the RHS.
15389   if (LHSHasPattern && !RHSHasPattern)
15390     std::swap(LHS, RHS);
15391   else if (!LHSHasPattern && !RHSHasPattern)
15392     return SDValue();
15393 
15394   SDLoc DL(N);
15395   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15396   SDValue Cmp = RHS.getOperand(0);
15397   SDValue Z = Cmp.getOperand(0);
15398   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15399 
15400   assert(Constant && "Constant Should not be a null pointer.");
15401   int64_t NegConstant = 0 - Constant->getSExtValue();
15402 
15403   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15404   default: break;
15405   case ISD::SETNE: {
15406     //                                 when C == 0
15407     //                             --> addze X, (addic Z, -1).carry
15408     //                            /
15409     // add X, (zext(setne Z, C))--
15410     //                            \    when -32768 <= -C <= 32767 && C != 0
15411     //                             --> addze X, (addic (addi Z, -C), -1).carry
15412     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15413                               DAG.getConstant(NegConstant, DL, MVT::i64));
15414     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15415     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15416                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15417     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15418                        SDValue(Addc.getNode(), 1));
15419     }
15420   case ISD::SETEQ: {
15421     //                                 when C == 0
15422     //                             --> addze X, (subfic Z, 0).carry
15423     //                            /
15424     // add X, (zext(sete  Z, C))--
15425     //                            \    when -32768 <= -C <= 32767 && C != 0
15426     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15427     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15428                               DAG.getConstant(NegConstant, DL, MVT::i64));
15429     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15430     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15431                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15432     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15433                        SDValue(Subc.getNode(), 1));
15434     }
15435   }
15436 
15437   return SDValue();
15438 }
15439 
15440 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15441   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15442     return Value;
15443 
15444   return SDValue();
15445 }
15446 
15447 // Detect TRUNCATE operations on bitcasts of float128 values.
15448 // What we are looking for here is the situtation where we extract a subset
15449 // of bits from a 128 bit float.
15450 // This can be of two forms:
15451 // 1) BITCAST of f128 feeding TRUNCATE
15452 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15453 // The reason this is required is because we do not have a legal i128 type
15454 // and so we want to prevent having to store the f128 and then reload part
15455 // of it.
15456 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15457                                            DAGCombinerInfo &DCI) const {
15458   // If we are using CRBits then try that first.
15459   if (Subtarget.useCRBits()) {
15460     // Check if CRBits did anything and return that if it did.
15461     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15462       return CRTruncValue;
15463   }
15464 
15465   SDLoc dl(N);
15466   SDValue Op0 = N->getOperand(0);
15467 
15468   // Looking for a truncate of i128 to i64.
15469   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15470     return SDValue();
15471 
15472   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15473 
15474   // SRL feeding TRUNCATE.
15475   if (Op0.getOpcode() == ISD::SRL) {
15476     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15477     // The right shift has to be by 64 bits.
15478     if (!ConstNode || ConstNode->getZExtValue() != 64)
15479       return SDValue();
15480 
15481     // Switch the element number to extract.
15482     EltToExtract = EltToExtract ? 0 : 1;
15483     // Update Op0 past the SRL.
15484     Op0 = Op0.getOperand(0);
15485   }
15486 
15487   // BITCAST feeding a TRUNCATE possibly via SRL.
15488   if (Op0.getOpcode() == ISD::BITCAST &&
15489       Op0.getValueType() == MVT::i128 &&
15490       Op0.getOperand(0).getValueType() == MVT::f128) {
15491     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15492     return DCI.DAG.getNode(
15493         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15494         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15495   }
15496   return SDValue();
15497 }
15498 
15499 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15500   SelectionDAG &DAG = DCI.DAG;
15501 
15502   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15503   if (!ConstOpOrElement)
15504     return SDValue();
15505 
15506   // An imul is usually smaller than the alternative sequence for legal type.
15507   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15508       isOperationLegal(ISD::MUL, N->getValueType(0)))
15509     return SDValue();
15510 
15511   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15512     switch (this->Subtarget.getCPUDirective()) {
15513     default:
15514       // TODO: enhance the condition for subtarget before pwr8
15515       return false;
15516     case PPC::DIR_PWR8:
15517       //  type        mul     add    shl
15518       // scalar        4       1      1
15519       // vector        7       2      2
15520       return true;
15521     case PPC::DIR_PWR9:
15522     case PPC::DIR_PWR_FUTURE:
15523       //  type        mul     add    shl
15524       // scalar        5       2      2
15525       // vector        7       2      2
15526 
15527       // The cycle RATIO of related operations are showed as a table above.
15528       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15529       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15530       // are 4, it is always profitable; but for 3 instrs patterns
15531       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15532       // So we should only do it for vector type.
15533       return IsAddOne && IsNeg ? VT.isVector() : true;
15534     }
15535   };
15536 
15537   EVT VT = N->getValueType(0);
15538   SDLoc DL(N);
15539 
15540   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15541   bool IsNeg = MulAmt.isNegative();
15542   APInt MulAmtAbs = MulAmt.abs();
15543 
15544   if ((MulAmtAbs - 1).isPowerOf2()) {
15545     // (mul x, 2^N + 1) => (add (shl x, N), x)
15546     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15547 
15548     if (!IsProfitable(IsNeg, true, VT))
15549       return SDValue();
15550 
15551     SDValue Op0 = N->getOperand(0);
15552     SDValue Op1 =
15553         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15554                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15555     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15556 
15557     if (!IsNeg)
15558       return Res;
15559 
15560     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15561   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15562     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15563     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15564 
15565     if (!IsProfitable(IsNeg, false, VT))
15566       return SDValue();
15567 
15568     SDValue Op0 = N->getOperand(0);
15569     SDValue Op1 =
15570         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15571                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15572 
15573     if (!IsNeg)
15574       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15575     else
15576       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15577 
15578   } else {
15579     return SDValue();
15580   }
15581 }
15582 
15583 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15584   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15585   if (!Subtarget.is64BitELFABI())
15586     return false;
15587 
15588   // If not a tail call then no need to proceed.
15589   if (!CI->isTailCall())
15590     return false;
15591 
15592   // If tail calls are disabled for the caller then we are done.
15593   const Function *Caller = CI->getParent()->getParent();
15594   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15595   if (Attr.getValueAsString() == "true")
15596     return false;
15597 
15598   // If sibling calls have been disabled and tail-calls aren't guaranteed
15599   // there is no reason to duplicate.
15600   auto &TM = getTargetMachine();
15601   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15602     return false;
15603 
15604   // Can't tail call a function called indirectly, or if it has variadic args.
15605   const Function *Callee = CI->getCalledFunction();
15606   if (!Callee || Callee->isVarArg())
15607     return false;
15608 
15609   // Make sure the callee and caller calling conventions are eligible for tco.
15610   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15611                                            CI->getCallingConv()))
15612       return false;
15613 
15614   // If the function is local then we have a good chance at tail-calling it
15615   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15616 }
15617 
15618 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15619   if (!Subtarget.hasVSX())
15620     return false;
15621   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15622     return true;
15623   return VT == MVT::f32 || VT == MVT::f64 ||
15624     VT == MVT::v4f32 || VT == MVT::v2f64;
15625 }
15626 
15627 bool PPCTargetLowering::
15628 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15629   const Value *Mask = AndI.getOperand(1);
15630   // If the mask is suitable for andi. or andis. we should sink the and.
15631   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15632     // Can't handle constants wider than 64-bits.
15633     if (CI->getBitWidth() > 64)
15634       return false;
15635     int64_t ConstVal = CI->getZExtValue();
15636     return isUInt<16>(ConstVal) ||
15637       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15638   }
15639 
15640   // For non-constant masks, we can always use the record-form and.
15641   return true;
15642 }
15643 
15644 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15645 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15646 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15647 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15648 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15649 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15650   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15651   assert(Subtarget.hasP9Altivec() &&
15652          "Only combine this when P9 altivec supported!");
15653   EVT VT = N->getValueType(0);
15654   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15655     return SDValue();
15656 
15657   SelectionDAG &DAG = DCI.DAG;
15658   SDLoc dl(N);
15659   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15660     // Even for signed integers, if it's known to be positive (as signed
15661     // integer) due to zero-extended inputs.
15662     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15663     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15664     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15665          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15666         (SubOpcd1 == ISD::ZERO_EXTEND ||
15667          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15668       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15669                          N->getOperand(0)->getOperand(0),
15670                          N->getOperand(0)->getOperand(1),
15671                          DAG.getTargetConstant(0, dl, MVT::i32));
15672     }
15673 
15674     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15675     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15676         N->getOperand(0).hasOneUse()) {
15677       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15678                          N->getOperand(0)->getOperand(0),
15679                          N->getOperand(0)->getOperand(1),
15680                          DAG.getTargetConstant(1, dl, MVT::i32));
15681     }
15682   }
15683 
15684   return SDValue();
15685 }
15686 
15687 // For type v4i32/v8ii16/v16i8, transform
15688 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15689 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15690 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15691 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15692 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15693                                           DAGCombinerInfo &DCI) const {
15694   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15695   assert(Subtarget.hasP9Altivec() &&
15696          "Only combine this when P9 altivec supported!");
15697 
15698   SelectionDAG &DAG = DCI.DAG;
15699   SDLoc dl(N);
15700   SDValue Cond = N->getOperand(0);
15701   SDValue TrueOpnd = N->getOperand(1);
15702   SDValue FalseOpnd = N->getOperand(2);
15703   EVT VT = N->getOperand(1).getValueType();
15704 
15705   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15706       FalseOpnd.getOpcode() != ISD::SUB)
15707     return SDValue();
15708 
15709   // ABSD only available for type v4i32/v8i16/v16i8
15710   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15711     return SDValue();
15712 
15713   // At least to save one more dependent computation
15714   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15715     return SDValue();
15716 
15717   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15718 
15719   // Can only handle unsigned comparison here
15720   switch (CC) {
15721   default:
15722     return SDValue();
15723   case ISD::SETUGT:
15724   case ISD::SETUGE:
15725     break;
15726   case ISD::SETULT:
15727   case ISD::SETULE:
15728     std::swap(TrueOpnd, FalseOpnd);
15729     break;
15730   }
15731 
15732   SDValue CmpOpnd1 = Cond.getOperand(0);
15733   SDValue CmpOpnd2 = Cond.getOperand(1);
15734 
15735   // SETCC CmpOpnd1 CmpOpnd2 cond
15736   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15737   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15738   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15739       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15740       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15741       FalseOpnd.getOperand(1) == CmpOpnd1) {
15742     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15743                        CmpOpnd1, CmpOpnd2,
15744                        DAG.getTargetConstant(0, dl, MVT::i32));
15745   }
15746 
15747   return SDValue();
15748 }
15749