1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/RuntimeLibcalls.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/Constant.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/IRBuilder.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/Intrinsics.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCExpr.h"
72 #include "llvm/MC/MCRegisterInfo.h"
73 #include "llvm/Support/AtomicOrdering.h"
74 #include "llvm/Support/BranchProbability.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CodeGen.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/KnownBits.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetLowering.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include "llvm/Target/TargetRegisterInfo.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumSiblingCalls, "Number of sibling calls");
116 
117 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
118 
119 // FIXME: Remove this once the bug has been fixed!
120 extern cl::opt<bool> ANDIGlueBug;
121 
122 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
123                                      const PPCSubtarget &STI)
124     : TargetLowering(TM), Subtarget(STI) {
125   // Use _setjmp/_longjmp instead of setjmp/longjmp.
126   setUseUnderscoreSetJmp(true);
127   setUseUnderscoreLongJmp(true);
128 
129   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
130   // arguments are at least 4/8 bytes aligned.
131   bool isPPC64 = Subtarget.isPPC64();
132   setMinStackArgumentAlignment(isPPC64 ? 8:4);
133 
134   // Set up the register classes.
135   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
136   if (!useSoftFloat()) {
137     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
138     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
139   }
140 
141   // Match BITREVERSE to customized fast code sequence in the td file.
142   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
143   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
144 
145   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
146   for (MVT VT : MVT::integer_valuetypes()) {
147     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
148     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
149   }
150 
151   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 
153   // PowerPC has pre-inc load and store's.
154   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
155   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
156   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
157   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
158   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
159   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
160   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
161   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
162   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
163   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
164   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
165   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
166   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
167   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
168 
169   if (Subtarget.useCRBits()) {
170     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
171 
172     if (isPPC64 || Subtarget.hasFPCVT()) {
173       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
174       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
175                          isPPC64 ? MVT::i64 : MVT::i32);
176       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
177       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
178                         isPPC64 ? MVT::i64 : MVT::i32);
179     } else {
180       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
181       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
182     }
183 
184     // PowerPC does not support direct load/store of condition registers.
185     setOperationAction(ISD::LOAD, MVT::i1, Custom);
186     setOperationAction(ISD::STORE, MVT::i1, Custom);
187 
188     // FIXME: Remove this once the ANDI glue bug is fixed:
189     if (ANDIGlueBug)
190       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
191 
192     for (MVT VT : MVT::integer_valuetypes()) {
193       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
194       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
195       setTruncStoreAction(VT, MVT::i1, Expand);
196     }
197 
198     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
199   }
200 
201   // This is used in the ppcf128->int sequence.  Note it has different semantics
202   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
203   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
204 
205   // We do not currently implement these libm ops for PowerPC.
206   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
207   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
208   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
209   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
210   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
211   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
212 
213   // PowerPC has no SREM/UREM instructions unless we are on P9
214   // On P9 we may use a hardware instruction to compute the remainder.
215   // The instructions are not legalized directly because in the cases where the
216   // result of both the remainder and the division is required it is more
217   // efficient to compute the remainder from the result of the division rather
218   // than use the remainder instruction.
219   if (Subtarget.isISA3_0()) {
220     setOperationAction(ISD::SREM, MVT::i32, Custom);
221     setOperationAction(ISD::UREM, MVT::i32, Custom);
222     setOperationAction(ISD::SREM, MVT::i64, Custom);
223     setOperationAction(ISD::UREM, MVT::i64, Custom);
224   } else {
225     setOperationAction(ISD::SREM, MVT::i32, Expand);
226     setOperationAction(ISD::UREM, MVT::i32, Expand);
227     setOperationAction(ISD::SREM, MVT::i64, Expand);
228     setOperationAction(ISD::UREM, MVT::i64, Expand);
229   }
230 
231   if (Subtarget.hasP9Vector()) {
232     setOperationAction(ISD::ABS, MVT::v4i32, Legal);
233     setOperationAction(ISD::ABS, MVT::v8i16, Legal);
234     setOperationAction(ISD::ABS, MVT::v16i8, Legal);
235   }
236 
237   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
238   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
239   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
240   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
241   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
242   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
243   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
244   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
246 
247   // We don't support sin/cos/sqrt/fmod/pow
248   setOperationAction(ISD::FSIN , MVT::f64, Expand);
249   setOperationAction(ISD::FCOS , MVT::f64, Expand);
250   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
251   setOperationAction(ISD::FREM , MVT::f64, Expand);
252   setOperationAction(ISD::FPOW , MVT::f64, Expand);
253   setOperationAction(ISD::FMA  , MVT::f64, Legal);
254   setOperationAction(ISD::FSIN , MVT::f32, Expand);
255   setOperationAction(ISD::FCOS , MVT::f32, Expand);
256   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
257   setOperationAction(ISD::FREM , MVT::f32, Expand);
258   setOperationAction(ISD::FPOW , MVT::f32, Expand);
259   setOperationAction(ISD::FMA  , MVT::f32, Legal);
260 
261   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
262 
263   // If we're enabling GP optimizations, use hardware square root
264   if (!Subtarget.hasFSQRT() &&
265       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
266         Subtarget.hasFRE()))
267     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
268 
269   if (!Subtarget.hasFSQRT() &&
270       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
271         Subtarget.hasFRES()))
272     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
273 
274   if (Subtarget.hasFCPSGN()) {
275     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
276     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
277   } else {
278     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
279     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
280   }
281 
282   if (Subtarget.hasFPRND()) {
283     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
284     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
285     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
286     setOperationAction(ISD::FROUND, MVT::f64, Legal);
287 
288     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
289     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
290     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
291     setOperationAction(ISD::FROUND, MVT::f32, Legal);
292   }
293 
294   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
295   // to speed up scalar BSWAP64.
296   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
297   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
298   if (Subtarget.isISA3_0()) {
299     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
300     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
301     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
302   } else {
303     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
304     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
305     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
306   }
307 
308   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
309     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
310     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
311   } else {
312     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
313     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
314   }
315 
316   // PowerPC does not have ROTR
317   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
318   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
319 
320   if (!Subtarget.useCRBits()) {
321     // PowerPC does not have Select
322     setOperationAction(ISD::SELECT, MVT::i32, Expand);
323     setOperationAction(ISD::SELECT, MVT::i64, Expand);
324     setOperationAction(ISD::SELECT, MVT::f32, Expand);
325     setOperationAction(ISD::SELECT, MVT::f64, Expand);
326   }
327 
328   // PowerPC wants to turn select_cc of FP into fsel when possible.
329   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
330   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
331 
332   // PowerPC wants to optimize integer setcc a bit
333   if (!Subtarget.useCRBits())
334     setOperationAction(ISD::SETCC, MVT::i32, Custom);
335 
336   // PowerPC does not have BRCOND which requires SetCC
337   if (!Subtarget.useCRBits())
338     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
339 
340   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
341 
342   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
343   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
344 
345   // PowerPC does not have [U|S]INT_TO_FP
346   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
347   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
348 
349   if (Subtarget.hasDirectMove() && isPPC64) {
350     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
351     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
352     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
353     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
354   } else {
355     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
356     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
357     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
358     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
359   }
360 
361   // We cannot sextinreg(i1).  Expand to shifts.
362   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
363 
364   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
365   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
366   // support continuation, user-level threading, and etc.. As a result, no
367   // other SjLj exception interfaces are implemented and please don't build
368   // your own exception handling based on them.
369   // LLVM/Clang supports zero-cost DWARF exception handling.
370   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
371   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
372 
373   // We want to legalize GlobalAddress and ConstantPool nodes into the
374   // appropriate instructions to materialize the address.
375   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
376   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
377   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
378   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
379   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
380   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
381   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
382   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
383   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
384   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
385 
386   // TRAP is legal.
387   setOperationAction(ISD::TRAP, MVT::Other, Legal);
388 
389   // TRAMPOLINE is custom lowered.
390   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
391   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
392 
393   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
394   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
395 
396   if (Subtarget.isSVR4ABI()) {
397     if (isPPC64) {
398       // VAARG always uses double-word chunks, so promote anything smaller.
399       setOperationAction(ISD::VAARG, MVT::i1, Promote);
400       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
401       setOperationAction(ISD::VAARG, MVT::i8, Promote);
402       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
403       setOperationAction(ISD::VAARG, MVT::i16, Promote);
404       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
405       setOperationAction(ISD::VAARG, MVT::i32, Promote);
406       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
407       setOperationAction(ISD::VAARG, MVT::Other, Expand);
408     } else {
409       // VAARG is custom lowered with the 32-bit SVR4 ABI.
410       setOperationAction(ISD::VAARG, MVT::Other, Custom);
411       setOperationAction(ISD::VAARG, MVT::i64, Custom);
412     }
413   } else
414     setOperationAction(ISD::VAARG, MVT::Other, Expand);
415 
416   if (Subtarget.isSVR4ABI() && !isPPC64)
417     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
418     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
419   else
420     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
421 
422   // Use the default implementation.
423   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
424   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
425   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
426   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
427   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
428   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
429   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
430   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
431   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
432 
433   // We want to custom lower some of our intrinsics.
434   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
435 
436   // To handle counter-based loop conditions.
437   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
438 
439   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
440   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
441   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
442   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
443 
444   // Comparisons that require checking two conditions.
445   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
446   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
447   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
448   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
449   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
450   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
451   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
452   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
453   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
454   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
455   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
456   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
457 
458   if (Subtarget.has64BitSupport()) {
459     // They also have instructions for converting between i64 and fp.
460     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
461     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
462     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
463     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
464     // This is just the low 32 bits of a (signed) fp->i64 conversion.
465     // We cannot do this with Promote because i64 is not a legal type.
466     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
467 
468     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
469       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
470   } else {
471     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
472     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
473   }
474 
475   // With the instructions enabled under FPCVT, we can do everything.
476   if (Subtarget.hasFPCVT()) {
477     if (Subtarget.has64BitSupport()) {
478       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
479       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
480       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
481       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
482     }
483 
484     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
485     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
486     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
487     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
488   }
489 
490   if (Subtarget.use64BitRegs()) {
491     // 64-bit PowerPC implementations can support i64 types directly
492     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
493     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
494     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
495     // 64-bit PowerPC wants to expand i128 shifts itself.
496     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
497     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
498     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
499   } else {
500     // 32-bit PowerPC wants to expand i64 shifts itself.
501     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
502     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
503     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
504   }
505 
506   if (Subtarget.hasAltivec()) {
507     // First set operation action for all vector types to expand. Then we
508     // will selectively turn on ones that can be effectively codegen'd.
509     for (MVT VT : MVT::vector_valuetypes()) {
510       // add/sub are legal for all supported vector VT's.
511       setOperationAction(ISD::ADD, VT, Legal);
512       setOperationAction(ISD::SUB, VT, Legal);
513 
514       // Vector instructions introduced in P8
515       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
516         setOperationAction(ISD::CTPOP, VT, Legal);
517         setOperationAction(ISD::CTLZ, VT, Legal);
518       }
519       else {
520         setOperationAction(ISD::CTPOP, VT, Expand);
521         setOperationAction(ISD::CTLZ, VT, Expand);
522       }
523 
524       // Vector instructions introduced in P9
525       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
526         setOperationAction(ISD::CTTZ, VT, Legal);
527       else
528         setOperationAction(ISD::CTTZ, VT, Expand);
529 
530       // We promote all shuffles to v16i8.
531       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
532       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
533 
534       // We promote all non-typed operations to v4i32.
535       setOperationAction(ISD::AND   , VT, Promote);
536       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
537       setOperationAction(ISD::OR    , VT, Promote);
538       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
539       setOperationAction(ISD::XOR   , VT, Promote);
540       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
541       setOperationAction(ISD::LOAD  , VT, Promote);
542       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
543       setOperationAction(ISD::SELECT, VT, Promote);
544       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
545       setOperationAction(ISD::SELECT_CC, VT, Promote);
546       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
547       setOperationAction(ISD::STORE, VT, Promote);
548       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
549 
550       // No other operations are legal.
551       setOperationAction(ISD::MUL , VT, Expand);
552       setOperationAction(ISD::SDIV, VT, Expand);
553       setOperationAction(ISD::SREM, VT, Expand);
554       setOperationAction(ISD::UDIV, VT, Expand);
555       setOperationAction(ISD::UREM, VT, Expand);
556       setOperationAction(ISD::FDIV, VT, Expand);
557       setOperationAction(ISD::FREM, VT, Expand);
558       setOperationAction(ISD::FNEG, VT, Expand);
559       setOperationAction(ISD::FSQRT, VT, Expand);
560       setOperationAction(ISD::FLOG, VT, Expand);
561       setOperationAction(ISD::FLOG10, VT, Expand);
562       setOperationAction(ISD::FLOG2, VT, Expand);
563       setOperationAction(ISD::FEXP, VT, Expand);
564       setOperationAction(ISD::FEXP2, VT, Expand);
565       setOperationAction(ISD::FSIN, VT, Expand);
566       setOperationAction(ISD::FCOS, VT, Expand);
567       setOperationAction(ISD::FABS, VT, Expand);
568       setOperationAction(ISD::FFLOOR, VT, Expand);
569       setOperationAction(ISD::FCEIL,  VT, Expand);
570       setOperationAction(ISD::FTRUNC, VT, Expand);
571       setOperationAction(ISD::FRINT,  VT, Expand);
572       setOperationAction(ISD::FNEARBYINT, VT, Expand);
573       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
574       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
575       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
576       setOperationAction(ISD::MULHU, VT, Expand);
577       setOperationAction(ISD::MULHS, VT, Expand);
578       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
579       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
580       setOperationAction(ISD::UDIVREM, VT, Expand);
581       setOperationAction(ISD::SDIVREM, VT, Expand);
582       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
583       setOperationAction(ISD::FPOW, VT, Expand);
584       setOperationAction(ISD::BSWAP, VT, Expand);
585       setOperationAction(ISD::VSELECT, VT, Expand);
586       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
587       setOperationAction(ISD::ROTL, VT, Expand);
588       setOperationAction(ISD::ROTR, VT, Expand);
589 
590       for (MVT InnerVT : MVT::vector_valuetypes()) {
591         setTruncStoreAction(VT, InnerVT, Expand);
592         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
593         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
594         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
595       }
596     }
597 
598     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
599     // with merges, splats, etc.
600     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
601 
602     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
603     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
604     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
605     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
606     setOperationAction(ISD::SELECT, MVT::v4i32,
607                        Subtarget.useCRBits() ? Legal : Expand);
608     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
609     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
610     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
611     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
612     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
613     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
614     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
615     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
616     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
617 
618     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
619     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
620     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
621     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
622 
623     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
624     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
625 
626     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
627       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
628       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
629     }
630 
631     if (Subtarget.hasP8Altivec())
632       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
633     else
634       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
635 
636     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
637     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
638 
639     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
640     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
641 
642     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
643     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
644     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
645     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
646 
647     // Altivec does not contain unordered floating-point compare instructions
648     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
649     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
650     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
651     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
652 
653     if (Subtarget.hasVSX()) {
654       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
655       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
656       if (Subtarget.hasP8Vector()) {
657         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
658         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
659       }
660       if (Subtarget.hasDirectMove() && isPPC64) {
661         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
662         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
663         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
664         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
665         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
666         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
667         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
668         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
669       }
670       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
671 
672       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
673       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
674       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
675       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
676       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
677 
678       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
679 
680       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
681       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
682 
683       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
684       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
685 
686       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
687       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
688       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
689       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
690       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
691 
692       // Share the Altivec comparison restrictions.
693       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
694       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
695       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
696       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
697 
698       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
699       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
700 
701       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
702 
703       if (Subtarget.hasP8Vector())
704         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
705 
706       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
707 
708       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
709       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
710       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
711 
712       if (Subtarget.hasP8Altivec()) {
713         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
714         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
715         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
716 
717         // 128 bit shifts can be accomplished via 3 instructions for SHL and
718         // SRL, but not for SRA because of the instructions available:
719         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
720         // doing
721         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
722         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
723         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
724 
725         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
726       }
727       else {
728         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
729         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
730         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
731 
732         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
733 
734         // VSX v2i64 only supports non-arithmetic operations.
735         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
736         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
737       }
738 
739       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
740       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
741       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
742       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
743 
744       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
745 
746       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
747       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
748       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
749       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
750 
751       // Vector operation legalization checks the result type of
752       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
753       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
754       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
755       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
756       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
757 
758       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
759       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
760       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
761       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
762 
763       if (Subtarget.hasDirectMove())
764         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
765       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
766 
767       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
768     }
769 
770     if (Subtarget.hasP8Altivec()) {
771       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
772       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
773     }
774 
775     if (Subtarget.hasP9Vector()) {
776       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
777       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
778 
779       // 128 bit shifts can be accomplished via 3 instructions for SHL and
780       // SRL, but not for SRA because of the instructions available:
781       // VS{RL} and VS{RL}O.
782       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
783       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
784       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
785     }
786   }
787 
788   if (Subtarget.hasQPX()) {
789     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
790     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
791     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
792     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
793 
794     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
795     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
796 
797     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
798     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
799 
800     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
801     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
802 
803     if (!Subtarget.useCRBits())
804       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
805     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
806 
807     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
808     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
809     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
811     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
812     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
813     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
814 
815     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
816     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
817 
818     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
819     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
820     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
821 
822     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
823     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
824     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
825     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
826     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
827     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
828     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
829     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
830     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
831     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
832 
833     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
834     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
835 
836     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
837     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
838 
839     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
840 
841     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
842     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
843     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
844     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
845 
846     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
847     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
848 
849     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
850     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
851 
852     if (!Subtarget.useCRBits())
853       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
854     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
855 
856     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
857     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
858     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
859     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
860     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
861     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
862     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
863 
864     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
865     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
866 
867     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
868     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
869     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
870     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
871     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
872     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
873     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
874     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
875     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
876     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
877 
878     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
879     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
880 
881     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
882     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
883 
884     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
885 
886     setOperationAction(ISD::AND , MVT::v4i1, Legal);
887     setOperationAction(ISD::OR , MVT::v4i1, Legal);
888     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
889 
890     if (!Subtarget.useCRBits())
891       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
892     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
893 
894     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
895     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
896 
897     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
898     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
899     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
900     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
901     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
902     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
903     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
904 
905     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
906     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
907 
908     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
909 
910     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
911     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
912     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
913     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
914 
915     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
916     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
917     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
918     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
919 
920     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
921     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
922 
923     // These need to set FE_INEXACT, and so cannot be vectorized here.
924     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
925     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
926 
927     if (TM.Options.UnsafeFPMath) {
928       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
929       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
930 
931       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
932       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
933     } else {
934       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
935       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
936 
937       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
938       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
939     }
940   }
941 
942   if (Subtarget.has64BitSupport())
943     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
944 
945   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
946 
947   if (!isPPC64) {
948     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
949     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
950   }
951 
952   setBooleanContents(ZeroOrOneBooleanContent);
953 
954   if (Subtarget.hasAltivec()) {
955     // Altivec instructions set fields to all zeros or all ones.
956     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
957   }
958 
959   if (!isPPC64) {
960     // These libcalls are not available in 32-bit.
961     setLibcallName(RTLIB::SHL_I128, nullptr);
962     setLibcallName(RTLIB::SRL_I128, nullptr);
963     setLibcallName(RTLIB::SRA_I128, nullptr);
964   }
965 
966   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
967 
968   // We have target-specific dag combine patterns for the following nodes:
969   setTargetDAGCombine(ISD::SHL);
970   setTargetDAGCombine(ISD::SRA);
971   setTargetDAGCombine(ISD::SRL);
972   setTargetDAGCombine(ISD::SINT_TO_FP);
973   setTargetDAGCombine(ISD::BUILD_VECTOR);
974   if (Subtarget.hasFPCVT())
975     setTargetDAGCombine(ISD::UINT_TO_FP);
976   setTargetDAGCombine(ISD::LOAD);
977   setTargetDAGCombine(ISD::STORE);
978   setTargetDAGCombine(ISD::BR_CC);
979   if (Subtarget.useCRBits())
980     setTargetDAGCombine(ISD::BRCOND);
981   setTargetDAGCombine(ISD::BSWAP);
982   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
983   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
984   setTargetDAGCombine(ISD::INTRINSIC_VOID);
985 
986   setTargetDAGCombine(ISD::SIGN_EXTEND);
987   setTargetDAGCombine(ISD::ZERO_EXTEND);
988   setTargetDAGCombine(ISD::ANY_EXTEND);
989 
990   if (Subtarget.useCRBits()) {
991     setTargetDAGCombine(ISD::TRUNCATE);
992     setTargetDAGCombine(ISD::SETCC);
993     setTargetDAGCombine(ISD::SELECT_CC);
994   }
995 
996   // Use reciprocal estimates.
997   if (TM.Options.UnsafeFPMath) {
998     setTargetDAGCombine(ISD::FDIV);
999     setTargetDAGCombine(ISD::FSQRT);
1000   }
1001 
1002   // Darwin long double math library functions have $LDBL128 appended.
1003   if (Subtarget.isDarwin()) {
1004     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1005     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1006     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1007     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1008     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1009     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1010     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1011     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1012     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1013     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1014   }
1015 
1016   // With 32 condition bits, we don't need to sink (and duplicate) compares
1017   // aggressively in CodeGenPrep.
1018   if (Subtarget.useCRBits()) {
1019     setHasMultipleConditionRegisters();
1020     setJumpIsExpensive();
1021   }
1022 
1023   setMinFunctionAlignment(2);
1024   if (Subtarget.isDarwin())
1025     setPrefFunctionAlignment(4);
1026 
1027   switch (Subtarget.getDarwinDirective()) {
1028   default: break;
1029   case PPC::DIR_970:
1030   case PPC::DIR_A2:
1031   case PPC::DIR_E500mc:
1032   case PPC::DIR_E5500:
1033   case PPC::DIR_PWR4:
1034   case PPC::DIR_PWR5:
1035   case PPC::DIR_PWR5X:
1036   case PPC::DIR_PWR6:
1037   case PPC::DIR_PWR6X:
1038   case PPC::DIR_PWR7:
1039   case PPC::DIR_PWR8:
1040   case PPC::DIR_PWR9:
1041     setPrefFunctionAlignment(4);
1042     setPrefLoopAlignment(4);
1043     break;
1044   }
1045 
1046   if (Subtarget.enableMachineScheduler())
1047     setSchedulingPreference(Sched::Source);
1048   else
1049     setSchedulingPreference(Sched::Hybrid);
1050 
1051   computeRegisterProperties(STI.getRegisterInfo());
1052 
1053   // The Freescale cores do better with aggressive inlining of memcpy and
1054   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1055   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1056       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1057     MaxStoresPerMemset = 32;
1058     MaxStoresPerMemsetOptSize = 16;
1059     MaxStoresPerMemcpy = 32;
1060     MaxStoresPerMemcpyOptSize = 8;
1061     MaxStoresPerMemmove = 32;
1062     MaxStoresPerMemmoveOptSize = 8;
1063   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1064     // The A2 also benefits from (very) aggressive inlining of memcpy and
1065     // friends. The overhead of a the function call, even when warm, can be
1066     // over one hundred cycles.
1067     MaxStoresPerMemset = 128;
1068     MaxStoresPerMemcpy = 128;
1069     MaxStoresPerMemmove = 128;
1070     MaxLoadsPerMemcmp = 128;
1071   } else {
1072     MaxLoadsPerMemcmp = 8;
1073     MaxLoadsPerMemcmpOptSize = 4;
1074   }
1075 }
1076 
1077 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1078 /// the desired ByVal argument alignment.
1079 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1080                              unsigned MaxMaxAlign) {
1081   if (MaxAlign == MaxMaxAlign)
1082     return;
1083   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1084     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1085       MaxAlign = 32;
1086     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1087       MaxAlign = 16;
1088   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1089     unsigned EltAlign = 0;
1090     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1091     if (EltAlign > MaxAlign)
1092       MaxAlign = EltAlign;
1093   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1094     for (auto *EltTy : STy->elements()) {
1095       unsigned EltAlign = 0;
1096       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1097       if (EltAlign > MaxAlign)
1098         MaxAlign = EltAlign;
1099       if (MaxAlign == MaxMaxAlign)
1100         break;
1101     }
1102   }
1103 }
1104 
1105 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1106 /// function arguments in the caller parameter area.
1107 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1108                                                   const DataLayout &DL) const {
1109   // Darwin passes everything on 4 byte boundary.
1110   if (Subtarget.isDarwin())
1111     return 4;
1112 
1113   // 16byte and wider vectors are passed on 16byte boundary.
1114   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1115   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1116   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1117     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1118   return Align;
1119 }
1120 
1121 bool PPCTargetLowering::useSoftFloat() const {
1122   return Subtarget.useSoftFloat();
1123 }
1124 
1125 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1126   switch ((PPCISD::NodeType)Opcode) {
1127   case PPCISD::FIRST_NUMBER:    break;
1128   case PPCISD::FSEL:            return "PPCISD::FSEL";
1129   case PPCISD::FCFID:           return "PPCISD::FCFID";
1130   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1131   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1132   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1133   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1134   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1135   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1136   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1137   case PPCISD::FRE:             return "PPCISD::FRE";
1138   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1139   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1140   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1141   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1142   case PPCISD::VPERM:           return "PPCISD::VPERM";
1143   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1144   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1145   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1146   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1147   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1148   case PPCISD::CMPB:            return "PPCISD::CMPB";
1149   case PPCISD::Hi:              return "PPCISD::Hi";
1150   case PPCISD::Lo:              return "PPCISD::Lo";
1151   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1152   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1153   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1154   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1155   case PPCISD::SRL:             return "PPCISD::SRL";
1156   case PPCISD::SRA:             return "PPCISD::SRA";
1157   case PPCISD::SHL:             return "PPCISD::SHL";
1158   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1159   case PPCISD::CALL:            return "PPCISD::CALL";
1160   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1161   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1162   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1163   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1164   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1165   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1166   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1167   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1168   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1169   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1170   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1171   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1172   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1173   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1174   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1175   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1176   case PPCISD::VCMP:            return "PPCISD::VCMP";
1177   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1178   case PPCISD::LBRX:            return "PPCISD::LBRX";
1179   case PPCISD::STBRX:           return "PPCISD::STBRX";
1180   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1181   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1182   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1183   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1184   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1185   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1186   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1187   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1188   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1189   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1190   case PPCISD::BDZ:             return "PPCISD::BDZ";
1191   case PPCISD::MFFS:            return "PPCISD::MFFS";
1192   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1193   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1194   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1195   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1196   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1197   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1198   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1199   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1200   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1201   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1202   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1203   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1204   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1205   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1206   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1207   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1208   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1209   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1210   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1211   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1212   case PPCISD::SC:              return "PPCISD::SC";
1213   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1214   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1215   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1216   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1217   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1218   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1219   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1220   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1221   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1222   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1223   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1224   }
1225   return nullptr;
1226 }
1227 
1228 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1229                                           EVT VT) const {
1230   if (!VT.isVector())
1231     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1232 
1233   if (Subtarget.hasQPX())
1234     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1235 
1236   return VT.changeVectorElementTypeToInteger();
1237 }
1238 
1239 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1240   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1241   return true;
1242 }
1243 
1244 //===----------------------------------------------------------------------===//
1245 // Node matching predicates, for use by the tblgen matching code.
1246 //===----------------------------------------------------------------------===//
1247 
1248 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1249 static bool isFloatingPointZero(SDValue Op) {
1250   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1251     return CFP->getValueAPF().isZero();
1252   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1253     // Maybe this has already been legalized into the constant pool?
1254     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1255       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1256         return CFP->getValueAPF().isZero();
1257   }
1258   return false;
1259 }
1260 
1261 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1262 /// true if Op is undef or if it matches the specified value.
1263 static bool isConstantOrUndef(int Op, int Val) {
1264   return Op < 0 || Op == Val;
1265 }
1266 
1267 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1268 /// VPKUHUM instruction.
1269 /// The ShuffleKind distinguishes between big-endian operations with
1270 /// two different inputs (0), either-endian operations with two identical
1271 /// inputs (1), and little-endian operations with two different inputs (2).
1272 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1273 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1274                                SelectionDAG &DAG) {
1275   bool IsLE = DAG.getDataLayout().isLittleEndian();
1276   if (ShuffleKind == 0) {
1277     if (IsLE)
1278       return false;
1279     for (unsigned i = 0; i != 16; ++i)
1280       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1281         return false;
1282   } else if (ShuffleKind == 2) {
1283     if (!IsLE)
1284       return false;
1285     for (unsigned i = 0; i != 16; ++i)
1286       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1287         return false;
1288   } else if (ShuffleKind == 1) {
1289     unsigned j = IsLE ? 0 : 1;
1290     for (unsigned i = 0; i != 8; ++i)
1291       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1292           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1293         return false;
1294   }
1295   return true;
1296 }
1297 
1298 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1299 /// VPKUWUM instruction.
1300 /// The ShuffleKind distinguishes between big-endian operations with
1301 /// two different inputs (0), either-endian operations with two identical
1302 /// inputs (1), and little-endian operations with two different inputs (2).
1303 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1304 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1305                                SelectionDAG &DAG) {
1306   bool IsLE = DAG.getDataLayout().isLittleEndian();
1307   if (ShuffleKind == 0) {
1308     if (IsLE)
1309       return false;
1310     for (unsigned i = 0; i != 16; i += 2)
1311       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1312           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1313         return false;
1314   } else if (ShuffleKind == 2) {
1315     if (!IsLE)
1316       return false;
1317     for (unsigned i = 0; i != 16; i += 2)
1318       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1319           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1320         return false;
1321   } else if (ShuffleKind == 1) {
1322     unsigned j = IsLE ? 0 : 2;
1323     for (unsigned i = 0; i != 8; i += 2)
1324       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1325           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1326           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1327           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1328         return false;
1329   }
1330   return true;
1331 }
1332 
1333 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1334 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1335 /// current subtarget.
1336 ///
1337 /// The ShuffleKind distinguishes between big-endian operations with
1338 /// two different inputs (0), either-endian operations with two identical
1339 /// inputs (1), and little-endian operations with two different inputs (2).
1340 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1341 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1342                                SelectionDAG &DAG) {
1343   const PPCSubtarget& Subtarget =
1344     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1345   if (!Subtarget.hasP8Vector())
1346     return false;
1347 
1348   bool IsLE = DAG.getDataLayout().isLittleEndian();
1349   if (ShuffleKind == 0) {
1350     if (IsLE)
1351       return false;
1352     for (unsigned i = 0; i != 16; i += 4)
1353       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1354           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1355           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1356           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1357         return false;
1358   } else if (ShuffleKind == 2) {
1359     if (!IsLE)
1360       return false;
1361     for (unsigned i = 0; i != 16; i += 4)
1362       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1363           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1364           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1365           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1366         return false;
1367   } else if (ShuffleKind == 1) {
1368     unsigned j = IsLE ? 0 : 4;
1369     for (unsigned i = 0; i != 8; i += 4)
1370       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1371           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1372           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1373           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1374           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1375           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1376           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1377           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1378         return false;
1379   }
1380   return true;
1381 }
1382 
1383 /// isVMerge - Common function, used to match vmrg* shuffles.
1384 ///
1385 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1386                      unsigned LHSStart, unsigned RHSStart) {
1387   if (N->getValueType(0) != MVT::v16i8)
1388     return false;
1389   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1390          "Unsupported merge size!");
1391 
1392   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1393     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1394       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1395                              LHSStart+j+i*UnitSize) ||
1396           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1397                              RHSStart+j+i*UnitSize))
1398         return false;
1399     }
1400   return true;
1401 }
1402 
1403 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1404 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1405 /// The ShuffleKind distinguishes between big-endian merges with two
1406 /// different inputs (0), either-endian merges with two identical inputs (1),
1407 /// and little-endian merges with two different inputs (2).  For the latter,
1408 /// the input operands are swapped (see PPCInstrAltivec.td).
1409 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1410                              unsigned ShuffleKind, SelectionDAG &DAG) {
1411   if (DAG.getDataLayout().isLittleEndian()) {
1412     if (ShuffleKind == 1) // unary
1413       return isVMerge(N, UnitSize, 0, 0);
1414     else if (ShuffleKind == 2) // swapped
1415       return isVMerge(N, UnitSize, 0, 16);
1416     else
1417       return false;
1418   } else {
1419     if (ShuffleKind == 1) // unary
1420       return isVMerge(N, UnitSize, 8, 8);
1421     else if (ShuffleKind == 0) // normal
1422       return isVMerge(N, UnitSize, 8, 24);
1423     else
1424       return false;
1425   }
1426 }
1427 
1428 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1429 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1430 /// The ShuffleKind distinguishes between big-endian merges with two
1431 /// different inputs (0), either-endian merges with two identical inputs (1),
1432 /// and little-endian merges with two different inputs (2).  For the latter,
1433 /// the input operands are swapped (see PPCInstrAltivec.td).
1434 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1435                              unsigned ShuffleKind, SelectionDAG &DAG) {
1436   if (DAG.getDataLayout().isLittleEndian()) {
1437     if (ShuffleKind == 1) // unary
1438       return isVMerge(N, UnitSize, 8, 8);
1439     else if (ShuffleKind == 2) // swapped
1440       return isVMerge(N, UnitSize, 8, 24);
1441     else
1442       return false;
1443   } else {
1444     if (ShuffleKind == 1) // unary
1445       return isVMerge(N, UnitSize, 0, 0);
1446     else if (ShuffleKind == 0) // normal
1447       return isVMerge(N, UnitSize, 0, 16);
1448     else
1449       return false;
1450   }
1451 }
1452 
1453 /**
1454  * \brief Common function used to match vmrgew and vmrgow shuffles
1455  *
1456  * The indexOffset determines whether to look for even or odd words in
1457  * the shuffle mask. This is based on the of the endianness of the target
1458  * machine.
1459  *   - Little Endian:
1460  *     - Use offset of 0 to check for odd elements
1461  *     - Use offset of 4 to check for even elements
1462  *   - Big Endian:
1463  *     - Use offset of 0 to check for even elements
1464  *     - Use offset of 4 to check for odd elements
1465  * A detailed description of the vector element ordering for little endian and
1466  * big endian can be found at
1467  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1468  * Targeting your applications - what little endian and big endian IBM XL C/C++
1469  * compiler differences mean to you
1470  *
1471  * The mask to the shuffle vector instruction specifies the indices of the
1472  * elements from the two input vectors to place in the result. The elements are
1473  * numbered in array-access order, starting with the first vector. These vectors
1474  * are always of type v16i8, thus each vector will contain 16 elements of size
1475  * 8. More info on the shuffle vector can be found in the
1476  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1477  * Language Reference.
1478  *
1479  * The RHSStartValue indicates whether the same input vectors are used (unary)
1480  * or two different input vectors are used, based on the following:
1481  *   - If the instruction uses the same vector for both inputs, the range of the
1482  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1483  *     be 0.
1484  *   - If the instruction has two different vectors then the range of the
1485  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1486  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1487  *     to 31 specify elements in the second vector).
1488  *
1489  * \param[in] N The shuffle vector SD Node to analyze
1490  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1491  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1492  * vector to the shuffle_vector instruction
1493  * \return true iff this shuffle vector represents an even or odd word merge
1494  */
1495 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1496                      unsigned RHSStartValue) {
1497   if (N->getValueType(0) != MVT::v16i8)
1498     return false;
1499 
1500   for (unsigned i = 0; i < 2; ++i)
1501     for (unsigned j = 0; j < 4; ++j)
1502       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1503                              i*RHSStartValue+j+IndexOffset) ||
1504           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1505                              i*RHSStartValue+j+IndexOffset+8))
1506         return false;
1507   return true;
1508 }
1509 
1510 /**
1511  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1512  * vmrgow instructions.
1513  *
1514  * \param[in] N The shuffle vector SD Node to analyze
1515  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1516  * \param[in] ShuffleKind Identify the type of merge:
1517  *   - 0 = big-endian merge with two different inputs;
1518  *   - 1 = either-endian merge with two identical inputs;
1519  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1520  *     little-endian merges).
1521  * \param[in] DAG The current SelectionDAG
1522  * \return true iff this shuffle mask
1523  */
1524 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1525                               unsigned ShuffleKind, SelectionDAG &DAG) {
1526   if (DAG.getDataLayout().isLittleEndian()) {
1527     unsigned indexOffset = CheckEven ? 4 : 0;
1528     if (ShuffleKind == 1) // Unary
1529       return isVMerge(N, indexOffset, 0);
1530     else if (ShuffleKind == 2) // swapped
1531       return isVMerge(N, indexOffset, 16);
1532     else
1533       return false;
1534   }
1535   else {
1536     unsigned indexOffset = CheckEven ? 0 : 4;
1537     if (ShuffleKind == 1) // Unary
1538       return isVMerge(N, indexOffset, 0);
1539     else if (ShuffleKind == 0) // Normal
1540       return isVMerge(N, indexOffset, 16);
1541     else
1542       return false;
1543   }
1544   return false;
1545 }
1546 
1547 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1548 /// amount, otherwise return -1.
1549 /// The ShuffleKind distinguishes between big-endian operations with two
1550 /// different inputs (0), either-endian operations with two identical inputs
1551 /// (1), and little-endian operations with two different inputs (2).  For the
1552 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1553 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1554                              SelectionDAG &DAG) {
1555   if (N->getValueType(0) != MVT::v16i8)
1556     return -1;
1557 
1558   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1559 
1560   // Find the first non-undef value in the shuffle mask.
1561   unsigned i;
1562   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1563     /*search*/;
1564 
1565   if (i == 16) return -1;  // all undef.
1566 
1567   // Otherwise, check to see if the rest of the elements are consecutively
1568   // numbered from this value.
1569   unsigned ShiftAmt = SVOp->getMaskElt(i);
1570   if (ShiftAmt < i) return -1;
1571 
1572   ShiftAmt -= i;
1573   bool isLE = DAG.getDataLayout().isLittleEndian();
1574 
1575   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1576     // Check the rest of the elements to see if they are consecutive.
1577     for (++i; i != 16; ++i)
1578       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1579         return -1;
1580   } else if (ShuffleKind == 1) {
1581     // Check the rest of the elements to see if they are consecutive.
1582     for (++i; i != 16; ++i)
1583       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1584         return -1;
1585   } else
1586     return -1;
1587 
1588   if (isLE)
1589     ShiftAmt = 16 - ShiftAmt;
1590 
1591   return ShiftAmt;
1592 }
1593 
1594 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1595 /// specifies a splat of a single element that is suitable for input to
1596 /// VSPLTB/VSPLTH/VSPLTW.
1597 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1598   assert(N->getValueType(0) == MVT::v16i8 &&
1599          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1600 
1601   // The consecutive indices need to specify an element, not part of two
1602   // different elements.  So abandon ship early if this isn't the case.
1603   if (N->getMaskElt(0) % EltSize != 0)
1604     return false;
1605 
1606   // This is a splat operation if each element of the permute is the same, and
1607   // if the value doesn't reference the second vector.
1608   unsigned ElementBase = N->getMaskElt(0);
1609 
1610   // FIXME: Handle UNDEF elements too!
1611   if (ElementBase >= 16)
1612     return false;
1613 
1614   // Check that the indices are consecutive, in the case of a multi-byte element
1615   // splatted with a v16i8 mask.
1616   for (unsigned i = 1; i != EltSize; ++i)
1617     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1618       return false;
1619 
1620   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1621     if (N->getMaskElt(i) < 0) continue;
1622     for (unsigned j = 0; j != EltSize; ++j)
1623       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1624         return false;
1625   }
1626   return true;
1627 }
1628 
1629 /// Check that the mask is shuffling N byte elements. Within each N byte
1630 /// element of the mask, the indices could be either in increasing or
1631 /// decreasing order as long as they are consecutive.
1632 /// \param[in] N the shuffle vector SD Node to analyze
1633 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1634 /// Word/DoubleWord/QuadWord).
1635 /// \param[in] StepLen the delta indices number among the N byte element, if
1636 /// the mask is in increasing/decreasing order then it is 1/-1.
1637 /// \return true iff the mask is shuffling N byte elements.
1638 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1639                                    int StepLen) {
1640   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1641          "Unexpected element width.");
1642   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1643 
1644   unsigned NumOfElem = 16 / Width;
1645   unsigned MaskVal[16]; //  Width is never greater than 16
1646   for (unsigned i = 0; i < NumOfElem; ++i) {
1647     MaskVal[0] = N->getMaskElt(i * Width);
1648     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1649       return false;
1650     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1651       return false;
1652     }
1653 
1654     for (unsigned int j = 1; j < Width; ++j) {
1655       MaskVal[j] = N->getMaskElt(i * Width + j);
1656       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1657         return false;
1658       }
1659     }
1660   }
1661 
1662   return true;
1663 }
1664 
1665 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1666                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1667   if (!isNByteElemShuffleMask(N, 4, 1))
1668     return false;
1669 
1670   // Now we look at mask elements 0,4,8,12
1671   unsigned M0 = N->getMaskElt(0) / 4;
1672   unsigned M1 = N->getMaskElt(4) / 4;
1673   unsigned M2 = N->getMaskElt(8) / 4;
1674   unsigned M3 = N->getMaskElt(12) / 4;
1675   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1676   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1677 
1678   // Below, let H and L be arbitrary elements of the shuffle mask
1679   // where H is in the range [4,7] and L is in the range [0,3].
1680   // H, 1, 2, 3 or L, 5, 6, 7
1681   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1682       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1683     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1684     InsertAtByte = IsLE ? 12 : 0;
1685     Swap = M0 < 4;
1686     return true;
1687   }
1688   // 0, H, 2, 3 or 4, L, 6, 7
1689   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1690       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1691     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1692     InsertAtByte = IsLE ? 8 : 4;
1693     Swap = M1 < 4;
1694     return true;
1695   }
1696   // 0, 1, H, 3 or 4, 5, L, 7
1697   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1698       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1699     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1700     InsertAtByte = IsLE ? 4 : 8;
1701     Swap = M2 < 4;
1702     return true;
1703   }
1704   // 0, 1, 2, H or 4, 5, 6, L
1705   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1706       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1707     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1708     InsertAtByte = IsLE ? 0 : 12;
1709     Swap = M3 < 4;
1710     return true;
1711   }
1712 
1713   // If both vector operands for the shuffle are the same vector, the mask will
1714   // contain only elements from the first one and the second one will be undef.
1715   if (N->getOperand(1).isUndef()) {
1716     ShiftElts = 0;
1717     Swap = true;
1718     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1719     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1720       InsertAtByte = IsLE ? 12 : 0;
1721       return true;
1722     }
1723     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1724       InsertAtByte = IsLE ? 8 : 4;
1725       return true;
1726     }
1727     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1728       InsertAtByte = IsLE ? 4 : 8;
1729       return true;
1730     }
1731     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1732       InsertAtByte = IsLE ? 0 : 12;
1733       return true;
1734     }
1735   }
1736 
1737   return false;
1738 }
1739 
1740 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1741                                bool &Swap, bool IsLE) {
1742   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1743   // Ensure each byte index of the word is consecutive.
1744   if (!isNByteElemShuffleMask(N, 4, 1))
1745     return false;
1746 
1747   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1748   unsigned M0 = N->getMaskElt(0) / 4;
1749   unsigned M1 = N->getMaskElt(4) / 4;
1750   unsigned M2 = N->getMaskElt(8) / 4;
1751   unsigned M3 = N->getMaskElt(12) / 4;
1752 
1753   // If both vector operands for the shuffle are the same vector, the mask will
1754   // contain only elements from the first one and the second one will be undef.
1755   if (N->getOperand(1).isUndef()) {
1756     assert(M0 < 4 && "Indexing into an undef vector?");
1757     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1758       return false;
1759 
1760     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1761     Swap = false;
1762     return true;
1763   }
1764 
1765   // Ensure each word index of the ShuffleVector Mask is consecutive.
1766   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1767     return false;
1768 
1769   if (IsLE) {
1770     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1771       // Input vectors don't need to be swapped if the leading element
1772       // of the result is one of the 3 left elements of the second vector
1773       // (or if there is no shift to be done at all).
1774       Swap = false;
1775       ShiftElts = (8 - M0) % 8;
1776     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1777       // Input vectors need to be swapped if the leading element
1778       // of the result is one of the 3 left elements of the first vector
1779       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1780       Swap = true;
1781       ShiftElts = (4 - M0) % 4;
1782     }
1783 
1784     return true;
1785   } else {                                          // BE
1786     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1787       // Input vectors don't need to be swapped if the leading element
1788       // of the result is one of the 4 elements of the first vector.
1789       Swap = false;
1790       ShiftElts = M0;
1791     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1792       // Input vectors need to be swapped if the leading element
1793       // of the result is one of the 4 elements of the right vector.
1794       Swap = true;
1795       ShiftElts = M0 - 4;
1796     }
1797 
1798     return true;
1799   }
1800 }
1801 
1802 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1803   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1804 
1805   if (!isNByteElemShuffleMask(N, Width, -1))
1806     return false;
1807 
1808   for (int i = 0; i < 16; i += Width)
1809     if (N->getMaskElt(i) != i + Width - 1)
1810       return false;
1811 
1812   return true;
1813 }
1814 
1815 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1816   return isXXBRShuffleMaskHelper(N, 2);
1817 }
1818 
1819 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1820   return isXXBRShuffleMaskHelper(N, 4);
1821 }
1822 
1823 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1824   return isXXBRShuffleMaskHelper(N, 8);
1825 }
1826 
1827 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1828   return isXXBRShuffleMaskHelper(N, 16);
1829 }
1830 
1831 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1832 /// if the inputs to the instruction should be swapped and set \p DM to the
1833 /// value for the immediate.
1834 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1835 /// AND element 0 of the result comes from the first input (LE) or second input
1836 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1837 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1838 /// mask.
1839 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1840                                bool &Swap, bool IsLE) {
1841   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1842 
1843   // Ensure each byte index of the double word is consecutive.
1844   if (!isNByteElemShuffleMask(N, 8, 1))
1845     return false;
1846 
1847   unsigned M0 = N->getMaskElt(0) / 8;
1848   unsigned M1 = N->getMaskElt(8) / 8;
1849   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1850 
1851   // If both vector operands for the shuffle are the same vector, the mask will
1852   // contain only elements from the first one and the second one will be undef.
1853   if (N->getOperand(1).isUndef()) {
1854     if ((M0 | M1) < 2) {
1855       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1856       Swap = false;
1857       return true;
1858     } else
1859       return false;
1860   }
1861 
1862   if (IsLE) {
1863     if (M0 > 1 && M1 < 2) {
1864       Swap = false;
1865     } else if (M0 < 2 && M1 > 1) {
1866       M0 = (M0 + 2) % 4;
1867       M1 = (M1 + 2) % 4;
1868       Swap = true;
1869     } else
1870       return false;
1871 
1872     // Note: if control flow comes here that means Swap is already set above
1873     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
1874     return true;
1875   } else { // BE
1876     if (M0 < 2 && M1 > 1) {
1877       Swap = false;
1878     } else if (M0 > 1 && M1 < 2) {
1879       M0 = (M0 + 2) % 4;
1880       M1 = (M1 + 2) % 4;
1881       Swap = true;
1882     } else
1883       return false;
1884 
1885     // Note: if control flow comes here that means Swap is already set above
1886     DM = (M0 << 1) + (M1 & 1);
1887     return true;
1888   }
1889 }
1890 
1891 
1892 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1893 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1894 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1895                                 SelectionDAG &DAG) {
1896   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1897   assert(isSplatShuffleMask(SVOp, EltSize));
1898   if (DAG.getDataLayout().isLittleEndian())
1899     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1900   else
1901     return SVOp->getMaskElt(0) / EltSize;
1902 }
1903 
1904 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1905 /// by using a vspltis[bhw] instruction of the specified element size, return
1906 /// the constant being splatted.  The ByteSize field indicates the number of
1907 /// bytes of each element [124] -> [bhw].
1908 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1909   SDValue OpVal(nullptr, 0);
1910 
1911   // If ByteSize of the splat is bigger than the element size of the
1912   // build_vector, then we have a case where we are checking for a splat where
1913   // multiple elements of the buildvector are folded together into a single
1914   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1915   unsigned EltSize = 16/N->getNumOperands();
1916   if (EltSize < ByteSize) {
1917     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1918     SDValue UniquedVals[4];
1919     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1920 
1921     // See if all of the elements in the buildvector agree across.
1922     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1923       if (N->getOperand(i).isUndef()) continue;
1924       // If the element isn't a constant, bail fully out.
1925       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1926 
1927       if (!UniquedVals[i&(Multiple-1)].getNode())
1928         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1929       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1930         return SDValue();  // no match.
1931     }
1932 
1933     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1934     // either constant or undef values that are identical for each chunk.  See
1935     // if these chunks can form into a larger vspltis*.
1936 
1937     // Check to see if all of the leading entries are either 0 or -1.  If
1938     // neither, then this won't fit into the immediate field.
1939     bool LeadingZero = true;
1940     bool LeadingOnes = true;
1941     for (unsigned i = 0; i != Multiple-1; ++i) {
1942       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1943 
1944       LeadingZero &= isNullConstant(UniquedVals[i]);
1945       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1946     }
1947     // Finally, check the least significant entry.
1948     if (LeadingZero) {
1949       if (!UniquedVals[Multiple-1].getNode())
1950         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1951       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1952       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1953         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1954     }
1955     if (LeadingOnes) {
1956       if (!UniquedVals[Multiple-1].getNode())
1957         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1958       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1959       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1960         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1961     }
1962 
1963     return SDValue();
1964   }
1965 
1966   // Check to see if this buildvec has a single non-undef value in its elements.
1967   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1968     if (N->getOperand(i).isUndef()) continue;
1969     if (!OpVal.getNode())
1970       OpVal = N->getOperand(i);
1971     else if (OpVal != N->getOperand(i))
1972       return SDValue();
1973   }
1974 
1975   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1976 
1977   unsigned ValSizeInBytes = EltSize;
1978   uint64_t Value = 0;
1979   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1980     Value = CN->getZExtValue();
1981   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1982     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1983     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1984   }
1985 
1986   // If the splat value is larger than the element value, then we can never do
1987   // this splat.  The only case that we could fit the replicated bits into our
1988   // immediate field for would be zero, and we prefer to use vxor for it.
1989   if (ValSizeInBytes < ByteSize) return SDValue();
1990 
1991   // If the element value is larger than the splat value, check if it consists
1992   // of a repeated bit pattern of size ByteSize.
1993   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1994     return SDValue();
1995 
1996   // Properly sign extend the value.
1997   int MaskVal = SignExtend32(Value, ByteSize * 8);
1998 
1999   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2000   if (MaskVal == 0) return SDValue();
2001 
2002   // Finally, if this value fits in a 5 bit sext field, return it
2003   if (SignExtend32<5>(MaskVal) == MaskVal)
2004     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2005   return SDValue();
2006 }
2007 
2008 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2009 /// amount, otherwise return -1.
2010 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2011   EVT VT = N->getValueType(0);
2012   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2013     return -1;
2014 
2015   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2016 
2017   // Find the first non-undef value in the shuffle mask.
2018   unsigned i;
2019   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2020     /*search*/;
2021 
2022   if (i == 4) return -1;  // all undef.
2023 
2024   // Otherwise, check to see if the rest of the elements are consecutively
2025   // numbered from this value.
2026   unsigned ShiftAmt = SVOp->getMaskElt(i);
2027   if (ShiftAmt < i) return -1;
2028   ShiftAmt -= i;
2029 
2030   // Check the rest of the elements to see if they are consecutive.
2031   for (++i; i != 4; ++i)
2032     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2033       return -1;
2034 
2035   return ShiftAmt;
2036 }
2037 
2038 //===----------------------------------------------------------------------===//
2039 //  Addressing Mode Selection
2040 //===----------------------------------------------------------------------===//
2041 
2042 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2043 /// or 64-bit immediate, and if the value can be accurately represented as a
2044 /// sign extension from a 16-bit value.  If so, this returns true and the
2045 /// immediate.
2046 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2047   if (!isa<ConstantSDNode>(N))
2048     return false;
2049 
2050   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2051   if (N->getValueType(0) == MVT::i32)
2052     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2053   else
2054     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2055 }
2056 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2057   return isIntS16Immediate(Op.getNode(), Imm);
2058 }
2059 
2060 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2061 /// can be represented as an indexed [r+r] operation.  Returns false if it
2062 /// can be more efficiently represented with [r+imm].
2063 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2064                                             SDValue &Index,
2065                                             SelectionDAG &DAG) const {
2066   int16_t imm = 0;
2067   if (N.getOpcode() == ISD::ADD) {
2068     if (isIntS16Immediate(N.getOperand(1), imm))
2069       return false;    // r+i
2070     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2071       return false;    // r+i
2072 
2073     Base = N.getOperand(0);
2074     Index = N.getOperand(1);
2075     return true;
2076   } else if (N.getOpcode() == ISD::OR) {
2077     if (isIntS16Immediate(N.getOperand(1), imm))
2078       return false;    // r+i can fold it if we can.
2079 
2080     // If this is an or of disjoint bitfields, we can codegen this as an add
2081     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2082     // disjoint.
2083     KnownBits LHSKnown, RHSKnown;
2084     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2085 
2086     if (LHSKnown.Zero.getBoolValue()) {
2087       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2088       // If all of the bits are known zero on the LHS or RHS, the add won't
2089       // carry.
2090       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2091         Base = N.getOperand(0);
2092         Index = N.getOperand(1);
2093         return true;
2094       }
2095     }
2096   }
2097 
2098   return false;
2099 }
2100 
2101 // If we happen to be doing an i64 load or store into a stack slot that has
2102 // less than a 4-byte alignment, then the frame-index elimination may need to
2103 // use an indexed load or store instruction (because the offset may not be a
2104 // multiple of 4). The extra register needed to hold the offset comes from the
2105 // register scavenger, and it is possible that the scavenger will need to use
2106 // an emergency spill slot. As a result, we need to make sure that a spill slot
2107 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2108 // stack slot.
2109 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2110   // FIXME: This does not handle the LWA case.
2111   if (VT != MVT::i64)
2112     return;
2113 
2114   // NOTE: We'll exclude negative FIs here, which come from argument
2115   // lowering, because there are no known test cases triggering this problem
2116   // using packed structures (or similar). We can remove this exclusion if
2117   // we find such a test case. The reason why this is so test-case driven is
2118   // because this entire 'fixup' is only to prevent crashes (from the
2119   // register scavenger) on not-really-valid inputs. For example, if we have:
2120   //   %a = alloca i1
2121   //   %b = bitcast i1* %a to i64*
2122   //   store i64* a, i64 b
2123   // then the store should really be marked as 'align 1', but is not. If it
2124   // were marked as 'align 1' then the indexed form would have been
2125   // instruction-selected initially, and the problem this 'fixup' is preventing
2126   // won't happen regardless.
2127   if (FrameIdx < 0)
2128     return;
2129 
2130   MachineFunction &MF = DAG.getMachineFunction();
2131   MachineFrameInfo &MFI = MF.getFrameInfo();
2132 
2133   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2134   if (Align >= 4)
2135     return;
2136 
2137   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2138   FuncInfo->setHasNonRISpills();
2139 }
2140 
2141 /// Returns true if the address N can be represented by a base register plus
2142 /// a signed 16-bit displacement [r+imm], and if it is not better
2143 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2144 /// displacements that are multiples of that value.
2145 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2146                                             SDValue &Base,
2147                                             SelectionDAG &DAG,
2148                                             unsigned Alignment) const {
2149   // FIXME dl should come from parent load or store, not from address
2150   SDLoc dl(N);
2151   // If this can be more profitably realized as r+r, fail.
2152   if (SelectAddressRegReg(N, Disp, Base, DAG))
2153     return false;
2154 
2155   if (N.getOpcode() == ISD::ADD) {
2156     int16_t imm = 0;
2157     if (isIntS16Immediate(N.getOperand(1), imm) &&
2158         (!Alignment || (imm % Alignment) == 0)) {
2159       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2160       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2161         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2162         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2163       } else {
2164         Base = N.getOperand(0);
2165       }
2166       return true; // [r+i]
2167     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2168       // Match LOAD (ADD (X, Lo(G))).
2169       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2170              && "Cannot handle constant offsets yet!");
2171       Disp = N.getOperand(1).getOperand(0);  // The global address.
2172       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2173              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2174              Disp.getOpcode() == ISD::TargetConstantPool ||
2175              Disp.getOpcode() == ISD::TargetJumpTable);
2176       Base = N.getOperand(0);
2177       return true;  // [&g+r]
2178     }
2179   } else if (N.getOpcode() == ISD::OR) {
2180     int16_t imm = 0;
2181     if (isIntS16Immediate(N.getOperand(1), imm) &&
2182         (!Alignment || (imm % Alignment) == 0)) {
2183       // If this is an or of disjoint bitfields, we can codegen this as an add
2184       // (for better address arithmetic) if the LHS and RHS of the OR are
2185       // provably disjoint.
2186       KnownBits LHSKnown;
2187       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2188 
2189       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2190         // If all of the bits are known zero on the LHS or RHS, the add won't
2191         // carry.
2192         if (FrameIndexSDNode *FI =
2193               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2194           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2195           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2196         } else {
2197           Base = N.getOperand(0);
2198         }
2199         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2200         return true;
2201       }
2202     }
2203   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2204     // Loading from a constant address.
2205 
2206     // If this address fits entirely in a 16-bit sext immediate field, codegen
2207     // this as "d, 0"
2208     int16_t Imm;
2209     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2210       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2211       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2212                              CN->getValueType(0));
2213       return true;
2214     }
2215 
2216     // Handle 32-bit sext immediates with LIS + addr mode.
2217     if ((CN->getValueType(0) == MVT::i32 ||
2218          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2219         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2220       int Addr = (int)CN->getZExtValue();
2221 
2222       // Otherwise, break this down into an LIS + disp.
2223       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2224 
2225       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2226                                    MVT::i32);
2227       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2228       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2229       return true;
2230     }
2231   }
2232 
2233   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2234   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2235     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2236     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2237   } else
2238     Base = N;
2239   return true;      // [r+0]
2240 }
2241 
2242 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2243 /// represented as an indexed [r+r] operation.
2244 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2245                                                 SDValue &Index,
2246                                                 SelectionDAG &DAG) const {
2247   // Check to see if we can easily represent this as an [r+r] address.  This
2248   // will fail if it thinks that the address is more profitably represented as
2249   // reg+imm, e.g. where imm = 0.
2250   if (SelectAddressRegReg(N, Base, Index, DAG))
2251     return true;
2252 
2253   // If the address is the result of an add, we will utilize the fact that the
2254   // address calculation includes an implicit add.  However, we can reduce
2255   // register pressure if we do not materialize a constant just for use as the
2256   // index register.  We only get rid of the add if it is not an add of a
2257   // value and a 16-bit signed constant and both have a single use.
2258   int16_t imm = 0;
2259   if (N.getOpcode() == ISD::ADD &&
2260       (!isIntS16Immediate(N.getOperand(1), imm) ||
2261        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2262     Base = N.getOperand(0);
2263     Index = N.getOperand(1);
2264     return true;
2265   }
2266 
2267   // Otherwise, do it the hard way, using R0 as the base register.
2268   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2269                          N.getValueType());
2270   Index = N;
2271   return true;
2272 }
2273 
2274 /// getPreIndexedAddressParts - returns true by value, base pointer and
2275 /// offset pointer and addressing mode by reference if the node's address
2276 /// can be legally represented as pre-indexed load / store address.
2277 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2278                                                   SDValue &Offset,
2279                                                   ISD::MemIndexedMode &AM,
2280                                                   SelectionDAG &DAG) const {
2281   if (DisablePPCPreinc) return false;
2282 
2283   bool isLoad = true;
2284   SDValue Ptr;
2285   EVT VT;
2286   unsigned Alignment;
2287   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2288     Ptr = LD->getBasePtr();
2289     VT = LD->getMemoryVT();
2290     Alignment = LD->getAlignment();
2291   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2292     Ptr = ST->getBasePtr();
2293     VT  = ST->getMemoryVT();
2294     Alignment = ST->getAlignment();
2295     isLoad = false;
2296   } else
2297     return false;
2298 
2299   // PowerPC doesn't have preinc load/store instructions for vectors (except
2300   // for QPX, which does have preinc r+r forms).
2301   if (VT.isVector()) {
2302     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2303       return false;
2304     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2305       AM = ISD::PRE_INC;
2306       return true;
2307     }
2308   }
2309 
2310   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2311     // Common code will reject creating a pre-inc form if the base pointer
2312     // is a frame index, or if N is a store and the base pointer is either
2313     // the same as or a predecessor of the value being stored.  Check for
2314     // those situations here, and try with swapped Base/Offset instead.
2315     bool Swap = false;
2316 
2317     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2318       Swap = true;
2319     else if (!isLoad) {
2320       SDValue Val = cast<StoreSDNode>(N)->getValue();
2321       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2322         Swap = true;
2323     }
2324 
2325     if (Swap)
2326       std::swap(Base, Offset);
2327 
2328     AM = ISD::PRE_INC;
2329     return true;
2330   }
2331 
2332   // LDU/STU can only handle immediates that are a multiple of 4.
2333   if (VT != MVT::i64) {
2334     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2335       return false;
2336   } else {
2337     // LDU/STU need an address with at least 4-byte alignment.
2338     if (Alignment < 4)
2339       return false;
2340 
2341     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2342       return false;
2343   }
2344 
2345   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2346     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2347     // sext i32 to i64 when addr mode is r+i.
2348     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2349         LD->getExtensionType() == ISD::SEXTLOAD &&
2350         isa<ConstantSDNode>(Offset))
2351       return false;
2352   }
2353 
2354   AM = ISD::PRE_INC;
2355   return true;
2356 }
2357 
2358 //===----------------------------------------------------------------------===//
2359 //  LowerOperation implementation
2360 //===----------------------------------------------------------------------===//
2361 
2362 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2363 /// and LoOpFlags to the target MO flags.
2364 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2365                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2366                                const GlobalValue *GV = nullptr) {
2367   HiOpFlags = PPCII::MO_HA;
2368   LoOpFlags = PPCII::MO_LO;
2369 
2370   // Don't use the pic base if not in PIC relocation model.
2371   if (IsPIC) {
2372     HiOpFlags |= PPCII::MO_PIC_FLAG;
2373     LoOpFlags |= PPCII::MO_PIC_FLAG;
2374   }
2375 
2376   // If this is a reference to a global value that requires a non-lazy-ptr, make
2377   // sure that instruction lowering adds it.
2378   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2379     HiOpFlags |= PPCII::MO_NLP_FLAG;
2380     LoOpFlags |= PPCII::MO_NLP_FLAG;
2381 
2382     if (GV->hasHiddenVisibility()) {
2383       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2384       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2385     }
2386   }
2387 }
2388 
2389 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2390                              SelectionDAG &DAG) {
2391   SDLoc DL(HiPart);
2392   EVT PtrVT = HiPart.getValueType();
2393   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2394 
2395   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2396   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2397 
2398   // With PIC, the first instruction is actually "GR+hi(&G)".
2399   if (isPIC)
2400     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2401                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2402 
2403   // Generate non-pic code that has direct accesses to the constant pool.
2404   // The address of the global is just (hi(&g)+lo(&g)).
2405   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2406 }
2407 
2408 static void setUsesTOCBasePtr(MachineFunction &MF) {
2409   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2410   FuncInfo->setUsesTOCBasePtr();
2411 }
2412 
2413 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2414   setUsesTOCBasePtr(DAG.getMachineFunction());
2415 }
2416 
2417 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2418                            SDValue GA) {
2419   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2420   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2421                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2422 
2423   SDValue Ops[] = { GA, Reg };
2424   return DAG.getMemIntrinsicNode(
2425       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2426       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2427       false, 0);
2428 }
2429 
2430 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2431                                              SelectionDAG &DAG) const {
2432   EVT PtrVT = Op.getValueType();
2433   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2434   const Constant *C = CP->getConstVal();
2435 
2436   // 64-bit SVR4 ABI code is always position-independent.
2437   // The actual address of the GlobalValue is stored in the TOC.
2438   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2439     setUsesTOCBasePtr(DAG);
2440     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2441     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2442   }
2443 
2444   unsigned MOHiFlag, MOLoFlag;
2445   bool IsPIC = isPositionIndependent();
2446   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2447 
2448   if (IsPIC && Subtarget.isSVR4ABI()) {
2449     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2450                                            PPCII::MO_PIC_FLAG);
2451     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2452   }
2453 
2454   SDValue CPIHi =
2455     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2456   SDValue CPILo =
2457     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2458   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2459 }
2460 
2461 // For 64-bit PowerPC, prefer the more compact relative encodings.
2462 // This trades 32 bits per jump table entry for one or two instructions
2463 // on the jump site.
2464 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2465   if (isJumpTableRelative())
2466     return MachineJumpTableInfo::EK_LabelDifference32;
2467 
2468   return TargetLowering::getJumpTableEncoding();
2469 }
2470 
2471 bool PPCTargetLowering::isJumpTableRelative() const {
2472   if (Subtarget.isPPC64())
2473     return true;
2474   return TargetLowering::isJumpTableRelative();
2475 }
2476 
2477 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2478                                                     SelectionDAG &DAG) const {
2479   if (!Subtarget.isPPC64())
2480     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2481 
2482   switch (getTargetMachine().getCodeModel()) {
2483   case CodeModel::Small:
2484   case CodeModel::Medium:
2485     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2486   default:
2487     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2488                        getPointerTy(DAG.getDataLayout()));
2489   }
2490 }
2491 
2492 const MCExpr *
2493 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2494                                                 unsigned JTI,
2495                                                 MCContext &Ctx) const {
2496   if (!Subtarget.isPPC64())
2497     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2498 
2499   switch (getTargetMachine().getCodeModel()) {
2500   case CodeModel::Small:
2501   case CodeModel::Medium:
2502     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2503   default:
2504     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2505   }
2506 }
2507 
2508 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2509   EVT PtrVT = Op.getValueType();
2510   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2511 
2512   // 64-bit SVR4 ABI code is always position-independent.
2513   // The actual address of the GlobalValue is stored in the TOC.
2514   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2515     setUsesTOCBasePtr(DAG);
2516     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2517     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2518   }
2519 
2520   unsigned MOHiFlag, MOLoFlag;
2521   bool IsPIC = isPositionIndependent();
2522   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2523 
2524   if (IsPIC && Subtarget.isSVR4ABI()) {
2525     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2526                                         PPCII::MO_PIC_FLAG);
2527     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2528   }
2529 
2530   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2531   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2532   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2533 }
2534 
2535 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2536                                              SelectionDAG &DAG) const {
2537   EVT PtrVT = Op.getValueType();
2538   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2539   const BlockAddress *BA = BASDN->getBlockAddress();
2540 
2541   // 64-bit SVR4 ABI code is always position-independent.
2542   // The actual BlockAddress is stored in the TOC.
2543   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2544     setUsesTOCBasePtr(DAG);
2545     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2546     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2547   }
2548 
2549   unsigned MOHiFlag, MOLoFlag;
2550   bool IsPIC = isPositionIndependent();
2551   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2552   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2553   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2554   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2555 }
2556 
2557 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2558                                               SelectionDAG &DAG) const {
2559   // FIXME: TLS addresses currently use medium model code sequences,
2560   // which is the most useful form.  Eventually support for small and
2561   // large models could be added if users need it, at the cost of
2562   // additional complexity.
2563   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2564   if (DAG.getTarget().Options.EmulatedTLS)
2565     return LowerToTLSEmulatedModel(GA, DAG);
2566 
2567   SDLoc dl(GA);
2568   const GlobalValue *GV = GA->getGlobal();
2569   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2570   bool is64bit = Subtarget.isPPC64();
2571   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2572   PICLevel::Level picLevel = M->getPICLevel();
2573 
2574   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2575 
2576   if (Model == TLSModel::LocalExec) {
2577     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2578                                                PPCII::MO_TPREL_HA);
2579     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2580                                                PPCII::MO_TPREL_LO);
2581     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2582                              : DAG.getRegister(PPC::R2, MVT::i32);
2583 
2584     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2585     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2586   }
2587 
2588   if (Model == TLSModel::InitialExec) {
2589     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2590     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2591                                                 PPCII::MO_TLS);
2592     SDValue GOTPtr;
2593     if (is64bit) {
2594       setUsesTOCBasePtr(DAG);
2595       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2596       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2597                            PtrVT, GOTReg, TGA);
2598     } else
2599       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2600     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2601                                    PtrVT, TGA, GOTPtr);
2602     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2603   }
2604 
2605   if (Model == TLSModel::GeneralDynamic) {
2606     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2607     SDValue GOTPtr;
2608     if (is64bit) {
2609       setUsesTOCBasePtr(DAG);
2610       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2611       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2612                                    GOTReg, TGA);
2613     } else {
2614       if (picLevel == PICLevel::SmallPIC)
2615         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2616       else
2617         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2618     }
2619     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2620                        GOTPtr, TGA, TGA);
2621   }
2622 
2623   if (Model == TLSModel::LocalDynamic) {
2624     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2625     SDValue GOTPtr;
2626     if (is64bit) {
2627       setUsesTOCBasePtr(DAG);
2628       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2629       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2630                            GOTReg, TGA);
2631     } else {
2632       if (picLevel == PICLevel::SmallPIC)
2633         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2634       else
2635         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2636     }
2637     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2638                                   PtrVT, GOTPtr, TGA, TGA);
2639     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2640                                       PtrVT, TLSAddr, TGA);
2641     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2642   }
2643 
2644   llvm_unreachable("Unknown TLS model!");
2645 }
2646 
2647 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2648                                               SelectionDAG &DAG) const {
2649   EVT PtrVT = Op.getValueType();
2650   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2651   SDLoc DL(GSDN);
2652   const GlobalValue *GV = GSDN->getGlobal();
2653 
2654   // 64-bit SVR4 ABI code is always position-independent.
2655   // The actual address of the GlobalValue is stored in the TOC.
2656   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2657     setUsesTOCBasePtr(DAG);
2658     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2659     return getTOCEntry(DAG, DL, true, GA);
2660   }
2661 
2662   unsigned MOHiFlag, MOLoFlag;
2663   bool IsPIC = isPositionIndependent();
2664   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2665 
2666   if (IsPIC && Subtarget.isSVR4ABI()) {
2667     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2668                                             GSDN->getOffset(),
2669                                             PPCII::MO_PIC_FLAG);
2670     return getTOCEntry(DAG, DL, false, GA);
2671   }
2672 
2673   SDValue GAHi =
2674     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2675   SDValue GALo =
2676     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2677 
2678   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2679 
2680   // If the global reference is actually to a non-lazy-pointer, we have to do an
2681   // extra load to get the address of the global.
2682   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2683     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2684   return Ptr;
2685 }
2686 
2687 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2688   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2689   SDLoc dl(Op);
2690 
2691   if (Op.getValueType() == MVT::v2i64) {
2692     // When the operands themselves are v2i64 values, we need to do something
2693     // special because VSX has no underlying comparison operations for these.
2694     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2695       // Equality can be handled by casting to the legal type for Altivec
2696       // comparisons, everything else needs to be expanded.
2697       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2698         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2699                  DAG.getSetCC(dl, MVT::v4i32,
2700                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2701                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2702                    CC));
2703       }
2704 
2705       return SDValue();
2706     }
2707 
2708     // We handle most of these in the usual way.
2709     return Op;
2710   }
2711 
2712   // If we're comparing for equality to zero, expose the fact that this is
2713   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2714   // fold the new nodes.
2715   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2716     return V;
2717 
2718   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2719     // Leave comparisons against 0 and -1 alone for now, since they're usually
2720     // optimized.  FIXME: revisit this when we can custom lower all setcc
2721     // optimizations.
2722     if (C->isAllOnesValue() || C->isNullValue())
2723       return SDValue();
2724   }
2725 
2726   // If we have an integer seteq/setne, turn it into a compare against zero
2727   // by xor'ing the rhs with the lhs, which is faster than setting a
2728   // condition register, reading it back out, and masking the correct bit.  The
2729   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2730   // the result to other bit-twiddling opportunities.
2731   EVT LHSVT = Op.getOperand(0).getValueType();
2732   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2733     EVT VT = Op.getValueType();
2734     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2735                                 Op.getOperand(1));
2736     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2737   }
2738   return SDValue();
2739 }
2740 
2741 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2742   SDNode *Node = Op.getNode();
2743   EVT VT = Node->getValueType(0);
2744   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2745   SDValue InChain = Node->getOperand(0);
2746   SDValue VAListPtr = Node->getOperand(1);
2747   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2748   SDLoc dl(Node);
2749 
2750   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2751 
2752   // gpr_index
2753   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2754                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2755   InChain = GprIndex.getValue(1);
2756 
2757   if (VT == MVT::i64) {
2758     // Check if GprIndex is even
2759     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2760                                  DAG.getConstant(1, dl, MVT::i32));
2761     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2762                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2763     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2764                                           DAG.getConstant(1, dl, MVT::i32));
2765     // Align GprIndex to be even if it isn't
2766     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2767                            GprIndex);
2768   }
2769 
2770   // fpr index is 1 byte after gpr
2771   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2772                                DAG.getConstant(1, dl, MVT::i32));
2773 
2774   // fpr
2775   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2776                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2777   InChain = FprIndex.getValue(1);
2778 
2779   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2780                                        DAG.getConstant(8, dl, MVT::i32));
2781 
2782   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2783                                         DAG.getConstant(4, dl, MVT::i32));
2784 
2785   // areas
2786   SDValue OverflowArea =
2787       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2788   InChain = OverflowArea.getValue(1);
2789 
2790   SDValue RegSaveArea =
2791       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2792   InChain = RegSaveArea.getValue(1);
2793 
2794   // select overflow_area if index > 8
2795   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2796                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2797 
2798   // adjustment constant gpr_index * 4/8
2799   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2800                                     VT.isInteger() ? GprIndex : FprIndex,
2801                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2802                                                     MVT::i32));
2803 
2804   // OurReg = RegSaveArea + RegConstant
2805   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2806                                RegConstant);
2807 
2808   // Floating types are 32 bytes into RegSaveArea
2809   if (VT.isFloatingPoint())
2810     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2811                          DAG.getConstant(32, dl, MVT::i32));
2812 
2813   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2814   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2815                                    VT.isInteger() ? GprIndex : FprIndex,
2816                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2817                                                    MVT::i32));
2818 
2819   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2820                               VT.isInteger() ? VAListPtr : FprPtr,
2821                               MachinePointerInfo(SV), MVT::i8);
2822 
2823   // determine if we should load from reg_save_area or overflow_area
2824   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2825 
2826   // increase overflow_area by 4/8 if gpr/fpr > 8
2827   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2828                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2829                                           dl, MVT::i32));
2830 
2831   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2832                              OverflowAreaPlusN);
2833 
2834   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2835                               MachinePointerInfo(), MVT::i32);
2836 
2837   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2838 }
2839 
2840 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2841   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2842 
2843   // We have to copy the entire va_list struct:
2844   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2845   return DAG.getMemcpy(Op.getOperand(0), Op,
2846                        Op.getOperand(1), Op.getOperand(2),
2847                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2848                        false, MachinePointerInfo(), MachinePointerInfo());
2849 }
2850 
2851 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2852                                                   SelectionDAG &DAG) const {
2853   return Op.getOperand(0);
2854 }
2855 
2856 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2857                                                 SelectionDAG &DAG) const {
2858   SDValue Chain = Op.getOperand(0);
2859   SDValue Trmp = Op.getOperand(1); // trampoline
2860   SDValue FPtr = Op.getOperand(2); // nested function
2861   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2862   SDLoc dl(Op);
2863 
2864   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2865   bool isPPC64 = (PtrVT == MVT::i64);
2866   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2867 
2868   TargetLowering::ArgListTy Args;
2869   TargetLowering::ArgListEntry Entry;
2870 
2871   Entry.Ty = IntPtrTy;
2872   Entry.Node = Trmp; Args.push_back(Entry);
2873 
2874   // TrampSize == (isPPC64 ? 48 : 40);
2875   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2876                                isPPC64 ? MVT::i64 : MVT::i32);
2877   Args.push_back(Entry);
2878 
2879   Entry.Node = FPtr; Args.push_back(Entry);
2880   Entry.Node = Nest; Args.push_back(Entry);
2881 
2882   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2883   TargetLowering::CallLoweringInfo CLI(DAG);
2884   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2885       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2886       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2887 
2888   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2889   return CallResult.second;
2890 }
2891 
2892 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2893   MachineFunction &MF = DAG.getMachineFunction();
2894   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2895   EVT PtrVT = getPointerTy(MF.getDataLayout());
2896 
2897   SDLoc dl(Op);
2898 
2899   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2900     // vastart just stores the address of the VarArgsFrameIndex slot into the
2901     // memory location argument.
2902     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2903     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2904     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2905                         MachinePointerInfo(SV));
2906   }
2907 
2908   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2909   // We suppose the given va_list is already allocated.
2910   //
2911   // typedef struct {
2912   //  char gpr;     /* index into the array of 8 GPRs
2913   //                 * stored in the register save area
2914   //                 * gpr=0 corresponds to r3,
2915   //                 * gpr=1 to r4, etc.
2916   //                 */
2917   //  char fpr;     /* index into the array of 8 FPRs
2918   //                 * stored in the register save area
2919   //                 * fpr=0 corresponds to f1,
2920   //                 * fpr=1 to f2, etc.
2921   //                 */
2922   //  char *overflow_arg_area;
2923   //                /* location on stack that holds
2924   //                 * the next overflow argument
2925   //                 */
2926   //  char *reg_save_area;
2927   //               /* where r3:r10 and f1:f8 (if saved)
2928   //                * are stored
2929   //                */
2930   // } va_list[1];
2931 
2932   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2933   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2934   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2935                                             PtrVT);
2936   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2937                                  PtrVT);
2938 
2939   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2940   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2941 
2942   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2943   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2944 
2945   uint64_t FPROffset = 1;
2946   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2947 
2948   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2949 
2950   // Store first byte : number of int regs
2951   SDValue firstStore =
2952       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2953                         MachinePointerInfo(SV), MVT::i8);
2954   uint64_t nextOffset = FPROffset;
2955   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2956                                   ConstFPROffset);
2957 
2958   // Store second byte : number of float regs
2959   SDValue secondStore =
2960       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2961                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2962   nextOffset += StackOffset;
2963   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2964 
2965   // Store second word : arguments given on stack
2966   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2967                                     MachinePointerInfo(SV, nextOffset));
2968   nextOffset += FrameOffset;
2969   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2970 
2971   // Store third word : arguments given in registers
2972   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2973                       MachinePointerInfo(SV, nextOffset));
2974 }
2975 
2976 #include "PPCGenCallingConv.inc"
2977 
2978 // Function whose sole purpose is to kill compiler warnings
2979 // stemming from unused functions included from PPCGenCallingConv.inc.
2980 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2981   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2982 }
2983 
2984 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2985                                       CCValAssign::LocInfo &LocInfo,
2986                                       ISD::ArgFlagsTy &ArgFlags,
2987                                       CCState &State) {
2988   return true;
2989 }
2990 
2991 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2992                                              MVT &LocVT,
2993                                              CCValAssign::LocInfo &LocInfo,
2994                                              ISD::ArgFlagsTy &ArgFlags,
2995                                              CCState &State) {
2996   static const MCPhysReg ArgRegs[] = {
2997     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2998     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2999   };
3000   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3001 
3002   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3003 
3004   // Skip one register if the first unallocated register has an even register
3005   // number and there are still argument registers available which have not been
3006   // allocated yet. RegNum is actually an index into ArgRegs, which means we
3007   // need to skip a register if RegNum is odd.
3008   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3009     State.AllocateReg(ArgRegs[RegNum]);
3010   }
3011 
3012   // Always return false here, as this function only makes sure that the first
3013   // unallocated register has an odd register number and does not actually
3014   // allocate a register for the current argument.
3015   return false;
3016 }
3017 
3018 bool
3019 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3020                                                   MVT &LocVT,
3021                                                   CCValAssign::LocInfo &LocInfo,
3022                                                   ISD::ArgFlagsTy &ArgFlags,
3023                                                   CCState &State) {
3024   static const MCPhysReg ArgRegs[] = {
3025     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3026     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3027   };
3028   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3029 
3030   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3031   int RegsLeft = NumArgRegs - RegNum;
3032 
3033   // Skip if there is not enough registers left for long double type (4 gpr regs
3034   // in soft float mode) and put long double argument on the stack.
3035   if (RegNum != NumArgRegs && RegsLeft < 4) {
3036     for (int i = 0; i < RegsLeft; i++) {
3037       State.AllocateReg(ArgRegs[RegNum + i]);
3038     }
3039   }
3040 
3041   return false;
3042 }
3043 
3044 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3045                                                MVT &LocVT,
3046                                                CCValAssign::LocInfo &LocInfo,
3047                                                ISD::ArgFlagsTy &ArgFlags,
3048                                                CCState &State) {
3049   static const MCPhysReg ArgRegs[] = {
3050     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3051     PPC::F8
3052   };
3053 
3054   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3055 
3056   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3057 
3058   // If there is only one Floating-point register left we need to put both f64
3059   // values of a split ppc_fp128 value on the stack.
3060   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3061     State.AllocateReg(ArgRegs[RegNum]);
3062   }
3063 
3064   // Always return false here, as this function only makes sure that the two f64
3065   // values a ppc_fp128 value is split into are both passed in registers or both
3066   // passed on the stack and does not actually allocate a register for the
3067   // current argument.
3068   return false;
3069 }
3070 
3071 /// FPR - The set of FP registers that should be allocated for arguments,
3072 /// on Darwin.
3073 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3074                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3075                                 PPC::F11, PPC::F12, PPC::F13};
3076 
3077 /// QFPR - The set of QPX registers that should be allocated for arguments.
3078 static const MCPhysReg QFPR[] = {
3079     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3080     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3081 
3082 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3083 /// the stack.
3084 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3085                                        unsigned PtrByteSize) {
3086   unsigned ArgSize = ArgVT.getStoreSize();
3087   if (Flags.isByVal())
3088     ArgSize = Flags.getByValSize();
3089 
3090   // Round up to multiples of the pointer size, except for array members,
3091   // which are always packed.
3092   if (!Flags.isInConsecutiveRegs())
3093     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3094 
3095   return ArgSize;
3096 }
3097 
3098 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3099 /// on the stack.
3100 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3101                                             ISD::ArgFlagsTy Flags,
3102                                             unsigned PtrByteSize) {
3103   unsigned Align = PtrByteSize;
3104 
3105   // Altivec parameters are padded to a 16 byte boundary.
3106   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3107       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3108       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3109       ArgVT == MVT::v1i128)
3110     Align = 16;
3111   // QPX vector types stored in double-precision are padded to a 32 byte
3112   // boundary.
3113   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3114     Align = 32;
3115 
3116   // ByVal parameters are aligned as requested.
3117   if (Flags.isByVal()) {
3118     unsigned BVAlign = Flags.getByValAlign();
3119     if (BVAlign > PtrByteSize) {
3120       if (BVAlign % PtrByteSize != 0)
3121           llvm_unreachable(
3122             "ByVal alignment is not a multiple of the pointer size");
3123 
3124       Align = BVAlign;
3125     }
3126   }
3127 
3128   // Array members are always packed to their original alignment.
3129   if (Flags.isInConsecutiveRegs()) {
3130     // If the array member was split into multiple registers, the first
3131     // needs to be aligned to the size of the full type.  (Except for
3132     // ppcf128, which is only aligned as its f64 components.)
3133     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3134       Align = OrigVT.getStoreSize();
3135     else
3136       Align = ArgVT.getStoreSize();
3137   }
3138 
3139   return Align;
3140 }
3141 
3142 /// CalculateStackSlotUsed - Return whether this argument will use its
3143 /// stack slot (instead of being passed in registers).  ArgOffset,
3144 /// AvailableFPRs, and AvailableVRs must hold the current argument
3145 /// position, and will be updated to account for this argument.
3146 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3147                                    ISD::ArgFlagsTy Flags,
3148                                    unsigned PtrByteSize,
3149                                    unsigned LinkageSize,
3150                                    unsigned ParamAreaSize,
3151                                    unsigned &ArgOffset,
3152                                    unsigned &AvailableFPRs,
3153                                    unsigned &AvailableVRs, bool HasQPX) {
3154   bool UseMemory = false;
3155 
3156   // Respect alignment of argument on the stack.
3157   unsigned Align =
3158     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3159   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3160   // If there's no space left in the argument save area, we must
3161   // use memory (this check also catches zero-sized arguments).
3162   if (ArgOffset >= LinkageSize + ParamAreaSize)
3163     UseMemory = true;
3164 
3165   // Allocate argument on the stack.
3166   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3167   if (Flags.isInConsecutiveRegsLast())
3168     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3169   // If we overran the argument save area, we must use memory
3170   // (this check catches arguments passed partially in memory)
3171   if (ArgOffset > LinkageSize + ParamAreaSize)
3172     UseMemory = true;
3173 
3174   // However, if the argument is actually passed in an FPR or a VR,
3175   // we don't use memory after all.
3176   if (!Flags.isByVal()) {
3177     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3178         // QPX registers overlap with the scalar FP registers.
3179         (HasQPX && (ArgVT == MVT::v4f32 ||
3180                     ArgVT == MVT::v4f64 ||
3181                     ArgVT == MVT::v4i1)))
3182       if (AvailableFPRs > 0) {
3183         --AvailableFPRs;
3184         return false;
3185       }
3186     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3187         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3188         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3189         ArgVT == MVT::v1i128)
3190       if (AvailableVRs > 0) {
3191         --AvailableVRs;
3192         return false;
3193       }
3194   }
3195 
3196   return UseMemory;
3197 }
3198 
3199 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3200 /// ensure minimum alignment required for target.
3201 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3202                                      unsigned NumBytes) {
3203   unsigned TargetAlign = Lowering->getStackAlignment();
3204   unsigned AlignMask = TargetAlign - 1;
3205   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3206   return NumBytes;
3207 }
3208 
3209 SDValue PPCTargetLowering::LowerFormalArguments(
3210     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3211     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3212     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3213   if (Subtarget.isSVR4ABI()) {
3214     if (Subtarget.isPPC64())
3215       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3216                                          dl, DAG, InVals);
3217     else
3218       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3219                                          dl, DAG, InVals);
3220   } else {
3221     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3222                                        dl, DAG, InVals);
3223   }
3224 }
3225 
3226 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3227     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3228     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3229     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3230 
3231   // 32-bit SVR4 ABI Stack Frame Layout:
3232   //              +-----------------------------------+
3233   //        +-->  |            Back chain             |
3234   //        |     +-----------------------------------+
3235   //        |     | Floating-point register save area |
3236   //        |     +-----------------------------------+
3237   //        |     |    General register save area     |
3238   //        |     +-----------------------------------+
3239   //        |     |          CR save word             |
3240   //        |     +-----------------------------------+
3241   //        |     |         VRSAVE save word          |
3242   //        |     +-----------------------------------+
3243   //        |     |         Alignment padding         |
3244   //        |     +-----------------------------------+
3245   //        |     |     Vector register save area     |
3246   //        |     +-----------------------------------+
3247   //        |     |       Local variable space        |
3248   //        |     +-----------------------------------+
3249   //        |     |        Parameter list area        |
3250   //        |     +-----------------------------------+
3251   //        |     |           LR save word            |
3252   //        |     +-----------------------------------+
3253   // SP-->  +---  |            Back chain             |
3254   //              +-----------------------------------+
3255   //
3256   // Specifications:
3257   //   System V Application Binary Interface PowerPC Processor Supplement
3258   //   AltiVec Technology Programming Interface Manual
3259 
3260   MachineFunction &MF = DAG.getMachineFunction();
3261   MachineFrameInfo &MFI = MF.getFrameInfo();
3262   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3263 
3264   EVT PtrVT = getPointerTy(MF.getDataLayout());
3265   // Potential tail calls could cause overwriting of argument stack slots.
3266   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3267                        (CallConv == CallingConv::Fast));
3268   unsigned PtrByteSize = 4;
3269 
3270   // Assign locations to all of the incoming arguments.
3271   SmallVector<CCValAssign, 16> ArgLocs;
3272   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3273                  *DAG.getContext());
3274 
3275   // Reserve space for the linkage area on the stack.
3276   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3277   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3278   if (useSoftFloat())
3279     CCInfo.PreAnalyzeFormalArguments(Ins);
3280 
3281   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3282   CCInfo.clearWasPPCF128();
3283 
3284   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3285     CCValAssign &VA = ArgLocs[i];
3286 
3287     // Arguments stored in registers.
3288     if (VA.isRegLoc()) {
3289       const TargetRegisterClass *RC;
3290       EVT ValVT = VA.getValVT();
3291 
3292       switch (ValVT.getSimpleVT().SimpleTy) {
3293         default:
3294           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3295         case MVT::i1:
3296         case MVT::i32:
3297           RC = &PPC::GPRCRegClass;
3298           break;
3299         case MVT::f32:
3300           if (Subtarget.hasP8Vector())
3301             RC = &PPC::VSSRCRegClass;
3302           else
3303             RC = &PPC::F4RCRegClass;
3304           break;
3305         case MVT::f64:
3306           if (Subtarget.hasVSX())
3307             RC = &PPC::VSFRCRegClass;
3308           else
3309             RC = &PPC::F8RCRegClass;
3310           break;
3311         case MVT::v16i8:
3312         case MVT::v8i16:
3313         case MVT::v4i32:
3314           RC = &PPC::VRRCRegClass;
3315           break;
3316         case MVT::v4f32:
3317           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3318           break;
3319         case MVT::v2f64:
3320         case MVT::v2i64:
3321           RC = &PPC::VRRCRegClass;
3322           break;
3323         case MVT::v4f64:
3324           RC = &PPC::QFRCRegClass;
3325           break;
3326         case MVT::v4i1:
3327           RC = &PPC::QBRCRegClass;
3328           break;
3329       }
3330 
3331       // Transform the arguments stored in physical registers into virtual ones.
3332       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3333       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3334                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3335 
3336       if (ValVT == MVT::i1)
3337         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3338 
3339       InVals.push_back(ArgValue);
3340     } else {
3341       // Argument stored in memory.
3342       assert(VA.isMemLoc());
3343 
3344       unsigned ArgSize = VA.getLocVT().getStoreSize();
3345       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3346                                      isImmutable);
3347 
3348       // Create load nodes to retrieve arguments from the stack.
3349       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3350       InVals.push_back(
3351           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3352     }
3353   }
3354 
3355   // Assign locations to all of the incoming aggregate by value arguments.
3356   // Aggregates passed by value are stored in the local variable space of the
3357   // caller's stack frame, right above the parameter list area.
3358   SmallVector<CCValAssign, 16> ByValArgLocs;
3359   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3360                       ByValArgLocs, *DAG.getContext());
3361 
3362   // Reserve stack space for the allocations in CCInfo.
3363   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3364 
3365   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3366 
3367   // Area that is at least reserved in the caller of this function.
3368   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3369   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3370 
3371   // Set the size that is at least reserved in caller of this function.  Tail
3372   // call optimized function's reserved stack space needs to be aligned so that
3373   // taking the difference between two stack areas will result in an aligned
3374   // stack.
3375   MinReservedArea =
3376       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3377   FuncInfo->setMinReservedArea(MinReservedArea);
3378 
3379   SmallVector<SDValue, 8> MemOps;
3380 
3381   // If the function takes variable number of arguments, make a frame index for
3382   // the start of the first vararg value... for expansion of llvm.va_start.
3383   if (isVarArg) {
3384     static const MCPhysReg GPArgRegs[] = {
3385       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3386       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3387     };
3388     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3389 
3390     static const MCPhysReg FPArgRegs[] = {
3391       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3392       PPC::F8
3393     };
3394     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3395 
3396     if (useSoftFloat())
3397        NumFPArgRegs = 0;
3398 
3399     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3400     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3401 
3402     // Make room for NumGPArgRegs and NumFPArgRegs.
3403     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3404                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3405 
3406     FuncInfo->setVarArgsStackOffset(
3407       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3408                             CCInfo.getNextStackOffset(), true));
3409 
3410     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3411     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3412 
3413     // The fixed integer arguments of a variadic function are stored to the
3414     // VarArgsFrameIndex on the stack so that they may be loaded by
3415     // dereferencing the result of va_next.
3416     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3417       // Get an existing live-in vreg, or add a new one.
3418       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3419       if (!VReg)
3420         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3421 
3422       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3423       SDValue Store =
3424           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3425       MemOps.push_back(Store);
3426       // Increment the address by four for the next argument to store
3427       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3428       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3429     }
3430 
3431     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3432     // is set.
3433     // The double arguments are stored to the VarArgsFrameIndex
3434     // on the stack.
3435     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3436       // Get an existing live-in vreg, or add a new one.
3437       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3438       if (!VReg)
3439         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3440 
3441       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3442       SDValue Store =
3443           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3444       MemOps.push_back(Store);
3445       // Increment the address by eight for the next argument to store
3446       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3447                                          PtrVT);
3448       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3449     }
3450   }
3451 
3452   if (!MemOps.empty())
3453     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3454 
3455   return Chain;
3456 }
3457 
3458 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3459 // value to MVT::i64 and then truncate to the correct register size.
3460 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3461                                              EVT ObjectVT, SelectionDAG &DAG,
3462                                              SDValue ArgVal,
3463                                              const SDLoc &dl) const {
3464   if (Flags.isSExt())
3465     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3466                          DAG.getValueType(ObjectVT));
3467   else if (Flags.isZExt())
3468     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3469                          DAG.getValueType(ObjectVT));
3470 
3471   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3472 }
3473 
3474 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3475     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3476     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3477     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3478   // TODO: add description of PPC stack frame format, or at least some docs.
3479   //
3480   bool isELFv2ABI = Subtarget.isELFv2ABI();
3481   bool isLittleEndian = Subtarget.isLittleEndian();
3482   MachineFunction &MF = DAG.getMachineFunction();
3483   MachineFrameInfo &MFI = MF.getFrameInfo();
3484   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3485 
3486   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3487          "fastcc not supported on varargs functions");
3488 
3489   EVT PtrVT = getPointerTy(MF.getDataLayout());
3490   // Potential tail calls could cause overwriting of argument stack slots.
3491   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3492                        (CallConv == CallingConv::Fast));
3493   unsigned PtrByteSize = 8;
3494   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3495 
3496   static const MCPhysReg GPR[] = {
3497     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3498     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3499   };
3500   static const MCPhysReg VR[] = {
3501     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3502     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3503   };
3504 
3505   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3506   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3507   const unsigned Num_VR_Regs  = array_lengthof(VR);
3508   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3509 
3510   // Do a first pass over the arguments to determine whether the ABI
3511   // guarantees that our caller has allocated the parameter save area
3512   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3513   // in the ELFv2 ABI, it is true if this is a vararg function or if
3514   // any parameter is located in a stack slot.
3515 
3516   bool HasParameterArea = !isELFv2ABI || isVarArg;
3517   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3518   unsigned NumBytes = LinkageSize;
3519   unsigned AvailableFPRs = Num_FPR_Regs;
3520   unsigned AvailableVRs = Num_VR_Regs;
3521   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3522     if (Ins[i].Flags.isNest())
3523       continue;
3524 
3525     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3526                                PtrByteSize, LinkageSize, ParamAreaSize,
3527                                NumBytes, AvailableFPRs, AvailableVRs,
3528                                Subtarget.hasQPX()))
3529       HasParameterArea = true;
3530   }
3531 
3532   // Add DAG nodes to load the arguments or copy them out of registers.  On
3533   // entry to a function on PPC, the arguments start after the linkage area,
3534   // although the first ones are often in registers.
3535 
3536   unsigned ArgOffset = LinkageSize;
3537   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3538   unsigned &QFPR_idx = FPR_idx;
3539   SmallVector<SDValue, 8> MemOps;
3540   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3541   unsigned CurArgIdx = 0;
3542   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3543     SDValue ArgVal;
3544     bool needsLoad = false;
3545     EVT ObjectVT = Ins[ArgNo].VT;
3546     EVT OrigVT = Ins[ArgNo].ArgVT;
3547     unsigned ObjSize = ObjectVT.getStoreSize();
3548     unsigned ArgSize = ObjSize;
3549     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3550     if (Ins[ArgNo].isOrigArg()) {
3551       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3552       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3553     }
3554     // We re-align the argument offset for each argument, except when using the
3555     // fast calling convention, when we need to make sure we do that only when
3556     // we'll actually use a stack slot.
3557     unsigned CurArgOffset, Align;
3558     auto ComputeArgOffset = [&]() {
3559       /* Respect alignment of argument on the stack.  */
3560       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3561       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3562       CurArgOffset = ArgOffset;
3563     };
3564 
3565     if (CallConv != CallingConv::Fast) {
3566       ComputeArgOffset();
3567 
3568       /* Compute GPR index associated with argument offset.  */
3569       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3570       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3571     }
3572 
3573     // FIXME the codegen can be much improved in some cases.
3574     // We do not have to keep everything in memory.
3575     if (Flags.isByVal()) {
3576       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3577 
3578       if (CallConv == CallingConv::Fast)
3579         ComputeArgOffset();
3580 
3581       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3582       ObjSize = Flags.getByValSize();
3583       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3584       // Empty aggregate parameters do not take up registers.  Examples:
3585       //   struct { } a;
3586       //   union  { } b;
3587       //   int c[0];
3588       // etc.  However, we have to provide a place-holder in InVals, so
3589       // pretend we have an 8-byte item at the current address for that
3590       // purpose.
3591       if (!ObjSize) {
3592         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3593         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3594         InVals.push_back(FIN);
3595         continue;
3596       }
3597 
3598       // Create a stack object covering all stack doublewords occupied
3599       // by the argument.  If the argument is (fully or partially) on
3600       // the stack, or if the argument is fully in registers but the
3601       // caller has allocated the parameter save anyway, we can refer
3602       // directly to the caller's stack frame.  Otherwise, create a
3603       // local copy in our own frame.
3604       int FI;
3605       if (HasParameterArea ||
3606           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3607         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3608       else
3609         FI = MFI.CreateStackObject(ArgSize, Align, false);
3610       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3611 
3612       // Handle aggregates smaller than 8 bytes.
3613       if (ObjSize < PtrByteSize) {
3614         // The value of the object is its address, which differs from the
3615         // address of the enclosing doubleword on big-endian systems.
3616         SDValue Arg = FIN;
3617         if (!isLittleEndian) {
3618           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3619           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3620         }
3621         InVals.push_back(Arg);
3622 
3623         if (GPR_idx != Num_GPR_Regs) {
3624           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3625           FuncInfo->addLiveInAttr(VReg, Flags);
3626           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3627           SDValue Store;
3628 
3629           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3630             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3631                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3632             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3633                                       MachinePointerInfo(&*FuncArg), ObjType);
3634           } else {
3635             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3636             // store the whole register as-is to the parameter save area
3637             // slot.
3638             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3639                                  MachinePointerInfo(&*FuncArg));
3640           }
3641 
3642           MemOps.push_back(Store);
3643         }
3644         // Whether we copied from a register or not, advance the offset
3645         // into the parameter save area by a full doubleword.
3646         ArgOffset += PtrByteSize;
3647         continue;
3648       }
3649 
3650       // The value of the object is its address, which is the address of
3651       // its first stack doubleword.
3652       InVals.push_back(FIN);
3653 
3654       // Store whatever pieces of the object are in registers to memory.
3655       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3656         if (GPR_idx == Num_GPR_Regs)
3657           break;
3658 
3659         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3660         FuncInfo->addLiveInAttr(VReg, Flags);
3661         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3662         SDValue Addr = FIN;
3663         if (j) {
3664           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3665           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3666         }
3667         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3668                                      MachinePointerInfo(&*FuncArg, j));
3669         MemOps.push_back(Store);
3670         ++GPR_idx;
3671       }
3672       ArgOffset += ArgSize;
3673       continue;
3674     }
3675 
3676     switch (ObjectVT.getSimpleVT().SimpleTy) {
3677     default: llvm_unreachable("Unhandled argument type!");
3678     case MVT::i1:
3679     case MVT::i32:
3680     case MVT::i64:
3681       if (Flags.isNest()) {
3682         // The 'nest' parameter, if any, is passed in R11.
3683         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3684         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3685 
3686         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3687           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3688 
3689         break;
3690       }
3691 
3692       // These can be scalar arguments or elements of an integer array type
3693       // passed directly.  Clang may use those instead of "byval" aggregate
3694       // types to avoid forcing arguments to memory unnecessarily.
3695       if (GPR_idx != Num_GPR_Regs) {
3696         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3697         FuncInfo->addLiveInAttr(VReg, Flags);
3698         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3699 
3700         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3701           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3702           // value to MVT::i64 and then truncate to the correct register size.
3703           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3704       } else {
3705         if (CallConv == CallingConv::Fast)
3706           ComputeArgOffset();
3707 
3708         needsLoad = true;
3709         ArgSize = PtrByteSize;
3710       }
3711       if (CallConv != CallingConv::Fast || needsLoad)
3712         ArgOffset += 8;
3713       break;
3714 
3715     case MVT::f32:
3716     case MVT::f64:
3717       // These can be scalar arguments or elements of a float array type
3718       // passed directly.  The latter are used to implement ELFv2 homogenous
3719       // float aggregates.
3720       if (FPR_idx != Num_FPR_Regs) {
3721         unsigned VReg;
3722 
3723         if (ObjectVT == MVT::f32)
3724           VReg = MF.addLiveIn(FPR[FPR_idx],
3725                               Subtarget.hasP8Vector()
3726                                   ? &PPC::VSSRCRegClass
3727                                   : &PPC::F4RCRegClass);
3728         else
3729           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3730                                                 ? &PPC::VSFRCRegClass
3731                                                 : &PPC::F8RCRegClass);
3732 
3733         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3734         ++FPR_idx;
3735       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3736         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3737         // once we support fp <-> gpr moves.
3738 
3739         // This can only ever happen in the presence of f32 array types,
3740         // since otherwise we never run out of FPRs before running out
3741         // of GPRs.
3742         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3743         FuncInfo->addLiveInAttr(VReg, Flags);
3744         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3745 
3746         if (ObjectVT == MVT::f32) {
3747           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3748             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3749                                  DAG.getConstant(32, dl, MVT::i32));
3750           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3751         }
3752 
3753         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3754       } else {
3755         if (CallConv == CallingConv::Fast)
3756           ComputeArgOffset();
3757 
3758         needsLoad = true;
3759       }
3760 
3761       // When passing an array of floats, the array occupies consecutive
3762       // space in the argument area; only round up to the next doubleword
3763       // at the end of the array.  Otherwise, each float takes 8 bytes.
3764       if (CallConv != CallingConv::Fast || needsLoad) {
3765         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3766         ArgOffset += ArgSize;
3767         if (Flags.isInConsecutiveRegsLast())
3768           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3769       }
3770       break;
3771     case MVT::v4f32:
3772     case MVT::v4i32:
3773     case MVT::v8i16:
3774     case MVT::v16i8:
3775     case MVT::v2f64:
3776     case MVT::v2i64:
3777     case MVT::v1i128:
3778       if (!Subtarget.hasQPX()) {
3779       // These can be scalar arguments or elements of a vector array type
3780       // passed directly.  The latter are used to implement ELFv2 homogenous
3781       // vector aggregates.
3782       if (VR_idx != Num_VR_Regs) {
3783         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3784         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3785         ++VR_idx;
3786       } else {
3787         if (CallConv == CallingConv::Fast)
3788           ComputeArgOffset();
3789 
3790         needsLoad = true;
3791       }
3792       if (CallConv != CallingConv::Fast || needsLoad)
3793         ArgOffset += 16;
3794       break;
3795       } // not QPX
3796 
3797       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3798              "Invalid QPX parameter type");
3799       /* fall through */
3800 
3801     case MVT::v4f64:
3802     case MVT::v4i1:
3803       // QPX vectors are treated like their scalar floating-point subregisters
3804       // (except that they're larger).
3805       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3806       if (QFPR_idx != Num_QFPR_Regs) {
3807         const TargetRegisterClass *RC;
3808         switch (ObjectVT.getSimpleVT().SimpleTy) {
3809         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3810         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3811         default:         RC = &PPC::QBRCRegClass; break;
3812         }
3813 
3814         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3815         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3816         ++QFPR_idx;
3817       } else {
3818         if (CallConv == CallingConv::Fast)
3819           ComputeArgOffset();
3820         needsLoad = true;
3821       }
3822       if (CallConv != CallingConv::Fast || needsLoad)
3823         ArgOffset += Sz;
3824       break;
3825     }
3826 
3827     // We need to load the argument to a virtual register if we determined
3828     // above that we ran out of physical registers of the appropriate type.
3829     if (needsLoad) {
3830       if (ObjSize < ArgSize && !isLittleEndian)
3831         CurArgOffset += ArgSize - ObjSize;
3832       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3833       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3834       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3835     }
3836 
3837     InVals.push_back(ArgVal);
3838   }
3839 
3840   // Area that is at least reserved in the caller of this function.
3841   unsigned MinReservedArea;
3842   if (HasParameterArea)
3843     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3844   else
3845     MinReservedArea = LinkageSize;
3846 
3847   // Set the size that is at least reserved in caller of this function.  Tail
3848   // call optimized functions' reserved stack space needs to be aligned so that
3849   // taking the difference between two stack areas will result in an aligned
3850   // stack.
3851   MinReservedArea =
3852       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3853   FuncInfo->setMinReservedArea(MinReservedArea);
3854 
3855   // If the function takes variable number of arguments, make a frame index for
3856   // the start of the first vararg value... for expansion of llvm.va_start.
3857   if (isVarArg) {
3858     int Depth = ArgOffset;
3859 
3860     FuncInfo->setVarArgsFrameIndex(
3861       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3862     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3863 
3864     // If this function is vararg, store any remaining integer argument regs
3865     // to their spots on the stack so that they may be loaded by dereferencing
3866     // the result of va_next.
3867     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3868          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3869       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3870       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3871       SDValue Store =
3872           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3873       MemOps.push_back(Store);
3874       // Increment the address by four for the next argument to store
3875       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3876       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3877     }
3878   }
3879 
3880   if (!MemOps.empty())
3881     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3882 
3883   return Chain;
3884 }
3885 
3886 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3887     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3888     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3889     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3890   // TODO: add description of PPC stack frame format, or at least some docs.
3891   //
3892   MachineFunction &MF = DAG.getMachineFunction();
3893   MachineFrameInfo &MFI = MF.getFrameInfo();
3894   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3895 
3896   EVT PtrVT = getPointerTy(MF.getDataLayout());
3897   bool isPPC64 = PtrVT == MVT::i64;
3898   // Potential tail calls could cause overwriting of argument stack slots.
3899   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3900                        (CallConv == CallingConv::Fast));
3901   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3902   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3903   unsigned ArgOffset = LinkageSize;
3904   // Area that is at least reserved in caller of this function.
3905   unsigned MinReservedArea = ArgOffset;
3906 
3907   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3908     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3909     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3910   };
3911   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3912     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3913     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3914   };
3915   static const MCPhysReg VR[] = {
3916     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3917     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3918   };
3919 
3920   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3921   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3922   const unsigned Num_VR_Regs  = array_lengthof( VR);
3923 
3924   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3925 
3926   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3927 
3928   // In 32-bit non-varargs functions, the stack space for vectors is after the
3929   // stack space for non-vectors.  We do not use this space unless we have
3930   // too many vectors to fit in registers, something that only occurs in
3931   // constructed examples:), but we have to walk the arglist to figure
3932   // that out...for the pathological case, compute VecArgOffset as the
3933   // start of the vector parameter area.  Computing VecArgOffset is the
3934   // entire point of the following loop.
3935   unsigned VecArgOffset = ArgOffset;
3936   if (!isVarArg && !isPPC64) {
3937     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3938          ++ArgNo) {
3939       EVT ObjectVT = Ins[ArgNo].VT;
3940       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3941 
3942       if (Flags.isByVal()) {
3943         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3944         unsigned ObjSize = Flags.getByValSize();
3945         unsigned ArgSize =
3946                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3947         VecArgOffset += ArgSize;
3948         continue;
3949       }
3950 
3951       switch(ObjectVT.getSimpleVT().SimpleTy) {
3952       default: llvm_unreachable("Unhandled argument type!");
3953       case MVT::i1:
3954       case MVT::i32:
3955       case MVT::f32:
3956         VecArgOffset += 4;
3957         break;
3958       case MVT::i64:  // PPC64
3959       case MVT::f64:
3960         // FIXME: We are guaranteed to be !isPPC64 at this point.
3961         // Does MVT::i64 apply?
3962         VecArgOffset += 8;
3963         break;
3964       case MVT::v4f32:
3965       case MVT::v4i32:
3966       case MVT::v8i16:
3967       case MVT::v16i8:
3968         // Nothing to do, we're only looking at Nonvector args here.
3969         break;
3970       }
3971     }
3972   }
3973   // We've found where the vector parameter area in memory is.  Skip the
3974   // first 12 parameters; these don't use that memory.
3975   VecArgOffset = ((VecArgOffset+15)/16)*16;
3976   VecArgOffset += 12*16;
3977 
3978   // Add DAG nodes to load the arguments or copy them out of registers.  On
3979   // entry to a function on PPC, the arguments start after the linkage area,
3980   // although the first ones are often in registers.
3981 
3982   SmallVector<SDValue, 8> MemOps;
3983   unsigned nAltivecParamsAtEnd = 0;
3984   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3985   unsigned CurArgIdx = 0;
3986   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3987     SDValue ArgVal;
3988     bool needsLoad = false;
3989     EVT ObjectVT = Ins[ArgNo].VT;
3990     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3991     unsigned ArgSize = ObjSize;
3992     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3993     if (Ins[ArgNo].isOrigArg()) {
3994       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3995       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3996     }
3997     unsigned CurArgOffset = ArgOffset;
3998 
3999     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4000     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4001         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4002       if (isVarArg || isPPC64) {
4003         MinReservedArea = ((MinReservedArea+15)/16)*16;
4004         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4005                                                   Flags,
4006                                                   PtrByteSize);
4007       } else  nAltivecParamsAtEnd++;
4008     } else
4009       // Calculate min reserved area.
4010       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4011                                                 Flags,
4012                                                 PtrByteSize);
4013 
4014     // FIXME the codegen can be much improved in some cases.
4015     // We do not have to keep everything in memory.
4016     if (Flags.isByVal()) {
4017       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4018 
4019       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4020       ObjSize = Flags.getByValSize();
4021       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4022       // Objects of size 1 and 2 are right justified, everything else is
4023       // left justified.  This means the memory address is adjusted forwards.
4024       if (ObjSize==1 || ObjSize==2) {
4025         CurArgOffset = CurArgOffset + (4 - ObjSize);
4026       }
4027       // The value of the object is its address.
4028       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4029       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4030       InVals.push_back(FIN);
4031       if (ObjSize==1 || ObjSize==2) {
4032         if (GPR_idx != Num_GPR_Regs) {
4033           unsigned VReg;
4034           if (isPPC64)
4035             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4036           else
4037             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4038           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4039           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4040           SDValue Store =
4041               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4042                                 MachinePointerInfo(&*FuncArg), ObjType);
4043           MemOps.push_back(Store);
4044           ++GPR_idx;
4045         }
4046 
4047         ArgOffset += PtrByteSize;
4048 
4049         continue;
4050       }
4051       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4052         // Store whatever pieces of the object are in registers
4053         // to memory.  ArgOffset will be the address of the beginning
4054         // of the object.
4055         if (GPR_idx != Num_GPR_Regs) {
4056           unsigned VReg;
4057           if (isPPC64)
4058             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4059           else
4060             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4061           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4062           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4063           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4064           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4065                                        MachinePointerInfo(&*FuncArg, j));
4066           MemOps.push_back(Store);
4067           ++GPR_idx;
4068           ArgOffset += PtrByteSize;
4069         } else {
4070           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4071           break;
4072         }
4073       }
4074       continue;
4075     }
4076 
4077     switch (ObjectVT.getSimpleVT().SimpleTy) {
4078     default: llvm_unreachable("Unhandled argument type!");
4079     case MVT::i1:
4080     case MVT::i32:
4081       if (!isPPC64) {
4082         if (GPR_idx != Num_GPR_Regs) {
4083           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4084           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4085 
4086           if (ObjectVT == MVT::i1)
4087             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4088 
4089           ++GPR_idx;
4090         } else {
4091           needsLoad = true;
4092           ArgSize = PtrByteSize;
4093         }
4094         // All int arguments reserve stack space in the Darwin ABI.
4095         ArgOffset += PtrByteSize;
4096         break;
4097       }
4098       LLVM_FALLTHROUGH;
4099     case MVT::i64:  // PPC64
4100       if (GPR_idx != Num_GPR_Regs) {
4101         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4102         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4103 
4104         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4105           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4106           // value to MVT::i64 and then truncate to the correct register size.
4107           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4108 
4109         ++GPR_idx;
4110       } else {
4111         needsLoad = true;
4112         ArgSize = PtrByteSize;
4113       }
4114       // All int arguments reserve stack space in the Darwin ABI.
4115       ArgOffset += 8;
4116       break;
4117 
4118     case MVT::f32:
4119     case MVT::f64:
4120       // Every 4 bytes of argument space consumes one of the GPRs available for
4121       // argument passing.
4122       if (GPR_idx != Num_GPR_Regs) {
4123         ++GPR_idx;
4124         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4125           ++GPR_idx;
4126       }
4127       if (FPR_idx != Num_FPR_Regs) {
4128         unsigned VReg;
4129 
4130         if (ObjectVT == MVT::f32)
4131           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4132         else
4133           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4134 
4135         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4136         ++FPR_idx;
4137       } else {
4138         needsLoad = true;
4139       }
4140 
4141       // All FP arguments reserve stack space in the Darwin ABI.
4142       ArgOffset += isPPC64 ? 8 : ObjSize;
4143       break;
4144     case MVT::v4f32:
4145     case MVT::v4i32:
4146     case MVT::v8i16:
4147     case MVT::v16i8:
4148       // Note that vector arguments in registers don't reserve stack space,
4149       // except in varargs functions.
4150       if (VR_idx != Num_VR_Regs) {
4151         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4152         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4153         if (isVarArg) {
4154           while ((ArgOffset % 16) != 0) {
4155             ArgOffset += PtrByteSize;
4156             if (GPR_idx != Num_GPR_Regs)
4157               GPR_idx++;
4158           }
4159           ArgOffset += 16;
4160           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4161         }
4162         ++VR_idx;
4163       } else {
4164         if (!isVarArg && !isPPC64) {
4165           // Vectors go after all the nonvectors.
4166           CurArgOffset = VecArgOffset;
4167           VecArgOffset += 16;
4168         } else {
4169           // Vectors are aligned.
4170           ArgOffset = ((ArgOffset+15)/16)*16;
4171           CurArgOffset = ArgOffset;
4172           ArgOffset += 16;
4173         }
4174         needsLoad = true;
4175       }
4176       break;
4177     }
4178 
4179     // We need to load the argument to a virtual register if we determined above
4180     // that we ran out of physical registers of the appropriate type.
4181     if (needsLoad) {
4182       int FI = MFI.CreateFixedObject(ObjSize,
4183                                      CurArgOffset + (ArgSize - ObjSize),
4184                                      isImmutable);
4185       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4186       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4187     }
4188 
4189     InVals.push_back(ArgVal);
4190   }
4191 
4192   // Allow for Altivec parameters at the end, if needed.
4193   if (nAltivecParamsAtEnd) {
4194     MinReservedArea = ((MinReservedArea+15)/16)*16;
4195     MinReservedArea += 16*nAltivecParamsAtEnd;
4196   }
4197 
4198   // Area that is at least reserved in the caller of this function.
4199   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4200 
4201   // Set the size that is at least reserved in caller of this function.  Tail
4202   // call optimized functions' reserved stack space needs to be aligned so that
4203   // taking the difference between two stack areas will result in an aligned
4204   // stack.
4205   MinReservedArea =
4206       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4207   FuncInfo->setMinReservedArea(MinReservedArea);
4208 
4209   // If the function takes variable number of arguments, make a frame index for
4210   // the start of the first vararg value... for expansion of llvm.va_start.
4211   if (isVarArg) {
4212     int Depth = ArgOffset;
4213 
4214     FuncInfo->setVarArgsFrameIndex(
4215       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4216                             Depth, true));
4217     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4218 
4219     // If this function is vararg, store any remaining integer argument regs
4220     // to their spots on the stack so that they may be loaded by dereferencing
4221     // the result of va_next.
4222     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4223       unsigned VReg;
4224 
4225       if (isPPC64)
4226         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4227       else
4228         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4229 
4230       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4231       SDValue Store =
4232           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4233       MemOps.push_back(Store);
4234       // Increment the address by four for the next argument to store
4235       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4236       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4237     }
4238   }
4239 
4240   if (!MemOps.empty())
4241     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4242 
4243   return Chain;
4244 }
4245 
4246 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4247 /// adjusted to accommodate the arguments for the tailcall.
4248 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4249                                    unsigned ParamSize) {
4250 
4251   if (!isTailCall) return 0;
4252 
4253   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4254   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4255   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4256   // Remember only if the new adjustement is bigger.
4257   if (SPDiff < FI->getTailCallSPDelta())
4258     FI->setTailCallSPDelta(SPDiff);
4259 
4260   return SPDiff;
4261 }
4262 
4263 static bool isFunctionGlobalAddress(SDValue Callee);
4264 
4265 static bool
4266 callsShareTOCBase(const Function *Caller, SDValue Callee,
4267                     const TargetMachine &TM) {
4268   // If !G, Callee can be an external symbol.
4269   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4270   if (!G)
4271     return false;
4272 
4273   // The medium and large code models are expected to provide a sufficiently
4274   // large TOC to provide all data addressing needs of a module with a
4275   // single TOC. Since each module will be addressed with a single TOC then we
4276   // only need to check that caller and callee don't cross dso boundaries.
4277   if (CodeModel::Medium == TM.getCodeModel() ||
4278       CodeModel::Large == TM.getCodeModel())
4279     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4280 
4281   // Otherwise we need to ensure callee and caller are in the same section,
4282   // since the linker may allocate multiple TOCs, and we don't know which
4283   // sections will belong to the same TOC base.
4284 
4285   const GlobalValue *GV = G->getGlobal();
4286   if (!GV->isStrongDefinitionForLinker())
4287     return false;
4288 
4289   // Any explicitly-specified sections and section prefixes must also match.
4290   // Also, if we're using -ffunction-sections, then each function is always in
4291   // a different section (the same is true for COMDAT functions).
4292   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4293       GV->getSection() != Caller->getSection())
4294     return false;
4295   if (const auto *F = dyn_cast<Function>(GV)) {
4296     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4297       return false;
4298   }
4299 
4300   // If the callee might be interposed, then we can't assume the ultimate call
4301   // target will be in the same section. Even in cases where we can assume that
4302   // interposition won't happen, in any case where the linker might insert a
4303   // stub to allow for interposition, we must generate code as though
4304   // interposition might occur. To understand why this matters, consider a
4305   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4306   // in the same section, but a is in a different module (i.e. has a different
4307   // TOC base pointer). If the linker allows for interposition between b and c,
4308   // then it will generate a stub for the call edge between b and c which will
4309   // save the TOC pointer into the designated stack slot allocated by b. If we
4310   // return true here, and therefore allow a tail call between b and c, that
4311   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4312   // pointer into the stack slot allocated by a (where the a -> b stub saved
4313   // a's TOC base pointer). If we're not considering a tail call, but rather,
4314   // whether a nop is needed after the call instruction in b, because the linker
4315   // will insert a stub, it might complain about a missing nop if we omit it
4316   // (although many don't complain in this case).
4317   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4318     return false;
4319 
4320   return true;
4321 }
4322 
4323 static bool
4324 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4325                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4326   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4327 
4328   const unsigned PtrByteSize = 8;
4329   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4330 
4331   static const MCPhysReg GPR[] = {
4332     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4333     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4334   };
4335   static const MCPhysReg VR[] = {
4336     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4337     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4338   };
4339 
4340   const unsigned NumGPRs = array_lengthof(GPR);
4341   const unsigned NumFPRs = 13;
4342   const unsigned NumVRs = array_lengthof(VR);
4343   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4344 
4345   unsigned NumBytes = LinkageSize;
4346   unsigned AvailableFPRs = NumFPRs;
4347   unsigned AvailableVRs = NumVRs;
4348 
4349   for (const ISD::OutputArg& Param : Outs) {
4350     if (Param.Flags.isNest()) continue;
4351 
4352     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4353                                PtrByteSize, LinkageSize, ParamAreaSize,
4354                                NumBytes, AvailableFPRs, AvailableVRs,
4355                                Subtarget.hasQPX()))
4356       return true;
4357   }
4358   return false;
4359 }
4360 
4361 static bool
4362 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4363   if (CS.arg_size() != CallerFn->arg_size())
4364     return false;
4365 
4366   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4367   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4368   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4369 
4370   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4371     const Value* CalleeArg = *CalleeArgIter;
4372     const Value* CallerArg = &(*CallerArgIter);
4373     if (CalleeArg == CallerArg)
4374       continue;
4375 
4376     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4377     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4378     //      }
4379     // 1st argument of callee is undef and has the same type as caller.
4380     if (CalleeArg->getType() == CallerArg->getType() &&
4381         isa<UndefValue>(CalleeArg))
4382       continue;
4383 
4384     return false;
4385   }
4386 
4387   return true;
4388 }
4389 
4390 bool
4391 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4392                                     SDValue Callee,
4393                                     CallingConv::ID CalleeCC,
4394                                     ImmutableCallSite CS,
4395                                     bool isVarArg,
4396                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4397                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4398                                     SelectionDAG& DAG) const {
4399   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4400 
4401   if (DisableSCO && !TailCallOpt) return false;
4402 
4403   // Variadic argument functions are not supported.
4404   if (isVarArg) return false;
4405 
4406   MachineFunction &MF = DAG.getMachineFunction();
4407   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4408 
4409   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4410   // the same calling convention
4411   if (CallerCC != CalleeCC) return false;
4412 
4413   // SCO support C calling convention
4414   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4415     return false;
4416 
4417   // Caller contains any byval parameter is not supported.
4418   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4419     return false;
4420 
4421   // Callee contains any byval parameter is not supported, too.
4422   // Note: This is a quick work around, because in some cases, e.g.
4423   // caller's stack size > callee's stack size, we are still able to apply
4424   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4425   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4426     return false;
4427 
4428   // No TCO/SCO on indirect call because Caller have to restore its TOC
4429   if (!isFunctionGlobalAddress(Callee) &&
4430       !isa<ExternalSymbolSDNode>(Callee))
4431     return false;
4432 
4433   // If the caller and callee potentially have different TOC bases then we
4434   // cannot tail call since we need to restore the TOC pointer after the call.
4435   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4436   if (!callsShareTOCBase(MF.getFunction(), Callee, getTargetMachine()))
4437     return false;
4438 
4439   // TCO allows altering callee ABI, so we don't have to check further.
4440   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4441     return true;
4442 
4443   if (DisableSCO) return false;
4444 
4445   // If callee use the same argument list that caller is using, then we can
4446   // apply SCO on this case. If it is not, then we need to check if callee needs
4447   // stack for passing arguments.
4448   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4449       needStackSlotPassParameters(Subtarget, Outs)) {
4450     return false;
4451   }
4452 
4453   return true;
4454 }
4455 
4456 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4457 /// for tail call optimization. Targets which want to do tail call
4458 /// optimization should implement this function.
4459 bool
4460 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4461                                                      CallingConv::ID CalleeCC,
4462                                                      bool isVarArg,
4463                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4464                                                      SelectionDAG& DAG) const {
4465   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4466     return false;
4467 
4468   // Variable argument functions are not supported.
4469   if (isVarArg)
4470     return false;
4471 
4472   MachineFunction &MF = DAG.getMachineFunction();
4473   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4474   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4475     // Functions containing by val parameters are not supported.
4476     for (unsigned i = 0; i != Ins.size(); i++) {
4477        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4478        if (Flags.isByVal()) return false;
4479     }
4480 
4481     // Non-PIC/GOT tail calls are supported.
4482     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4483       return true;
4484 
4485     // At the moment we can only do local tail calls (in same module, hidden
4486     // or protected) if we are generating PIC.
4487     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4488       return G->getGlobal()->hasHiddenVisibility()
4489           || G->getGlobal()->hasProtectedVisibility();
4490   }
4491 
4492   return false;
4493 }
4494 
4495 /// isCallCompatibleAddress - Return the immediate to use if the specified
4496 /// 32-bit value is representable in the immediate field of a BxA instruction.
4497 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4498   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4499   if (!C) return nullptr;
4500 
4501   int Addr = C->getZExtValue();
4502   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4503       SignExtend32<26>(Addr) != Addr)
4504     return nullptr;  // Top 6 bits have to be sext of immediate.
4505 
4506   return DAG
4507       .getConstant(
4508           (int)C->getZExtValue() >> 2, SDLoc(Op),
4509           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4510       .getNode();
4511 }
4512 
4513 namespace {
4514 
4515 struct TailCallArgumentInfo {
4516   SDValue Arg;
4517   SDValue FrameIdxOp;
4518   int FrameIdx = 0;
4519 
4520   TailCallArgumentInfo() = default;
4521 };
4522 
4523 } // end anonymous namespace
4524 
4525 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4526 static void StoreTailCallArgumentsToStackSlot(
4527     SelectionDAG &DAG, SDValue Chain,
4528     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4529     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4530   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4531     SDValue Arg = TailCallArgs[i].Arg;
4532     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4533     int FI = TailCallArgs[i].FrameIdx;
4534     // Store relative to framepointer.
4535     MemOpChains.push_back(DAG.getStore(
4536         Chain, dl, Arg, FIN,
4537         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4538   }
4539 }
4540 
4541 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4542 /// the appropriate stack slot for the tail call optimized function call.
4543 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4544                                              SDValue OldRetAddr, SDValue OldFP,
4545                                              int SPDiff, const SDLoc &dl) {
4546   if (SPDiff) {
4547     // Calculate the new stack slot for the return address.
4548     MachineFunction &MF = DAG.getMachineFunction();
4549     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4550     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4551     bool isPPC64 = Subtarget.isPPC64();
4552     int SlotSize = isPPC64 ? 8 : 4;
4553     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4554     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4555                                                          NewRetAddrLoc, true);
4556     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4557     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4558     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4559                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4560 
4561     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4562     // slot as the FP is never overwritten.
4563     if (Subtarget.isDarwinABI()) {
4564       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4565       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4566                                                          true);
4567       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4568       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4569                            MachinePointerInfo::getFixedStack(
4570                                DAG.getMachineFunction(), NewFPIdx));
4571     }
4572   }
4573   return Chain;
4574 }
4575 
4576 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4577 /// the position of the argument.
4578 static void
4579 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4580                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4581                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4582   int Offset = ArgOffset + SPDiff;
4583   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4584   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4585   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4586   SDValue FIN = DAG.getFrameIndex(FI, VT);
4587   TailCallArgumentInfo Info;
4588   Info.Arg = Arg;
4589   Info.FrameIdxOp = FIN;
4590   Info.FrameIdx = FI;
4591   TailCallArguments.push_back(Info);
4592 }
4593 
4594 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4595 /// stack slot. Returns the chain as result and the loaded frame pointers in
4596 /// LROpOut/FPOpout. Used when tail calling.
4597 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4598     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4599     SDValue &FPOpOut, const SDLoc &dl) const {
4600   if (SPDiff) {
4601     // Load the LR and FP stack slot for later adjusting.
4602     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4603     LROpOut = getReturnAddrFrameIndex(DAG);
4604     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4605     Chain = SDValue(LROpOut.getNode(), 1);
4606 
4607     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4608     // slot as the FP is never overwritten.
4609     if (Subtarget.isDarwinABI()) {
4610       FPOpOut = getFramePointerFrameIndex(DAG);
4611       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4612       Chain = SDValue(FPOpOut.getNode(), 1);
4613     }
4614   }
4615   return Chain;
4616 }
4617 
4618 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4619 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4620 /// specified by the specific parameter attribute. The copy will be passed as
4621 /// a byval function parameter.
4622 /// Sometimes what we are copying is the end of a larger object, the part that
4623 /// does not fit in registers.
4624 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4625                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4626                                          SelectionDAG &DAG, const SDLoc &dl) {
4627   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4628   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4629                        false, false, false, MachinePointerInfo(),
4630                        MachinePointerInfo());
4631 }
4632 
4633 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4634 /// tail calls.
4635 static void LowerMemOpCallTo(
4636     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4637     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4638     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4639     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4640   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4641   if (!isTailCall) {
4642     if (isVector) {
4643       SDValue StackPtr;
4644       if (isPPC64)
4645         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4646       else
4647         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4648       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4649                            DAG.getConstant(ArgOffset, dl, PtrVT));
4650     }
4651     MemOpChains.push_back(
4652         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4653     // Calculate and remember argument location.
4654   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4655                                   TailCallArguments);
4656 }
4657 
4658 static void
4659 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4660                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4661                 SDValue FPOp,
4662                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4663   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4664   // might overwrite each other in case of tail call optimization.
4665   SmallVector<SDValue, 8> MemOpChains2;
4666   // Do not flag preceding copytoreg stuff together with the following stuff.
4667   InFlag = SDValue();
4668   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4669                                     MemOpChains2, dl);
4670   if (!MemOpChains2.empty())
4671     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4672 
4673   // Store the return address to the appropriate stack slot.
4674   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4675 
4676   // Emit callseq_end just before tailcall node.
4677   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4678                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4679   InFlag = Chain.getValue(1);
4680 }
4681 
4682 // Is this global address that of a function that can be called by name? (as
4683 // opposed to something that must hold a descriptor for an indirect call).
4684 static bool isFunctionGlobalAddress(SDValue Callee) {
4685   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4686     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4687         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4688       return false;
4689 
4690     return G->getGlobal()->getValueType()->isFunctionTy();
4691   }
4692 
4693   return false;
4694 }
4695 
4696 static unsigned
4697 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4698             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4699             bool isPatchPoint, bool hasNest,
4700             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4701             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4702             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4703   bool isPPC64 = Subtarget.isPPC64();
4704   bool isSVR4ABI = Subtarget.isSVR4ABI();
4705   bool isELFv2ABI = Subtarget.isELFv2ABI();
4706 
4707   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4708   NodeTys.push_back(MVT::Other);   // Returns a chain
4709   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4710 
4711   unsigned CallOpc = PPCISD::CALL;
4712 
4713   bool needIndirectCall = true;
4714   if (!isSVR4ABI || !isPPC64)
4715     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4716       // If this is an absolute destination address, use the munged value.
4717       Callee = SDValue(Dest, 0);
4718       needIndirectCall = false;
4719     }
4720 
4721   // PC-relative references to external symbols should go through $stub, unless
4722   // we're building with the leopard linker or later, which automatically
4723   // synthesizes these stubs.
4724   const TargetMachine &TM = DAG.getTarget();
4725   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4726   const GlobalValue *GV = nullptr;
4727   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4728     GV = G->getGlobal();
4729   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4730   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4731 
4732   if (isFunctionGlobalAddress(Callee)) {
4733     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4734     // A call to a TLS address is actually an indirect call to a
4735     // thread-specific pointer.
4736     unsigned OpFlags = 0;
4737     if (UsePlt)
4738       OpFlags = PPCII::MO_PLT;
4739 
4740     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4741     // every direct call is) turn it into a TargetGlobalAddress /
4742     // TargetExternalSymbol node so that legalize doesn't hack it.
4743     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4744                                         Callee.getValueType(), 0, OpFlags);
4745     needIndirectCall = false;
4746   }
4747 
4748   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4749     unsigned char OpFlags = 0;
4750 
4751     if (UsePlt)
4752       OpFlags = PPCII::MO_PLT;
4753 
4754     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4755                                          OpFlags);
4756     needIndirectCall = false;
4757   }
4758 
4759   if (isPatchPoint) {
4760     // We'll form an invalid direct call when lowering a patchpoint; the full
4761     // sequence for an indirect call is complicated, and many of the
4762     // instructions introduced might have side effects (and, thus, can't be
4763     // removed later). The call itself will be removed as soon as the
4764     // argument/return lowering is complete, so the fact that it has the wrong
4765     // kind of operands should not really matter.
4766     needIndirectCall = false;
4767   }
4768 
4769   if (needIndirectCall) {
4770     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4771     // to do the call, we can't use PPCISD::CALL.
4772     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4773 
4774     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4775       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4776       // entry point, but to the function descriptor (the function entry point
4777       // address is part of the function descriptor though).
4778       // The function descriptor is a three doubleword structure with the
4779       // following fields: function entry point, TOC base address and
4780       // environment pointer.
4781       // Thus for a call through a function pointer, the following actions need
4782       // to be performed:
4783       //   1. Save the TOC of the caller in the TOC save area of its stack
4784       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4785       //   2. Load the address of the function entry point from the function
4786       //      descriptor.
4787       //   3. Load the TOC of the callee from the function descriptor into r2.
4788       //   4. Load the environment pointer from the function descriptor into
4789       //      r11.
4790       //   5. Branch to the function entry point address.
4791       //   6. On return of the callee, the TOC of the caller needs to be
4792       //      restored (this is done in FinishCall()).
4793       //
4794       // The loads are scheduled at the beginning of the call sequence, and the
4795       // register copies are flagged together to ensure that no other
4796       // operations can be scheduled in between. E.g. without flagging the
4797       // copies together, a TOC access in the caller could be scheduled between
4798       // the assignment of the callee TOC and the branch to the callee, which
4799       // results in the TOC access going through the TOC of the callee instead
4800       // of going through the TOC of the caller, which leads to incorrect code.
4801 
4802       // Load the address of the function entry point from the function
4803       // descriptor.
4804       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4805       if (LDChain.getValueType() == MVT::Glue)
4806         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4807 
4808       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4809                           ? (MachineMemOperand::MODereferenceable |
4810                              MachineMemOperand::MOInvariant)
4811                           : MachineMemOperand::MONone;
4812 
4813       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4814       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4815                                         /* Alignment = */ 8, MMOFlags);
4816 
4817       // Load environment pointer into r11.
4818       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4819       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4820       SDValue LoadEnvPtr =
4821           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4822                       /* Alignment = */ 8, MMOFlags);
4823 
4824       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4825       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4826       SDValue TOCPtr =
4827           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4828                       /* Alignment = */ 8, MMOFlags);
4829 
4830       setUsesTOCBasePtr(DAG);
4831       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4832                                         InFlag);
4833       Chain = TOCVal.getValue(0);
4834       InFlag = TOCVal.getValue(1);
4835 
4836       // If the function call has an explicit 'nest' parameter, it takes the
4837       // place of the environment pointer.
4838       if (!hasNest) {
4839         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4840                                           InFlag);
4841 
4842         Chain = EnvVal.getValue(0);
4843         InFlag = EnvVal.getValue(1);
4844       }
4845 
4846       MTCTROps[0] = Chain;
4847       MTCTROps[1] = LoadFuncPtr;
4848       MTCTROps[2] = InFlag;
4849     }
4850 
4851     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4852                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4853     InFlag = Chain.getValue(1);
4854 
4855     NodeTys.clear();
4856     NodeTys.push_back(MVT::Other);
4857     NodeTys.push_back(MVT::Glue);
4858     Ops.push_back(Chain);
4859     CallOpc = PPCISD::BCTRL;
4860     Callee.setNode(nullptr);
4861     // Add use of X11 (holding environment pointer)
4862     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4863       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4864     // Add CTR register as callee so a bctr can be emitted later.
4865     if (isTailCall)
4866       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4867   }
4868 
4869   // If this is a direct call, pass the chain and the callee.
4870   if (Callee.getNode()) {
4871     Ops.push_back(Chain);
4872     Ops.push_back(Callee);
4873   }
4874   // If this is a tail call add stack pointer delta.
4875   if (isTailCall)
4876     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4877 
4878   // Add argument registers to the end of the list so that they are known live
4879   // into the call.
4880   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4881     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4882                                   RegsToPass[i].second.getValueType()));
4883 
4884   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4885   // into the call.
4886   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4887     setUsesTOCBasePtr(DAG);
4888     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4889   }
4890 
4891   return CallOpc;
4892 }
4893 
4894 SDValue PPCTargetLowering::LowerCallResult(
4895     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4896     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4897     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4898   SmallVector<CCValAssign, 16> RVLocs;
4899   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4900                     *DAG.getContext());
4901   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4902 
4903   // Copy all of the result registers out of their specified physreg.
4904   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4905     CCValAssign &VA = RVLocs[i];
4906     assert(VA.isRegLoc() && "Can only return in registers!");
4907 
4908     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4909                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4910     Chain = Val.getValue(1);
4911     InFlag = Val.getValue(2);
4912 
4913     switch (VA.getLocInfo()) {
4914     default: llvm_unreachable("Unknown loc info!");
4915     case CCValAssign::Full: break;
4916     case CCValAssign::AExt:
4917       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4918       break;
4919     case CCValAssign::ZExt:
4920       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4921                         DAG.getValueType(VA.getValVT()));
4922       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4923       break;
4924     case CCValAssign::SExt:
4925       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4926                         DAG.getValueType(VA.getValVT()));
4927       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4928       break;
4929     }
4930 
4931     InVals.push_back(Val);
4932   }
4933 
4934   return Chain;
4935 }
4936 
4937 SDValue PPCTargetLowering::FinishCall(
4938     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4939     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4940     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4941     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4942     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4943     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
4944   std::vector<EVT> NodeTys;
4945   SmallVector<SDValue, 8> Ops;
4946   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4947                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4948                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4949 
4950   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4951   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4952     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4953 
4954   // When performing tail call optimization the callee pops its arguments off
4955   // the stack. Account for this here so these bytes can be pushed back on in
4956   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4957   int BytesCalleePops =
4958     (CallConv == CallingConv::Fast &&
4959      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4960 
4961   // Add a register mask operand representing the call-preserved registers.
4962   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4963   const uint32_t *Mask =
4964       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4965   assert(Mask && "Missing call preserved mask for calling convention");
4966   Ops.push_back(DAG.getRegisterMask(Mask));
4967 
4968   if (InFlag.getNode())
4969     Ops.push_back(InFlag);
4970 
4971   // Emit tail call.
4972   if (isTailCall) {
4973     assert(((Callee.getOpcode() == ISD::Register &&
4974              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4975             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4976             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4977             isa<ConstantSDNode>(Callee)) &&
4978     "Expecting an global address, external symbol, absolute value or register");
4979 
4980     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4981     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4982   }
4983 
4984   // Add a NOP immediately after the branch instruction when using the 64-bit
4985   // SVR4 ABI. At link time, if caller and callee are in a different module and
4986   // thus have a different TOC, the call will be replaced with a call to a stub
4987   // function which saves the current TOC, loads the TOC of the callee and
4988   // branches to the callee. The NOP will be replaced with a load instruction
4989   // which restores the TOC of the caller from the TOC save slot of the current
4990   // stack frame. If caller and callee belong to the same module (and have the
4991   // same TOC), the NOP will remain unchanged.
4992 
4993   MachineFunction &MF = DAG.getMachineFunction();
4994   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4995       !isPatchPoint) {
4996     if (CallOpc == PPCISD::BCTRL) {
4997       // This is a call through a function pointer.
4998       // Restore the caller TOC from the save area into R2.
4999       // See PrepareCall() for more information about calls through function
5000       // pointers in the 64-bit SVR4 ABI.
5001       // We are using a target-specific load with r2 hard coded, because the
5002       // result of a target-independent load would never go directly into r2,
5003       // since r2 is a reserved register (which prevents the register allocator
5004       // from allocating it), resulting in an additional register being
5005       // allocated and an unnecessary move instruction being generated.
5006       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5007 
5008       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5009       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5010       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5011       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5012       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5013 
5014       // The address needs to go after the chain input but before the flag (or
5015       // any other variadic arguments).
5016       Ops.insert(std::next(Ops.begin()), AddTOC);
5017     } else if (CallOpc == PPCISD::CALL &&
5018       !callsShareTOCBase(MF.getFunction(), Callee, DAG.getTarget())) {
5019       // Otherwise insert NOP for non-local calls.
5020       CallOpc = PPCISD::CALL_NOP;
5021     }
5022   }
5023 
5024   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5025   InFlag = Chain.getValue(1);
5026 
5027   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5028                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5029                              InFlag, dl);
5030   if (!Ins.empty())
5031     InFlag = Chain.getValue(1);
5032 
5033   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5034                          Ins, dl, DAG, InVals);
5035 }
5036 
5037 SDValue
5038 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5039                              SmallVectorImpl<SDValue> &InVals) const {
5040   SelectionDAG &DAG                     = CLI.DAG;
5041   SDLoc &dl                             = CLI.DL;
5042   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5043   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5044   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5045   SDValue Chain                         = CLI.Chain;
5046   SDValue Callee                        = CLI.Callee;
5047   bool &isTailCall                      = CLI.IsTailCall;
5048   CallingConv::ID CallConv              = CLI.CallConv;
5049   bool isVarArg                         = CLI.IsVarArg;
5050   bool isPatchPoint                     = CLI.IsPatchPoint;
5051   ImmutableCallSite CS                  = CLI.CS;
5052 
5053   if (isTailCall) {
5054     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5055       isTailCall = false;
5056     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5057       isTailCall =
5058         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5059                                                  isVarArg, Outs, Ins, DAG);
5060     else
5061       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5062                                                      Ins, DAG);
5063     if (isTailCall) {
5064       ++NumTailCalls;
5065       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5066         ++NumSiblingCalls;
5067 
5068       assert(isa<GlobalAddressSDNode>(Callee) &&
5069              "Callee should be an llvm::Function object.");
5070       DEBUG(
5071         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5072         const unsigned Width = 80 - strlen("TCO caller: ")
5073                                   - strlen(", callee linkage: 0, 0");
5074         dbgs() << "TCO caller: "
5075                << left_justify(DAG.getMachineFunction().getName(), Width)
5076                << ", callee linkage: "
5077                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
5078       );
5079     }
5080   }
5081 
5082   if (!isTailCall && CS && CS.isMustTailCall())
5083     report_fatal_error("failed to perform tail call elimination on a call "
5084                        "site marked musttail");
5085 
5086   // When long calls (i.e. indirect calls) are always used, calls are always
5087   // made via function pointer. If we have a function name, first translate it
5088   // into a pointer.
5089   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5090       !isTailCall)
5091     Callee = LowerGlobalAddress(Callee, DAG);
5092 
5093   if (Subtarget.isSVR4ABI()) {
5094     if (Subtarget.isPPC64())
5095       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5096                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5097                               dl, DAG, InVals, CS);
5098     else
5099       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5100                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5101                               dl, DAG, InVals, CS);
5102   }
5103 
5104   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5105                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5106                           dl, DAG, InVals, CS);
5107 }
5108 
5109 SDValue PPCTargetLowering::LowerCall_32SVR4(
5110     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5111     bool isTailCall, bool isPatchPoint,
5112     const SmallVectorImpl<ISD::OutputArg> &Outs,
5113     const SmallVectorImpl<SDValue> &OutVals,
5114     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5115     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5116     ImmutableCallSite CS) const {
5117   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5118   // of the 32-bit SVR4 ABI stack frame layout.
5119 
5120   assert((CallConv == CallingConv::C ||
5121           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5122 
5123   unsigned PtrByteSize = 4;
5124 
5125   MachineFunction &MF = DAG.getMachineFunction();
5126 
5127   // Mark this function as potentially containing a function that contains a
5128   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5129   // and restoring the callers stack pointer in this functions epilog. This is
5130   // done because by tail calling the called function might overwrite the value
5131   // in this function's (MF) stack pointer stack slot 0(SP).
5132   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5133       CallConv == CallingConv::Fast)
5134     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5135 
5136   // Count how many bytes are to be pushed on the stack, including the linkage
5137   // area, parameter list area and the part of the local variable space which
5138   // contains copies of aggregates which are passed by value.
5139 
5140   // Assign locations to all of the outgoing arguments.
5141   SmallVector<CCValAssign, 16> ArgLocs;
5142   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5143 
5144   // Reserve space for the linkage area on the stack.
5145   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5146                        PtrByteSize);
5147   if (useSoftFloat())
5148     CCInfo.PreAnalyzeCallOperands(Outs);
5149 
5150   if (isVarArg) {
5151     // Handle fixed and variable vector arguments differently.
5152     // Fixed vector arguments go into registers as long as registers are
5153     // available. Variable vector arguments always go into memory.
5154     unsigned NumArgs = Outs.size();
5155 
5156     for (unsigned i = 0; i != NumArgs; ++i) {
5157       MVT ArgVT = Outs[i].VT;
5158       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5159       bool Result;
5160 
5161       if (Outs[i].IsFixed) {
5162         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5163                                CCInfo);
5164       } else {
5165         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5166                                       ArgFlags, CCInfo);
5167       }
5168 
5169       if (Result) {
5170 #ifndef NDEBUG
5171         errs() << "Call operand #" << i << " has unhandled type "
5172              << EVT(ArgVT).getEVTString() << "\n";
5173 #endif
5174         llvm_unreachable(nullptr);
5175       }
5176     }
5177   } else {
5178     // All arguments are treated the same.
5179     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5180   }
5181   CCInfo.clearWasPPCF128();
5182 
5183   // Assign locations to all of the outgoing aggregate by value arguments.
5184   SmallVector<CCValAssign, 16> ByValArgLocs;
5185   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5186 
5187   // Reserve stack space for the allocations in CCInfo.
5188   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5189 
5190   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5191 
5192   // Size of the linkage area, parameter list area and the part of the local
5193   // space variable where copies of aggregates which are passed by value are
5194   // stored.
5195   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5196 
5197   // Calculate by how many bytes the stack has to be adjusted in case of tail
5198   // call optimization.
5199   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5200 
5201   // Adjust the stack pointer for the new arguments...
5202   // These operations are automatically eliminated by the prolog/epilog pass
5203   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5204   SDValue CallSeqStart = Chain;
5205 
5206   // Load the return address and frame pointer so it can be moved somewhere else
5207   // later.
5208   SDValue LROp, FPOp;
5209   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5210 
5211   // Set up a copy of the stack pointer for use loading and storing any
5212   // arguments that may not fit in the registers available for argument
5213   // passing.
5214   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5215 
5216   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5217   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5218   SmallVector<SDValue, 8> MemOpChains;
5219 
5220   bool seenFloatArg = false;
5221   // Walk the register/memloc assignments, inserting copies/loads.
5222   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5223        i != e;
5224        ++i) {
5225     CCValAssign &VA = ArgLocs[i];
5226     SDValue Arg = OutVals[i];
5227     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5228 
5229     if (Flags.isByVal()) {
5230       // Argument is an aggregate which is passed by value, thus we need to
5231       // create a copy of it in the local variable space of the current stack
5232       // frame (which is the stack frame of the caller) and pass the address of
5233       // this copy to the callee.
5234       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5235       CCValAssign &ByValVA = ByValArgLocs[j++];
5236       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5237 
5238       // Memory reserved in the local variable space of the callers stack frame.
5239       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5240 
5241       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5242       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5243                            StackPtr, PtrOff);
5244 
5245       // Create a copy of the argument in the local area of the current
5246       // stack frame.
5247       SDValue MemcpyCall =
5248         CreateCopyOfByValArgument(Arg, PtrOff,
5249                                   CallSeqStart.getNode()->getOperand(0),
5250                                   Flags, DAG, dl);
5251 
5252       // This must go outside the CALLSEQ_START..END.
5253       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5254                                                      SDLoc(MemcpyCall));
5255       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5256                              NewCallSeqStart.getNode());
5257       Chain = CallSeqStart = NewCallSeqStart;
5258 
5259       // Pass the address of the aggregate copy on the stack either in a
5260       // physical register or in the parameter list area of the current stack
5261       // frame to the callee.
5262       Arg = PtrOff;
5263     }
5264 
5265     if (VA.isRegLoc()) {
5266       if (Arg.getValueType() == MVT::i1)
5267         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5268 
5269       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5270       // Put argument in a physical register.
5271       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5272     } else {
5273       // Put argument in the parameter list area of the current stack frame.
5274       assert(VA.isMemLoc());
5275       unsigned LocMemOffset = VA.getLocMemOffset();
5276 
5277       if (!isTailCall) {
5278         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5279         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5280                              StackPtr, PtrOff);
5281 
5282         MemOpChains.push_back(
5283             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5284       } else {
5285         // Calculate and remember argument location.
5286         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5287                                  TailCallArguments);
5288       }
5289     }
5290   }
5291 
5292   if (!MemOpChains.empty())
5293     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5294 
5295   // Build a sequence of copy-to-reg nodes chained together with token chain
5296   // and flag operands which copy the outgoing args into the appropriate regs.
5297   SDValue InFlag;
5298   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5299     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5300                              RegsToPass[i].second, InFlag);
5301     InFlag = Chain.getValue(1);
5302   }
5303 
5304   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5305   // registers.
5306   if (isVarArg) {
5307     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5308     SDValue Ops[] = { Chain, InFlag };
5309 
5310     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5311                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5312 
5313     InFlag = Chain.getValue(1);
5314   }
5315 
5316   if (isTailCall)
5317     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5318                     TailCallArguments);
5319 
5320   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5321                     /* unused except on PPC64 ELFv1 */ false, DAG,
5322                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5323                     NumBytes, Ins, InVals, CS);
5324 }
5325 
5326 // Copy an argument into memory, being careful to do this outside the
5327 // call sequence for the call to which the argument belongs.
5328 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5329     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5330     SelectionDAG &DAG, const SDLoc &dl) const {
5331   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5332                         CallSeqStart.getNode()->getOperand(0),
5333                         Flags, DAG, dl);
5334   // The MEMCPY must go outside the CALLSEQ_START..END.
5335   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5336   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5337                                                  SDLoc(MemcpyCall));
5338   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5339                          NewCallSeqStart.getNode());
5340   return NewCallSeqStart;
5341 }
5342 
5343 SDValue PPCTargetLowering::LowerCall_64SVR4(
5344     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5345     bool isTailCall, bool isPatchPoint,
5346     const SmallVectorImpl<ISD::OutputArg> &Outs,
5347     const SmallVectorImpl<SDValue> &OutVals,
5348     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5349     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5350     ImmutableCallSite CS) const {
5351   bool isELFv2ABI = Subtarget.isELFv2ABI();
5352   bool isLittleEndian = Subtarget.isLittleEndian();
5353   unsigned NumOps = Outs.size();
5354   bool hasNest = false;
5355   bool IsSibCall = false;
5356 
5357   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5358   unsigned PtrByteSize = 8;
5359 
5360   MachineFunction &MF = DAG.getMachineFunction();
5361 
5362   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5363     IsSibCall = true;
5364 
5365   // Mark this function as potentially containing a function that contains a
5366   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5367   // and restoring the callers stack pointer in this functions epilog. This is
5368   // done because by tail calling the called function might overwrite the value
5369   // in this function's (MF) stack pointer stack slot 0(SP).
5370   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5371       CallConv == CallingConv::Fast)
5372     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5373 
5374   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5375          "fastcc not supported on varargs functions");
5376 
5377   // Count how many bytes are to be pushed on the stack, including the linkage
5378   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5379   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5380   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5381   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5382   unsigned NumBytes = LinkageSize;
5383   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5384   unsigned &QFPR_idx = FPR_idx;
5385 
5386   static const MCPhysReg GPR[] = {
5387     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5388     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5389   };
5390   static const MCPhysReg VR[] = {
5391     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5392     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5393   };
5394 
5395   const unsigned NumGPRs = array_lengthof(GPR);
5396   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5397   const unsigned NumVRs  = array_lengthof(VR);
5398   const unsigned NumQFPRs = NumFPRs;
5399 
5400   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5401   // can be passed to the callee in registers.
5402   // For the fast calling convention, there is another check below.
5403   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5404   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5405   if (!HasParameterArea) {
5406     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5407     unsigned AvailableFPRs = NumFPRs;
5408     unsigned AvailableVRs = NumVRs;
5409     unsigned NumBytesTmp = NumBytes;
5410     for (unsigned i = 0; i != NumOps; ++i) {
5411       if (Outs[i].Flags.isNest()) continue;
5412       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5413                                 PtrByteSize, LinkageSize, ParamAreaSize,
5414                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5415                                 Subtarget.hasQPX()))
5416         HasParameterArea = true;
5417     }
5418   }
5419 
5420   // When using the fast calling convention, we don't provide backing for
5421   // arguments that will be in registers.
5422   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5423 
5424   // Add up all the space actually used.
5425   for (unsigned i = 0; i != NumOps; ++i) {
5426     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5427     EVT ArgVT = Outs[i].VT;
5428     EVT OrigVT = Outs[i].ArgVT;
5429 
5430     if (Flags.isNest())
5431       continue;
5432 
5433     if (CallConv == CallingConv::Fast) {
5434       if (Flags.isByVal())
5435         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5436       else
5437         switch (ArgVT.getSimpleVT().SimpleTy) {
5438         default: llvm_unreachable("Unexpected ValueType for argument!");
5439         case MVT::i1:
5440         case MVT::i32:
5441         case MVT::i64:
5442           if (++NumGPRsUsed <= NumGPRs)
5443             continue;
5444           break;
5445         case MVT::v4i32:
5446         case MVT::v8i16:
5447         case MVT::v16i8:
5448         case MVT::v2f64:
5449         case MVT::v2i64:
5450         case MVT::v1i128:
5451           if (++NumVRsUsed <= NumVRs)
5452             continue;
5453           break;
5454         case MVT::v4f32:
5455           // When using QPX, this is handled like a FP register, otherwise, it
5456           // is an Altivec register.
5457           if (Subtarget.hasQPX()) {
5458             if (++NumFPRsUsed <= NumFPRs)
5459               continue;
5460           } else {
5461             if (++NumVRsUsed <= NumVRs)
5462               continue;
5463           }
5464           break;
5465         case MVT::f32:
5466         case MVT::f64:
5467         case MVT::v4f64: // QPX
5468         case MVT::v4i1:  // QPX
5469           if (++NumFPRsUsed <= NumFPRs)
5470             continue;
5471           break;
5472         }
5473     }
5474 
5475     /* Respect alignment of argument on the stack.  */
5476     unsigned Align =
5477       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5478     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5479 
5480     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5481     if (Flags.isInConsecutiveRegsLast())
5482       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5483   }
5484 
5485   unsigned NumBytesActuallyUsed = NumBytes;
5486 
5487   // In the old ELFv1 ABI,
5488   // the prolog code of the callee may store up to 8 GPR argument registers to
5489   // the stack, allowing va_start to index over them in memory if its varargs.
5490   // Because we cannot tell if this is needed on the caller side, we have to
5491   // conservatively assume that it is needed.  As such, make sure we have at
5492   // least enough stack space for the caller to store the 8 GPRs.
5493   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5494   // really requires memory operands, e.g. a vararg function.
5495   if (HasParameterArea)
5496     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5497   else
5498     NumBytes = LinkageSize;
5499 
5500   // Tail call needs the stack to be aligned.
5501   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5502       CallConv == CallingConv::Fast)
5503     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5504 
5505   int SPDiff = 0;
5506 
5507   // Calculate by how many bytes the stack has to be adjusted in case of tail
5508   // call optimization.
5509   if (!IsSibCall)
5510     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5511 
5512   // To protect arguments on the stack from being clobbered in a tail call,
5513   // force all the loads to happen before doing any other lowering.
5514   if (isTailCall)
5515     Chain = DAG.getStackArgumentTokenFactor(Chain);
5516 
5517   // Adjust the stack pointer for the new arguments...
5518   // These operations are automatically eliminated by the prolog/epilog pass
5519   if (!IsSibCall)
5520     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5521   SDValue CallSeqStart = Chain;
5522 
5523   // Load the return address and frame pointer so it can be move somewhere else
5524   // later.
5525   SDValue LROp, FPOp;
5526   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5527 
5528   // Set up a copy of the stack pointer for use loading and storing any
5529   // arguments that may not fit in the registers available for argument
5530   // passing.
5531   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5532 
5533   // Figure out which arguments are going to go in registers, and which in
5534   // memory.  Also, if this is a vararg function, floating point operations
5535   // must be stored to our stack, and loaded into integer regs as well, if
5536   // any integer regs are available for argument passing.
5537   unsigned ArgOffset = LinkageSize;
5538 
5539   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5540   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5541 
5542   SmallVector<SDValue, 8> MemOpChains;
5543   for (unsigned i = 0; i != NumOps; ++i) {
5544     SDValue Arg = OutVals[i];
5545     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5546     EVT ArgVT = Outs[i].VT;
5547     EVT OrigVT = Outs[i].ArgVT;
5548 
5549     // PtrOff will be used to store the current argument to the stack if a
5550     // register cannot be found for it.
5551     SDValue PtrOff;
5552 
5553     // We re-align the argument offset for each argument, except when using the
5554     // fast calling convention, when we need to make sure we do that only when
5555     // we'll actually use a stack slot.
5556     auto ComputePtrOff = [&]() {
5557       /* Respect alignment of argument on the stack.  */
5558       unsigned Align =
5559         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5560       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5561 
5562       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5563 
5564       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5565     };
5566 
5567     if (CallConv != CallingConv::Fast) {
5568       ComputePtrOff();
5569 
5570       /* Compute GPR index associated with argument offset.  */
5571       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5572       GPR_idx = std::min(GPR_idx, NumGPRs);
5573     }
5574 
5575     // Promote integers to 64-bit values.
5576     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5577       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5578       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5579       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5580     }
5581 
5582     // FIXME memcpy is used way more than necessary.  Correctness first.
5583     // Note: "by value" is code for passing a structure by value, not
5584     // basic types.
5585     if (Flags.isByVal()) {
5586       // Note: Size includes alignment padding, so
5587       //   struct x { short a; char b; }
5588       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5589       // These are the proper values we need for right-justifying the
5590       // aggregate in a parameter register.
5591       unsigned Size = Flags.getByValSize();
5592 
5593       // An empty aggregate parameter takes up no storage and no
5594       // registers.
5595       if (Size == 0)
5596         continue;
5597 
5598       if (CallConv == CallingConv::Fast)
5599         ComputePtrOff();
5600 
5601       // All aggregates smaller than 8 bytes must be passed right-justified.
5602       if (Size==1 || Size==2 || Size==4) {
5603         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5604         if (GPR_idx != NumGPRs) {
5605           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5606                                         MachinePointerInfo(), VT);
5607           MemOpChains.push_back(Load.getValue(1));
5608           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5609 
5610           ArgOffset += PtrByteSize;
5611           continue;
5612         }
5613       }
5614 
5615       if (GPR_idx == NumGPRs && Size < 8) {
5616         SDValue AddPtr = PtrOff;
5617         if (!isLittleEndian) {
5618           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5619                                           PtrOff.getValueType());
5620           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5621         }
5622         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5623                                                           CallSeqStart,
5624                                                           Flags, DAG, dl);
5625         ArgOffset += PtrByteSize;
5626         continue;
5627       }
5628       // Copy entire object into memory.  There are cases where gcc-generated
5629       // code assumes it is there, even if it could be put entirely into
5630       // registers.  (This is not what the doc says.)
5631 
5632       // FIXME: The above statement is likely due to a misunderstanding of the
5633       // documents.  All arguments must be copied into the parameter area BY
5634       // THE CALLEE in the event that the callee takes the address of any
5635       // formal argument.  That has not yet been implemented.  However, it is
5636       // reasonable to use the stack area as a staging area for the register
5637       // load.
5638 
5639       // Skip this for small aggregates, as we will use the same slot for a
5640       // right-justified copy, below.
5641       if (Size >= 8)
5642         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5643                                                           CallSeqStart,
5644                                                           Flags, DAG, dl);
5645 
5646       // When a register is available, pass a small aggregate right-justified.
5647       if (Size < 8 && GPR_idx != NumGPRs) {
5648         // The easiest way to get this right-justified in a register
5649         // is to copy the structure into the rightmost portion of a
5650         // local variable slot, then load the whole slot into the
5651         // register.
5652         // FIXME: The memcpy seems to produce pretty awful code for
5653         // small aggregates, particularly for packed ones.
5654         // FIXME: It would be preferable to use the slot in the
5655         // parameter save area instead of a new local variable.
5656         SDValue AddPtr = PtrOff;
5657         if (!isLittleEndian) {
5658           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5659           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5660         }
5661         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5662                                                           CallSeqStart,
5663                                                           Flags, DAG, dl);
5664 
5665         // Load the slot into the register.
5666         SDValue Load =
5667             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5668         MemOpChains.push_back(Load.getValue(1));
5669         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5670 
5671         // Done with this argument.
5672         ArgOffset += PtrByteSize;
5673         continue;
5674       }
5675 
5676       // For aggregates larger than PtrByteSize, copy the pieces of the
5677       // object that fit into registers from the parameter save area.
5678       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5679         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5680         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5681         if (GPR_idx != NumGPRs) {
5682           SDValue Load =
5683               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5684           MemOpChains.push_back(Load.getValue(1));
5685           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5686           ArgOffset += PtrByteSize;
5687         } else {
5688           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5689           break;
5690         }
5691       }
5692       continue;
5693     }
5694 
5695     switch (Arg.getSimpleValueType().SimpleTy) {
5696     default: llvm_unreachable("Unexpected ValueType for argument!");
5697     case MVT::i1:
5698     case MVT::i32:
5699     case MVT::i64:
5700       if (Flags.isNest()) {
5701         // The 'nest' parameter, if any, is passed in R11.
5702         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5703         hasNest = true;
5704         break;
5705       }
5706 
5707       // These can be scalar arguments or elements of an integer array type
5708       // passed directly.  Clang may use those instead of "byval" aggregate
5709       // types to avoid forcing arguments to memory unnecessarily.
5710       if (GPR_idx != NumGPRs) {
5711         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5712       } else {
5713         if (CallConv == CallingConv::Fast)
5714           ComputePtrOff();
5715 
5716         assert(HasParameterArea &&
5717                "Parameter area must exist to pass an argument in memory.");
5718         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5719                          true, isTailCall, false, MemOpChains,
5720                          TailCallArguments, dl);
5721         if (CallConv == CallingConv::Fast)
5722           ArgOffset += PtrByteSize;
5723       }
5724       if (CallConv != CallingConv::Fast)
5725         ArgOffset += PtrByteSize;
5726       break;
5727     case MVT::f32:
5728     case MVT::f64: {
5729       // These can be scalar arguments or elements of a float array type
5730       // passed directly.  The latter are used to implement ELFv2 homogenous
5731       // float aggregates.
5732 
5733       // Named arguments go into FPRs first, and once they overflow, the
5734       // remaining arguments go into GPRs and then the parameter save area.
5735       // Unnamed arguments for vararg functions always go to GPRs and
5736       // then the parameter save area.  For now, put all arguments to vararg
5737       // routines always in both locations (FPR *and* GPR or stack slot).
5738       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5739       bool NeededLoad = false;
5740 
5741       // First load the argument into the next available FPR.
5742       if (FPR_idx != NumFPRs)
5743         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5744 
5745       // Next, load the argument into GPR or stack slot if needed.
5746       if (!NeedGPROrStack)
5747         ;
5748       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5749         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5750         // once we support fp <-> gpr moves.
5751 
5752         // In the non-vararg case, this can only ever happen in the
5753         // presence of f32 array types, since otherwise we never run
5754         // out of FPRs before running out of GPRs.
5755         SDValue ArgVal;
5756 
5757         // Double values are always passed in a single GPR.
5758         if (Arg.getValueType() != MVT::f32) {
5759           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5760 
5761         // Non-array float values are extended and passed in a GPR.
5762         } else if (!Flags.isInConsecutiveRegs()) {
5763           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5764           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5765 
5766         // If we have an array of floats, we collect every odd element
5767         // together with its predecessor into one GPR.
5768         } else if (ArgOffset % PtrByteSize != 0) {
5769           SDValue Lo, Hi;
5770           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5771           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5772           if (!isLittleEndian)
5773             std::swap(Lo, Hi);
5774           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5775 
5776         // The final element, if even, goes into the first half of a GPR.
5777         } else if (Flags.isInConsecutiveRegsLast()) {
5778           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5779           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5780           if (!isLittleEndian)
5781             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5782                                  DAG.getConstant(32, dl, MVT::i32));
5783 
5784         // Non-final even elements are skipped; they will be handled
5785         // together the with subsequent argument on the next go-around.
5786         } else
5787           ArgVal = SDValue();
5788 
5789         if (ArgVal.getNode())
5790           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5791       } else {
5792         if (CallConv == CallingConv::Fast)
5793           ComputePtrOff();
5794 
5795         // Single-precision floating-point values are mapped to the
5796         // second (rightmost) word of the stack doubleword.
5797         if (Arg.getValueType() == MVT::f32 &&
5798             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5799           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5800           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5801         }
5802 
5803         assert(HasParameterArea &&
5804                "Parameter area must exist to pass an argument in memory.");
5805         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5806                          true, isTailCall, false, MemOpChains,
5807                          TailCallArguments, dl);
5808 
5809         NeededLoad = true;
5810       }
5811       // When passing an array of floats, the array occupies consecutive
5812       // space in the argument area; only round up to the next doubleword
5813       // at the end of the array.  Otherwise, each float takes 8 bytes.
5814       if (CallConv != CallingConv::Fast || NeededLoad) {
5815         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5816                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5817         if (Flags.isInConsecutiveRegsLast())
5818           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5819       }
5820       break;
5821     }
5822     case MVT::v4f32:
5823     case MVT::v4i32:
5824     case MVT::v8i16:
5825     case MVT::v16i8:
5826     case MVT::v2f64:
5827     case MVT::v2i64:
5828     case MVT::v1i128:
5829       if (!Subtarget.hasQPX()) {
5830       // These can be scalar arguments or elements of a vector array type
5831       // passed directly.  The latter are used to implement ELFv2 homogenous
5832       // vector aggregates.
5833 
5834       // For a varargs call, named arguments go into VRs or on the stack as
5835       // usual; unnamed arguments always go to the stack or the corresponding
5836       // GPRs when within range.  For now, we always put the value in both
5837       // locations (or even all three).
5838       if (isVarArg) {
5839         assert(HasParameterArea &&
5840                "Parameter area must exist if we have a varargs call.");
5841         // We could elide this store in the case where the object fits
5842         // entirely in R registers.  Maybe later.
5843         SDValue Store =
5844             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5845         MemOpChains.push_back(Store);
5846         if (VR_idx != NumVRs) {
5847           SDValue Load =
5848               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5849           MemOpChains.push_back(Load.getValue(1));
5850           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5851         }
5852         ArgOffset += 16;
5853         for (unsigned i=0; i<16; i+=PtrByteSize) {
5854           if (GPR_idx == NumGPRs)
5855             break;
5856           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5857                                    DAG.getConstant(i, dl, PtrVT));
5858           SDValue Load =
5859               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5860           MemOpChains.push_back(Load.getValue(1));
5861           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5862         }
5863         break;
5864       }
5865 
5866       // Non-varargs Altivec params go into VRs or on the stack.
5867       if (VR_idx != NumVRs) {
5868         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5869       } else {
5870         if (CallConv == CallingConv::Fast)
5871           ComputePtrOff();
5872 
5873         assert(HasParameterArea &&
5874                "Parameter area must exist to pass an argument in memory.");
5875         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5876                          true, isTailCall, true, MemOpChains,
5877                          TailCallArguments, dl);
5878         if (CallConv == CallingConv::Fast)
5879           ArgOffset += 16;
5880       }
5881 
5882       if (CallConv != CallingConv::Fast)
5883         ArgOffset += 16;
5884       break;
5885       } // not QPX
5886 
5887       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5888              "Invalid QPX parameter type");
5889 
5890       /* fall through */
5891     case MVT::v4f64:
5892     case MVT::v4i1: {
5893       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5894       if (isVarArg) {
5895         assert(HasParameterArea &&
5896                "Parameter area must exist if we have a varargs call.");
5897         // We could elide this store in the case where the object fits
5898         // entirely in R registers.  Maybe later.
5899         SDValue Store =
5900             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5901         MemOpChains.push_back(Store);
5902         if (QFPR_idx != NumQFPRs) {
5903           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5904                                      PtrOff, MachinePointerInfo());
5905           MemOpChains.push_back(Load.getValue(1));
5906           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5907         }
5908         ArgOffset += (IsF32 ? 16 : 32);
5909         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5910           if (GPR_idx == NumGPRs)
5911             break;
5912           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5913                                    DAG.getConstant(i, dl, PtrVT));
5914           SDValue Load =
5915               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5916           MemOpChains.push_back(Load.getValue(1));
5917           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5918         }
5919         break;
5920       }
5921 
5922       // Non-varargs QPX params go into registers or on the stack.
5923       if (QFPR_idx != NumQFPRs) {
5924         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5925       } else {
5926         if (CallConv == CallingConv::Fast)
5927           ComputePtrOff();
5928 
5929         assert(HasParameterArea &&
5930                "Parameter area must exist to pass an argument in memory.");
5931         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5932                          true, isTailCall, true, MemOpChains,
5933                          TailCallArguments, dl);
5934         if (CallConv == CallingConv::Fast)
5935           ArgOffset += (IsF32 ? 16 : 32);
5936       }
5937 
5938       if (CallConv != CallingConv::Fast)
5939         ArgOffset += (IsF32 ? 16 : 32);
5940       break;
5941       }
5942     }
5943   }
5944 
5945   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5946          "mismatch in size of parameter area");
5947   (void)NumBytesActuallyUsed;
5948 
5949   if (!MemOpChains.empty())
5950     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5951 
5952   // Check if this is an indirect call (MTCTR/BCTRL).
5953   // See PrepareCall() for more information about calls through function
5954   // pointers in the 64-bit SVR4 ABI.
5955   if (!isTailCall && !isPatchPoint &&
5956       !isFunctionGlobalAddress(Callee) &&
5957       !isa<ExternalSymbolSDNode>(Callee)) {
5958     // Load r2 into a virtual register and store it to the TOC save area.
5959     setUsesTOCBasePtr(DAG);
5960     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5961     // TOC save area offset.
5962     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5963     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5964     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5965     Chain = DAG.getStore(
5966         Val.getValue(1), dl, Val, AddPtr,
5967         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5968     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5969     // This does not mean the MTCTR instruction must use R12; it's easier
5970     // to model this as an extra parameter, so do that.
5971     if (isELFv2ABI && !isPatchPoint)
5972       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5973   }
5974 
5975   // Build a sequence of copy-to-reg nodes chained together with token chain
5976   // and flag operands which copy the outgoing args into the appropriate regs.
5977   SDValue InFlag;
5978   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5979     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5980                              RegsToPass[i].second, InFlag);
5981     InFlag = Chain.getValue(1);
5982   }
5983 
5984   if (isTailCall && !IsSibCall)
5985     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5986                     TailCallArguments);
5987 
5988   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5989                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5990                     SPDiff, NumBytes, Ins, InVals, CS);
5991 }
5992 
5993 SDValue PPCTargetLowering::LowerCall_Darwin(
5994     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5995     bool isTailCall, bool isPatchPoint,
5996     const SmallVectorImpl<ISD::OutputArg> &Outs,
5997     const SmallVectorImpl<SDValue> &OutVals,
5998     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5999     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6000     ImmutableCallSite CS) const {
6001   unsigned NumOps = Outs.size();
6002 
6003   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6004   bool isPPC64 = PtrVT == MVT::i64;
6005   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6006 
6007   MachineFunction &MF = DAG.getMachineFunction();
6008 
6009   // Mark this function as potentially containing a function that contains a
6010   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6011   // and restoring the callers stack pointer in this functions epilog. This is
6012   // done because by tail calling the called function might overwrite the value
6013   // in this function's (MF) stack pointer stack slot 0(SP).
6014   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6015       CallConv == CallingConv::Fast)
6016     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6017 
6018   // Count how many bytes are to be pushed on the stack, including the linkage
6019   // area, and parameter passing area.  We start with 24/48 bytes, which is
6020   // prereserved space for [SP][CR][LR][3 x unused].
6021   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6022   unsigned NumBytes = LinkageSize;
6023 
6024   // Add up all the space actually used.
6025   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6026   // they all go in registers, but we must reserve stack space for them for
6027   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6028   // assigned stack space in order, with padding so Altivec parameters are
6029   // 16-byte aligned.
6030   unsigned nAltivecParamsAtEnd = 0;
6031   for (unsigned i = 0; i != NumOps; ++i) {
6032     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6033     EVT ArgVT = Outs[i].VT;
6034     // Varargs Altivec parameters are padded to a 16 byte boundary.
6035     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6036         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6037         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6038       if (!isVarArg && !isPPC64) {
6039         // Non-varargs Altivec parameters go after all the non-Altivec
6040         // parameters; handle those later so we know how much padding we need.
6041         nAltivecParamsAtEnd++;
6042         continue;
6043       }
6044       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6045       NumBytes = ((NumBytes+15)/16)*16;
6046     }
6047     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6048   }
6049 
6050   // Allow for Altivec parameters at the end, if needed.
6051   if (nAltivecParamsAtEnd) {
6052     NumBytes = ((NumBytes+15)/16)*16;
6053     NumBytes += 16*nAltivecParamsAtEnd;
6054   }
6055 
6056   // The prolog code of the callee may store up to 8 GPR argument registers to
6057   // the stack, allowing va_start to index over them in memory if its varargs.
6058   // Because we cannot tell if this is needed on the caller side, we have to
6059   // conservatively assume that it is needed.  As such, make sure we have at
6060   // least enough stack space for the caller to store the 8 GPRs.
6061   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6062 
6063   // Tail call needs the stack to be aligned.
6064   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6065       CallConv == CallingConv::Fast)
6066     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6067 
6068   // Calculate by how many bytes the stack has to be adjusted in case of tail
6069   // call optimization.
6070   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6071 
6072   // To protect arguments on the stack from being clobbered in a tail call,
6073   // force all the loads to happen before doing any other lowering.
6074   if (isTailCall)
6075     Chain = DAG.getStackArgumentTokenFactor(Chain);
6076 
6077   // Adjust the stack pointer for the new arguments...
6078   // These operations are automatically eliminated by the prolog/epilog pass
6079   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6080   SDValue CallSeqStart = Chain;
6081 
6082   // Load the return address and frame pointer so it can be move somewhere else
6083   // later.
6084   SDValue LROp, FPOp;
6085   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6086 
6087   // Set up a copy of the stack pointer for use loading and storing any
6088   // arguments that may not fit in the registers available for argument
6089   // passing.
6090   SDValue StackPtr;
6091   if (isPPC64)
6092     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6093   else
6094     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6095 
6096   // Figure out which arguments are going to go in registers, and which in
6097   // memory.  Also, if this is a vararg function, floating point operations
6098   // must be stored to our stack, and loaded into integer regs as well, if
6099   // any integer regs are available for argument passing.
6100   unsigned ArgOffset = LinkageSize;
6101   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6102 
6103   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6104     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6105     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6106   };
6107   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6108     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6109     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6110   };
6111   static const MCPhysReg VR[] = {
6112     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6113     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6114   };
6115   const unsigned NumGPRs = array_lengthof(GPR_32);
6116   const unsigned NumFPRs = 13;
6117   const unsigned NumVRs  = array_lengthof(VR);
6118 
6119   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6120 
6121   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6122   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6123 
6124   SmallVector<SDValue, 8> MemOpChains;
6125   for (unsigned i = 0; i != NumOps; ++i) {
6126     SDValue Arg = OutVals[i];
6127     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6128 
6129     // PtrOff will be used to store the current argument to the stack if a
6130     // register cannot be found for it.
6131     SDValue PtrOff;
6132 
6133     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6134 
6135     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6136 
6137     // On PPC64, promote integers to 64-bit values.
6138     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6139       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6140       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6141       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6142     }
6143 
6144     // FIXME memcpy is used way more than necessary.  Correctness first.
6145     // Note: "by value" is code for passing a structure by value, not
6146     // basic types.
6147     if (Flags.isByVal()) {
6148       unsigned Size = Flags.getByValSize();
6149       // Very small objects are passed right-justified.  Everything else is
6150       // passed left-justified.
6151       if (Size==1 || Size==2) {
6152         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6153         if (GPR_idx != NumGPRs) {
6154           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6155                                         MachinePointerInfo(), VT);
6156           MemOpChains.push_back(Load.getValue(1));
6157           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6158 
6159           ArgOffset += PtrByteSize;
6160         } else {
6161           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6162                                           PtrOff.getValueType());
6163           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6164           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6165                                                             CallSeqStart,
6166                                                             Flags, DAG, dl);
6167           ArgOffset += PtrByteSize;
6168         }
6169         continue;
6170       }
6171       // Copy entire object into memory.  There are cases where gcc-generated
6172       // code assumes it is there, even if it could be put entirely into
6173       // registers.  (This is not what the doc says.)
6174       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6175                                                         CallSeqStart,
6176                                                         Flags, DAG, dl);
6177 
6178       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6179       // copy the pieces of the object that fit into registers from the
6180       // parameter save area.
6181       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6182         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6183         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6184         if (GPR_idx != NumGPRs) {
6185           SDValue Load =
6186               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6187           MemOpChains.push_back(Load.getValue(1));
6188           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6189           ArgOffset += PtrByteSize;
6190         } else {
6191           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6192           break;
6193         }
6194       }
6195       continue;
6196     }
6197 
6198     switch (Arg.getSimpleValueType().SimpleTy) {
6199     default: llvm_unreachable("Unexpected ValueType for argument!");
6200     case MVT::i1:
6201     case MVT::i32:
6202     case MVT::i64:
6203       if (GPR_idx != NumGPRs) {
6204         if (Arg.getValueType() == MVT::i1)
6205           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6206 
6207         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6208       } else {
6209         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6210                          isPPC64, isTailCall, false, MemOpChains,
6211                          TailCallArguments, dl);
6212       }
6213       ArgOffset += PtrByteSize;
6214       break;
6215     case MVT::f32:
6216     case MVT::f64:
6217       if (FPR_idx != NumFPRs) {
6218         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6219 
6220         if (isVarArg) {
6221           SDValue Store =
6222               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6223           MemOpChains.push_back(Store);
6224 
6225           // Float varargs are always shadowed in available integer registers
6226           if (GPR_idx != NumGPRs) {
6227             SDValue Load =
6228                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6229             MemOpChains.push_back(Load.getValue(1));
6230             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6231           }
6232           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6233             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6234             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6235             SDValue Load =
6236                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6237             MemOpChains.push_back(Load.getValue(1));
6238             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6239           }
6240         } else {
6241           // If we have any FPRs remaining, we may also have GPRs remaining.
6242           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6243           // GPRs.
6244           if (GPR_idx != NumGPRs)
6245             ++GPR_idx;
6246           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6247               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6248             ++GPR_idx;
6249         }
6250       } else
6251         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6252                          isPPC64, isTailCall, false, MemOpChains,
6253                          TailCallArguments, dl);
6254       if (isPPC64)
6255         ArgOffset += 8;
6256       else
6257         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6258       break;
6259     case MVT::v4f32:
6260     case MVT::v4i32:
6261     case MVT::v8i16:
6262     case MVT::v16i8:
6263       if (isVarArg) {
6264         // These go aligned on the stack, or in the corresponding R registers
6265         // when within range.  The Darwin PPC ABI doc claims they also go in
6266         // V registers; in fact gcc does this only for arguments that are
6267         // prototyped, not for those that match the ...  We do it for all
6268         // arguments, seems to work.
6269         while (ArgOffset % 16 !=0) {
6270           ArgOffset += PtrByteSize;
6271           if (GPR_idx != NumGPRs)
6272             GPR_idx++;
6273         }
6274         // We could elide this store in the case where the object fits
6275         // entirely in R registers.  Maybe later.
6276         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6277                              DAG.getConstant(ArgOffset, dl, PtrVT));
6278         SDValue Store =
6279             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6280         MemOpChains.push_back(Store);
6281         if (VR_idx != NumVRs) {
6282           SDValue Load =
6283               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6284           MemOpChains.push_back(Load.getValue(1));
6285           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6286         }
6287         ArgOffset += 16;
6288         for (unsigned i=0; i<16; i+=PtrByteSize) {
6289           if (GPR_idx == NumGPRs)
6290             break;
6291           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6292                                    DAG.getConstant(i, dl, PtrVT));
6293           SDValue Load =
6294               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6295           MemOpChains.push_back(Load.getValue(1));
6296           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6297         }
6298         break;
6299       }
6300 
6301       // Non-varargs Altivec params generally go in registers, but have
6302       // stack space allocated at the end.
6303       if (VR_idx != NumVRs) {
6304         // Doesn't have GPR space allocated.
6305         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6306       } else if (nAltivecParamsAtEnd==0) {
6307         // We are emitting Altivec params in order.
6308         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6309                          isPPC64, isTailCall, true, MemOpChains,
6310                          TailCallArguments, dl);
6311         ArgOffset += 16;
6312       }
6313       break;
6314     }
6315   }
6316   // If all Altivec parameters fit in registers, as they usually do,
6317   // they get stack space following the non-Altivec parameters.  We
6318   // don't track this here because nobody below needs it.
6319   // If there are more Altivec parameters than fit in registers emit
6320   // the stores here.
6321   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6322     unsigned j = 0;
6323     // Offset is aligned; skip 1st 12 params which go in V registers.
6324     ArgOffset = ((ArgOffset+15)/16)*16;
6325     ArgOffset += 12*16;
6326     for (unsigned i = 0; i != NumOps; ++i) {
6327       SDValue Arg = OutVals[i];
6328       EVT ArgType = Outs[i].VT;
6329       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6330           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6331         if (++j > NumVRs) {
6332           SDValue PtrOff;
6333           // We are emitting Altivec params in order.
6334           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6335                            isPPC64, isTailCall, true, MemOpChains,
6336                            TailCallArguments, dl);
6337           ArgOffset += 16;
6338         }
6339       }
6340     }
6341   }
6342 
6343   if (!MemOpChains.empty())
6344     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6345 
6346   // On Darwin, R12 must contain the address of an indirect callee.  This does
6347   // not mean the MTCTR instruction must use R12; it's easier to model this as
6348   // an extra parameter, so do that.
6349   if (!isTailCall &&
6350       !isFunctionGlobalAddress(Callee) &&
6351       !isa<ExternalSymbolSDNode>(Callee) &&
6352       !isBLACompatibleAddress(Callee, DAG))
6353     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6354                                                    PPC::R12), Callee));
6355 
6356   // Build a sequence of copy-to-reg nodes chained together with token chain
6357   // and flag operands which copy the outgoing args into the appropriate regs.
6358   SDValue InFlag;
6359   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6360     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6361                              RegsToPass[i].second, InFlag);
6362     InFlag = Chain.getValue(1);
6363   }
6364 
6365   if (isTailCall)
6366     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6367                     TailCallArguments);
6368 
6369   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6370                     /* unused except on PPC64 ELFv1 */ false, DAG,
6371                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6372                     NumBytes, Ins, InVals, CS);
6373 }
6374 
6375 bool
6376 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6377                                   MachineFunction &MF, bool isVarArg,
6378                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6379                                   LLVMContext &Context) const {
6380   SmallVector<CCValAssign, 16> RVLocs;
6381   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6382   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6383 }
6384 
6385 SDValue
6386 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6387                                bool isVarArg,
6388                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6389                                const SmallVectorImpl<SDValue> &OutVals,
6390                                const SDLoc &dl, SelectionDAG &DAG) const {
6391   SmallVector<CCValAssign, 16> RVLocs;
6392   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6393                  *DAG.getContext());
6394   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6395 
6396   SDValue Flag;
6397   SmallVector<SDValue, 4> RetOps(1, Chain);
6398 
6399   // Copy the result values into the output registers.
6400   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6401     CCValAssign &VA = RVLocs[i];
6402     assert(VA.isRegLoc() && "Can only return in registers!");
6403 
6404     SDValue Arg = OutVals[i];
6405 
6406     switch (VA.getLocInfo()) {
6407     default: llvm_unreachable("Unknown loc info!");
6408     case CCValAssign::Full: break;
6409     case CCValAssign::AExt:
6410       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6411       break;
6412     case CCValAssign::ZExt:
6413       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6414       break;
6415     case CCValAssign::SExt:
6416       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6417       break;
6418     }
6419 
6420     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6421     Flag = Chain.getValue(1);
6422     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6423   }
6424 
6425   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6426   const MCPhysReg *I =
6427     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6428   if (I) {
6429     for (; *I; ++I) {
6430 
6431       if (PPC::G8RCRegClass.contains(*I))
6432         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6433       else if (PPC::F8RCRegClass.contains(*I))
6434         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6435       else if (PPC::CRRCRegClass.contains(*I))
6436         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6437       else if (PPC::VRRCRegClass.contains(*I))
6438         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6439       else
6440         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6441     }
6442   }
6443 
6444   RetOps[0] = Chain;  // Update chain.
6445 
6446   // Add the flag if we have it.
6447   if (Flag.getNode())
6448     RetOps.push_back(Flag);
6449 
6450   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6451 }
6452 
6453 SDValue
6454 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6455                                                 SelectionDAG &DAG) const {
6456   SDLoc dl(Op);
6457 
6458   // Get the correct type for integers.
6459   EVT IntVT = Op.getValueType();
6460 
6461   // Get the inputs.
6462   SDValue Chain = Op.getOperand(0);
6463   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6464   // Build a DYNAREAOFFSET node.
6465   SDValue Ops[2] = {Chain, FPSIdx};
6466   SDVTList VTs = DAG.getVTList(IntVT);
6467   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6468 }
6469 
6470 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6471                                              SelectionDAG &DAG) const {
6472   // When we pop the dynamic allocation we need to restore the SP link.
6473   SDLoc dl(Op);
6474 
6475   // Get the correct type for pointers.
6476   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6477 
6478   // Construct the stack pointer operand.
6479   bool isPPC64 = Subtarget.isPPC64();
6480   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6481   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6482 
6483   // Get the operands for the STACKRESTORE.
6484   SDValue Chain = Op.getOperand(0);
6485   SDValue SaveSP = Op.getOperand(1);
6486 
6487   // Load the old link SP.
6488   SDValue LoadLinkSP =
6489       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6490 
6491   // Restore the stack pointer.
6492   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6493 
6494   // Store the old link SP.
6495   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6496 }
6497 
6498 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6499   MachineFunction &MF = DAG.getMachineFunction();
6500   bool isPPC64 = Subtarget.isPPC64();
6501   EVT PtrVT = getPointerTy(MF.getDataLayout());
6502 
6503   // Get current frame pointer save index.  The users of this index will be
6504   // primarily DYNALLOC instructions.
6505   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6506   int RASI = FI->getReturnAddrSaveIndex();
6507 
6508   // If the frame pointer save index hasn't been defined yet.
6509   if (!RASI) {
6510     // Find out what the fix offset of the frame pointer save area.
6511     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6512     // Allocate the frame index for frame pointer save area.
6513     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6514     // Save the result.
6515     FI->setReturnAddrSaveIndex(RASI);
6516   }
6517   return DAG.getFrameIndex(RASI, PtrVT);
6518 }
6519 
6520 SDValue
6521 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6522   MachineFunction &MF = DAG.getMachineFunction();
6523   bool isPPC64 = Subtarget.isPPC64();
6524   EVT PtrVT = getPointerTy(MF.getDataLayout());
6525 
6526   // Get current frame pointer save index.  The users of this index will be
6527   // primarily DYNALLOC instructions.
6528   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6529   int FPSI = FI->getFramePointerSaveIndex();
6530 
6531   // If the frame pointer save index hasn't been defined yet.
6532   if (!FPSI) {
6533     // Find out what the fix offset of the frame pointer save area.
6534     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6535     // Allocate the frame index for frame pointer save area.
6536     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6537     // Save the result.
6538     FI->setFramePointerSaveIndex(FPSI);
6539   }
6540   return DAG.getFrameIndex(FPSI, PtrVT);
6541 }
6542 
6543 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6544                                                    SelectionDAG &DAG) const {
6545   // Get the inputs.
6546   SDValue Chain = Op.getOperand(0);
6547   SDValue Size  = Op.getOperand(1);
6548   SDLoc dl(Op);
6549 
6550   // Get the correct type for pointers.
6551   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6552   // Negate the size.
6553   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6554                                 DAG.getConstant(0, dl, PtrVT), Size);
6555   // Construct a node for the frame pointer save index.
6556   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6557   // Build a DYNALLOC node.
6558   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6559   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6560   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6561 }
6562 
6563 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6564                                                      SelectionDAG &DAG) const {
6565   MachineFunction &MF = DAG.getMachineFunction();
6566 
6567   bool isPPC64 = Subtarget.isPPC64();
6568   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6569 
6570   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6571   return DAG.getFrameIndex(FI, PtrVT);
6572 }
6573 
6574 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6575                                                SelectionDAG &DAG) const {
6576   SDLoc DL(Op);
6577   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6578                      DAG.getVTList(MVT::i32, MVT::Other),
6579                      Op.getOperand(0), Op.getOperand(1));
6580 }
6581 
6582 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6583                                                 SelectionDAG &DAG) const {
6584   SDLoc DL(Op);
6585   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6586                      Op.getOperand(0), Op.getOperand(1));
6587 }
6588 
6589 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6590   if (Op.getValueType().isVector())
6591     return LowerVectorLoad(Op, DAG);
6592 
6593   assert(Op.getValueType() == MVT::i1 &&
6594          "Custom lowering only for i1 loads");
6595 
6596   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6597 
6598   SDLoc dl(Op);
6599   LoadSDNode *LD = cast<LoadSDNode>(Op);
6600 
6601   SDValue Chain = LD->getChain();
6602   SDValue BasePtr = LD->getBasePtr();
6603   MachineMemOperand *MMO = LD->getMemOperand();
6604 
6605   SDValue NewLD =
6606       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6607                      BasePtr, MVT::i8, MMO);
6608   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6609 
6610   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6611   return DAG.getMergeValues(Ops, dl);
6612 }
6613 
6614 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6615   if (Op.getOperand(1).getValueType().isVector())
6616     return LowerVectorStore(Op, DAG);
6617 
6618   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6619          "Custom lowering only for i1 stores");
6620 
6621   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6622 
6623   SDLoc dl(Op);
6624   StoreSDNode *ST = cast<StoreSDNode>(Op);
6625 
6626   SDValue Chain = ST->getChain();
6627   SDValue BasePtr = ST->getBasePtr();
6628   SDValue Value = ST->getValue();
6629   MachineMemOperand *MMO = ST->getMemOperand();
6630 
6631   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6632                       Value);
6633   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6634 }
6635 
6636 // FIXME: Remove this once the ANDI glue bug is fixed:
6637 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6638   assert(Op.getValueType() == MVT::i1 &&
6639          "Custom lowering only for i1 results");
6640 
6641   SDLoc DL(Op);
6642   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6643                      Op.getOperand(0));
6644 }
6645 
6646 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6647 /// possible.
6648 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6649   // Not FP? Not a fsel.
6650   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6651       !Op.getOperand(2).getValueType().isFloatingPoint())
6652     return Op;
6653 
6654   // We might be able to do better than this under some circumstances, but in
6655   // general, fsel-based lowering of select is a finite-math-only optimization.
6656   // For more information, see section F.3 of the 2.06 ISA specification.
6657   if (!DAG.getTarget().Options.NoInfsFPMath ||
6658       !DAG.getTarget().Options.NoNaNsFPMath)
6659     return Op;
6660   // TODO: Propagate flags from the select rather than global settings.
6661   SDNodeFlags Flags;
6662   Flags.setNoInfs(true);
6663   Flags.setNoNaNs(true);
6664 
6665   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6666 
6667   EVT ResVT = Op.getValueType();
6668   EVT CmpVT = Op.getOperand(0).getValueType();
6669   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6670   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6671   SDLoc dl(Op);
6672 
6673   // If the RHS of the comparison is a 0.0, we don't need to do the
6674   // subtraction at all.
6675   SDValue Sel1;
6676   if (isFloatingPointZero(RHS))
6677     switch (CC) {
6678     default: break;       // SETUO etc aren't handled by fsel.
6679     case ISD::SETNE:
6680       std::swap(TV, FV);
6681       LLVM_FALLTHROUGH;
6682     case ISD::SETEQ:
6683       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6684         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6685       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6686       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6687         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6688       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6689                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6690     case ISD::SETULT:
6691     case ISD::SETLT:
6692       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6693       LLVM_FALLTHROUGH;
6694     case ISD::SETOGE:
6695     case ISD::SETGE:
6696       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6697         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6698       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6699     case ISD::SETUGT:
6700     case ISD::SETGT:
6701       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6702       LLVM_FALLTHROUGH;
6703     case ISD::SETOLE:
6704     case ISD::SETLE:
6705       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6706         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6707       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6708                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6709     }
6710 
6711   SDValue Cmp;
6712   switch (CC) {
6713   default: break;       // SETUO etc aren't handled by fsel.
6714   case ISD::SETNE:
6715     std::swap(TV, FV);
6716     LLVM_FALLTHROUGH;
6717   case ISD::SETEQ:
6718     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6719     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6720       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6721     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6722     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6723       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6724     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6725                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6726   case ISD::SETULT:
6727   case ISD::SETLT:
6728     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6729     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6730       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6731     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6732   case ISD::SETOGE:
6733   case ISD::SETGE:
6734     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6735     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6736       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6737     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6738   case ISD::SETUGT:
6739   case ISD::SETGT:
6740     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6741     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6742       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6743     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6744   case ISD::SETOLE:
6745   case ISD::SETLE:
6746     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6747     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6748       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6749     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6750   }
6751   return Op;
6752 }
6753 
6754 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6755                                                SelectionDAG &DAG,
6756                                                const SDLoc &dl) const {
6757   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6758   SDValue Src = Op.getOperand(0);
6759   if (Src.getValueType() == MVT::f32)
6760     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6761 
6762   SDValue Tmp;
6763   switch (Op.getSimpleValueType().SimpleTy) {
6764   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6765   case MVT::i32:
6766     Tmp = DAG.getNode(
6767         Op.getOpcode() == ISD::FP_TO_SINT
6768             ? PPCISD::FCTIWZ
6769             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6770         dl, MVT::f64, Src);
6771     break;
6772   case MVT::i64:
6773     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6774            "i64 FP_TO_UINT is supported only with FPCVT");
6775     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6776                                                         PPCISD::FCTIDUZ,
6777                       dl, MVT::f64, Src);
6778     break;
6779   }
6780 
6781   // Convert the FP value to an int value through memory.
6782   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6783     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6784   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6785   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6786   MachinePointerInfo MPI =
6787       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6788 
6789   // Emit a store to the stack slot.
6790   SDValue Chain;
6791   if (i32Stack) {
6792     MachineFunction &MF = DAG.getMachineFunction();
6793     MachineMemOperand *MMO =
6794       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6795     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6796     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6797               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6798   } else
6799     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6800 
6801   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6802   // add in a bias on big endian.
6803   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6804     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6805                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6806     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6807   }
6808 
6809   RLI.Chain = Chain;
6810   RLI.Ptr = FIPtr;
6811   RLI.MPI = MPI;
6812 }
6813 
6814 /// \brief Custom lowers floating point to integer conversions to use
6815 /// the direct move instructions available in ISA 2.07 to avoid the
6816 /// need for load/store combinations.
6817 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6818                                                     SelectionDAG &DAG,
6819                                                     const SDLoc &dl) const {
6820   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6821   SDValue Src = Op.getOperand(0);
6822 
6823   if (Src.getValueType() == MVT::f32)
6824     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6825 
6826   SDValue Tmp;
6827   switch (Op.getSimpleValueType().SimpleTy) {
6828   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6829   case MVT::i32:
6830     Tmp = DAG.getNode(
6831         Op.getOpcode() == ISD::FP_TO_SINT
6832             ? PPCISD::FCTIWZ
6833             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6834         dl, MVT::f64, Src);
6835     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6836     break;
6837   case MVT::i64:
6838     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6839            "i64 FP_TO_UINT is supported only with FPCVT");
6840     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6841                                                         PPCISD::FCTIDUZ,
6842                       dl, MVT::f64, Src);
6843     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6844     break;
6845   }
6846   return Tmp;
6847 }
6848 
6849 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6850                                           const SDLoc &dl) const {
6851   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6852     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6853 
6854   ReuseLoadInfo RLI;
6855   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6856 
6857   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6858                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6859 }
6860 
6861 // We're trying to insert a regular store, S, and then a load, L. If the
6862 // incoming value, O, is a load, we might just be able to have our load use the
6863 // address used by O. However, we don't know if anything else will store to
6864 // that address before we can load from it. To prevent this situation, we need
6865 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6866 // the same chain operand as O, we create a token factor from the chain results
6867 // of O and L, and we replace all uses of O's chain result with that token
6868 // factor (see spliceIntoChain below for this last part).
6869 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6870                                             ReuseLoadInfo &RLI,
6871                                             SelectionDAG &DAG,
6872                                             ISD::LoadExtType ET) const {
6873   SDLoc dl(Op);
6874   if (ET == ISD::NON_EXTLOAD &&
6875       (Op.getOpcode() == ISD::FP_TO_UINT ||
6876        Op.getOpcode() == ISD::FP_TO_SINT) &&
6877       isOperationLegalOrCustom(Op.getOpcode(),
6878                                Op.getOperand(0).getValueType())) {
6879 
6880     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6881     return true;
6882   }
6883 
6884   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6885   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6886       LD->isNonTemporal())
6887     return false;
6888   if (LD->getMemoryVT() != MemVT)
6889     return false;
6890 
6891   RLI.Ptr = LD->getBasePtr();
6892   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6893     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6894            "Non-pre-inc AM on PPC?");
6895     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6896                           LD->getOffset());
6897   }
6898 
6899   RLI.Chain = LD->getChain();
6900   RLI.MPI = LD->getPointerInfo();
6901   RLI.IsDereferenceable = LD->isDereferenceable();
6902   RLI.IsInvariant = LD->isInvariant();
6903   RLI.Alignment = LD->getAlignment();
6904   RLI.AAInfo = LD->getAAInfo();
6905   RLI.Ranges = LD->getRanges();
6906 
6907   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6908   return true;
6909 }
6910 
6911 // Given the head of the old chain, ResChain, insert a token factor containing
6912 // it and NewResChain, and make users of ResChain now be users of that token
6913 // factor.
6914 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
6915 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6916                                         SDValue NewResChain,
6917                                         SelectionDAG &DAG) const {
6918   if (!ResChain)
6919     return;
6920 
6921   SDLoc dl(NewResChain);
6922 
6923   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6924                            NewResChain, DAG.getUNDEF(MVT::Other));
6925   assert(TF.getNode() != NewResChain.getNode() &&
6926          "A new TF really is required here");
6927 
6928   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6929   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6930 }
6931 
6932 /// \brief Analyze profitability of direct move
6933 /// prefer float load to int load plus direct move
6934 /// when there is no integer use of int load
6935 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6936   SDNode *Origin = Op.getOperand(0).getNode();
6937   if (Origin->getOpcode() != ISD::LOAD)
6938     return true;
6939 
6940   // If there is no LXSIBZX/LXSIHZX, like Power8,
6941   // prefer direct move if the memory size is 1 or 2 bytes.
6942   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6943   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6944     return true;
6945 
6946   for (SDNode::use_iterator UI = Origin->use_begin(),
6947                             UE = Origin->use_end();
6948        UI != UE; ++UI) {
6949 
6950     // Only look at the users of the loaded value.
6951     if (UI.getUse().get().getResNo() != 0)
6952       continue;
6953 
6954     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6955         UI->getOpcode() != ISD::UINT_TO_FP)
6956       return true;
6957   }
6958 
6959   return false;
6960 }
6961 
6962 /// \brief Custom lowers integer to floating point conversions to use
6963 /// the direct move instructions available in ISA 2.07 to avoid the
6964 /// need for load/store combinations.
6965 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6966                                                     SelectionDAG &DAG,
6967                                                     const SDLoc &dl) const {
6968   assert((Op.getValueType() == MVT::f32 ||
6969           Op.getValueType() == MVT::f64) &&
6970          "Invalid floating point type as target of conversion");
6971   assert(Subtarget.hasFPCVT() &&
6972          "Int to FP conversions with direct moves require FPCVT");
6973   SDValue FP;
6974   SDValue Src = Op.getOperand(0);
6975   bool SinglePrec = Op.getValueType() == MVT::f32;
6976   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6977   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6978   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6979                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6980 
6981   if (WordInt) {
6982     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6983                      dl, MVT::f64, Src);
6984     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6985   }
6986   else {
6987     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6988     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6989   }
6990 
6991   return FP;
6992 }
6993 
6994 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6995                                           SelectionDAG &DAG) const {
6996   SDLoc dl(Op);
6997 
6998   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6999     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7000       return SDValue();
7001 
7002     SDValue Value = Op.getOperand(0);
7003     // The values are now known to be -1 (false) or 1 (true). To convert this
7004     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7005     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7006     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7007 
7008     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7009 
7010     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7011 
7012     if (Op.getValueType() != MVT::v4f64)
7013       Value = DAG.getNode(ISD::FP_ROUND, dl,
7014                           Op.getValueType(), Value,
7015                           DAG.getIntPtrConstant(1, dl));
7016     return Value;
7017   }
7018 
7019   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7020   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7021     return SDValue();
7022 
7023   if (Op.getOperand(0).getValueType() == MVT::i1)
7024     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7025                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7026                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7027 
7028   // If we have direct moves, we can do all the conversion, skip the store/load
7029   // however, without FPCVT we can't do most conversions.
7030   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7031       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7032     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7033 
7034   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7035          "UINT_TO_FP is supported only with FPCVT");
7036 
7037   // If we have FCFIDS, then use it when converting to single-precision.
7038   // Otherwise, convert to double-precision and then round.
7039   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7040                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7041                                                             : PPCISD::FCFIDS)
7042                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7043                                                             : PPCISD::FCFID);
7044   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7045                   ? MVT::f32
7046                   : MVT::f64;
7047 
7048   if (Op.getOperand(0).getValueType() == MVT::i64) {
7049     SDValue SINT = Op.getOperand(0);
7050     // When converting to single-precision, we actually need to convert
7051     // to double-precision first and then round to single-precision.
7052     // To avoid double-rounding effects during that operation, we have
7053     // to prepare the input operand.  Bits that might be truncated when
7054     // converting to double-precision are replaced by a bit that won't
7055     // be lost at this stage, but is below the single-precision rounding
7056     // position.
7057     //
7058     // However, if -enable-unsafe-fp-math is in effect, accept double
7059     // rounding to avoid the extra overhead.
7060     if (Op.getValueType() == MVT::f32 &&
7061         !Subtarget.hasFPCVT() &&
7062         !DAG.getTarget().Options.UnsafeFPMath) {
7063 
7064       // Twiddle input to make sure the low 11 bits are zero.  (If this
7065       // is the case, we are guaranteed the value will fit into the 53 bit
7066       // mantissa of an IEEE double-precision value without rounding.)
7067       // If any of those low 11 bits were not zero originally, make sure
7068       // bit 12 (value 2048) is set instead, so that the final rounding
7069       // to single-precision gets the correct result.
7070       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7071                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7072       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7073                           Round, DAG.getConstant(2047, dl, MVT::i64));
7074       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7075       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7076                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7077 
7078       // However, we cannot use that value unconditionally: if the magnitude
7079       // of the input value is small, the bit-twiddling we did above might
7080       // end up visibly changing the output.  Fortunately, in that case, we
7081       // don't need to twiddle bits since the original input will convert
7082       // exactly to double-precision floating-point already.  Therefore,
7083       // construct a conditional to use the original value if the top 11
7084       // bits are all sign-bit copies, and use the rounded value computed
7085       // above otherwise.
7086       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7087                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7088       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7089                          Cond, DAG.getConstant(1, dl, MVT::i64));
7090       Cond = DAG.getSetCC(dl, MVT::i32,
7091                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7092 
7093       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7094     }
7095 
7096     ReuseLoadInfo RLI;
7097     SDValue Bits;
7098 
7099     MachineFunction &MF = DAG.getMachineFunction();
7100     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7101       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7102                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7103       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7104     } else if (Subtarget.hasLFIWAX() &&
7105                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7106       MachineMemOperand *MMO =
7107         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7108                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7109       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7110       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7111                                      DAG.getVTList(MVT::f64, MVT::Other),
7112                                      Ops, MVT::i32, MMO);
7113       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7114     } else if (Subtarget.hasFPCVT() &&
7115                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7116       MachineMemOperand *MMO =
7117         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7118                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7119       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7120       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7121                                      DAG.getVTList(MVT::f64, MVT::Other),
7122                                      Ops, MVT::i32, MMO);
7123       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7124     } else if (((Subtarget.hasLFIWAX() &&
7125                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7126                 (Subtarget.hasFPCVT() &&
7127                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7128                SINT.getOperand(0).getValueType() == MVT::i32) {
7129       MachineFrameInfo &MFI = MF.getFrameInfo();
7130       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7131 
7132       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7133       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7134 
7135       SDValue Store =
7136           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7137                        MachinePointerInfo::getFixedStack(
7138                            DAG.getMachineFunction(), FrameIdx));
7139 
7140       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7141              "Expected an i32 store");
7142 
7143       RLI.Ptr = FIdx;
7144       RLI.Chain = Store;
7145       RLI.MPI =
7146           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7147       RLI.Alignment = 4;
7148 
7149       MachineMemOperand *MMO =
7150         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7151                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7152       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7153       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7154                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7155                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7156                                      Ops, MVT::i32, MMO);
7157     } else
7158       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7159 
7160     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7161 
7162     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7163       FP = DAG.getNode(ISD::FP_ROUND, dl,
7164                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7165     return FP;
7166   }
7167 
7168   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7169          "Unhandled INT_TO_FP type in custom expander!");
7170   // Since we only generate this in 64-bit mode, we can take advantage of
7171   // 64-bit registers.  In particular, sign extend the input value into the
7172   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7173   // then lfd it and fcfid it.
7174   MachineFunction &MF = DAG.getMachineFunction();
7175   MachineFrameInfo &MFI = MF.getFrameInfo();
7176   EVT PtrVT = getPointerTy(MF.getDataLayout());
7177 
7178   SDValue Ld;
7179   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7180     ReuseLoadInfo RLI;
7181     bool ReusingLoad;
7182     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7183                                             DAG))) {
7184       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7185       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7186 
7187       SDValue Store =
7188           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7189                        MachinePointerInfo::getFixedStack(
7190                            DAG.getMachineFunction(), FrameIdx));
7191 
7192       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7193              "Expected an i32 store");
7194 
7195       RLI.Ptr = FIdx;
7196       RLI.Chain = Store;
7197       RLI.MPI =
7198           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7199       RLI.Alignment = 4;
7200     }
7201 
7202     MachineMemOperand *MMO =
7203       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7204                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7205     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7206     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7207                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7208                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7209                                  Ops, MVT::i32, MMO);
7210     if (ReusingLoad)
7211       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7212   } else {
7213     assert(Subtarget.isPPC64() &&
7214            "i32->FP without LFIWAX supported only on PPC64");
7215 
7216     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7217     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7218 
7219     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7220                                 Op.getOperand(0));
7221 
7222     // STD the extended value into the stack slot.
7223     SDValue Store = DAG.getStore(
7224         DAG.getEntryNode(), dl, Ext64, FIdx,
7225         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7226 
7227     // Load the value as a double.
7228     Ld = DAG.getLoad(
7229         MVT::f64, dl, Store, FIdx,
7230         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7231   }
7232 
7233   // FCFID it and return it.
7234   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7235   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7236     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7237                      DAG.getIntPtrConstant(0, dl));
7238   return FP;
7239 }
7240 
7241 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7242                                             SelectionDAG &DAG) const {
7243   SDLoc dl(Op);
7244   /*
7245    The rounding mode is in bits 30:31 of FPSR, and has the following
7246    settings:
7247      00 Round to nearest
7248      01 Round to 0
7249      10 Round to +inf
7250      11 Round to -inf
7251 
7252   FLT_ROUNDS, on the other hand, expects the following:
7253     -1 Undefined
7254      0 Round to 0
7255      1 Round to nearest
7256      2 Round to +inf
7257      3 Round to -inf
7258 
7259   To perform the conversion, we do:
7260     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7261   */
7262 
7263   MachineFunction &MF = DAG.getMachineFunction();
7264   EVT VT = Op.getValueType();
7265   EVT PtrVT = getPointerTy(MF.getDataLayout());
7266 
7267   // Save FP Control Word to register
7268   EVT NodeTys[] = {
7269     MVT::f64,    // return register
7270     MVT::Glue    // unused in this context
7271   };
7272   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7273 
7274   // Save FP register to stack slot
7275   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7276   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7277   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7278                                MachinePointerInfo());
7279 
7280   // Load FP Control Word from low 32 bits of stack slot.
7281   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7282   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7283   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7284 
7285   // Transform as necessary
7286   SDValue CWD1 =
7287     DAG.getNode(ISD::AND, dl, MVT::i32,
7288                 CWD, DAG.getConstant(3, dl, MVT::i32));
7289   SDValue CWD2 =
7290     DAG.getNode(ISD::SRL, dl, MVT::i32,
7291                 DAG.getNode(ISD::AND, dl, MVT::i32,
7292                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7293                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7294                             DAG.getConstant(3, dl, MVT::i32)),
7295                 DAG.getConstant(1, dl, MVT::i32));
7296 
7297   SDValue RetVal =
7298     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7299 
7300   return DAG.getNode((VT.getSizeInBits() < 16 ?
7301                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7302 }
7303 
7304 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7305   EVT VT = Op.getValueType();
7306   unsigned BitWidth = VT.getSizeInBits();
7307   SDLoc dl(Op);
7308   assert(Op.getNumOperands() == 3 &&
7309          VT == Op.getOperand(1).getValueType() &&
7310          "Unexpected SHL!");
7311 
7312   // Expand into a bunch of logical ops.  Note that these ops
7313   // depend on the PPC behavior for oversized shift amounts.
7314   SDValue Lo = Op.getOperand(0);
7315   SDValue Hi = Op.getOperand(1);
7316   SDValue Amt = Op.getOperand(2);
7317   EVT AmtVT = Amt.getValueType();
7318 
7319   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7320                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7321   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7322   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7323   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7324   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7325                              DAG.getConstant(-BitWidth, dl, AmtVT));
7326   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7327   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7328   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7329   SDValue OutOps[] = { OutLo, OutHi };
7330   return DAG.getMergeValues(OutOps, dl);
7331 }
7332 
7333 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7334   EVT VT = Op.getValueType();
7335   SDLoc dl(Op);
7336   unsigned BitWidth = VT.getSizeInBits();
7337   assert(Op.getNumOperands() == 3 &&
7338          VT == Op.getOperand(1).getValueType() &&
7339          "Unexpected SRL!");
7340 
7341   // Expand into a bunch of logical ops.  Note that these ops
7342   // depend on the PPC behavior for oversized shift amounts.
7343   SDValue Lo = Op.getOperand(0);
7344   SDValue Hi = Op.getOperand(1);
7345   SDValue Amt = Op.getOperand(2);
7346   EVT AmtVT = Amt.getValueType();
7347 
7348   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7349                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7350   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7351   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7352   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7353   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7354                              DAG.getConstant(-BitWidth, dl, AmtVT));
7355   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7356   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7357   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7358   SDValue OutOps[] = { OutLo, OutHi };
7359   return DAG.getMergeValues(OutOps, dl);
7360 }
7361 
7362 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7363   SDLoc dl(Op);
7364   EVT VT = Op.getValueType();
7365   unsigned BitWidth = VT.getSizeInBits();
7366   assert(Op.getNumOperands() == 3 &&
7367          VT == Op.getOperand(1).getValueType() &&
7368          "Unexpected SRA!");
7369 
7370   // Expand into a bunch of logical ops, followed by a select_cc.
7371   SDValue Lo = Op.getOperand(0);
7372   SDValue Hi = Op.getOperand(1);
7373   SDValue Amt = Op.getOperand(2);
7374   EVT AmtVT = Amt.getValueType();
7375 
7376   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7377                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7378   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7379   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7380   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7381   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7382                              DAG.getConstant(-BitWidth, dl, AmtVT));
7383   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7384   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7385   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7386                                   Tmp4, Tmp6, ISD::SETLE);
7387   SDValue OutOps[] = { OutLo, OutHi };
7388   return DAG.getMergeValues(OutOps, dl);
7389 }
7390 
7391 //===----------------------------------------------------------------------===//
7392 // Vector related lowering.
7393 //
7394 
7395 /// BuildSplatI - Build a canonical splati of Val with an element size of
7396 /// SplatSize.  Cast the result to VT.
7397 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7398                            SelectionDAG &DAG, const SDLoc &dl) {
7399   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7400 
7401   static const MVT VTys[] = { // canonical VT to use for each size.
7402     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7403   };
7404 
7405   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7406 
7407   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7408   if (Val == -1)
7409     SplatSize = 1;
7410 
7411   EVT CanonicalVT = VTys[SplatSize-1];
7412 
7413   // Build a canonical splat for this value.
7414   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7415 }
7416 
7417 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7418 /// specified intrinsic ID.
7419 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7420                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7421   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7422   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7423                      DAG.getConstant(IID, dl, MVT::i32), Op);
7424 }
7425 
7426 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7427 /// specified intrinsic ID.
7428 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7429                                 SelectionDAG &DAG, const SDLoc &dl,
7430                                 EVT DestVT = MVT::Other) {
7431   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7432   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7433                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7434 }
7435 
7436 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7437 /// specified intrinsic ID.
7438 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7439                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7440                                 EVT DestVT = MVT::Other) {
7441   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7442   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7443                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7444 }
7445 
7446 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7447 /// amount.  The result has the specified value type.
7448 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7449                            SelectionDAG &DAG, const SDLoc &dl) {
7450   // Force LHS/RHS to be the right type.
7451   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7452   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7453 
7454   int Ops[16];
7455   for (unsigned i = 0; i != 16; ++i)
7456     Ops[i] = i + Amt;
7457   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7458   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7459 }
7460 
7461 /// Do we have an efficient pattern in a .td file for this node?
7462 ///
7463 /// \param V - pointer to the BuildVectorSDNode being matched
7464 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7465 ///
7466 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7467 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7468 /// the opposite is true (expansion is beneficial) are:
7469 /// - The node builds a vector out of integers that are not 32 or 64-bits
7470 /// - The node builds a vector out of constants
7471 /// - The node is a "load-and-splat"
7472 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7473 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7474                                             bool HasDirectMove,
7475                                             bool HasP8Vector) {
7476   EVT VecVT = V->getValueType(0);
7477   bool RightType = VecVT == MVT::v2f64 ||
7478     (HasP8Vector && VecVT == MVT::v4f32) ||
7479     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7480   if (!RightType)
7481     return false;
7482 
7483   bool IsSplat = true;
7484   bool IsLoad = false;
7485   SDValue Op0 = V->getOperand(0);
7486 
7487   // This function is called in a block that confirms the node is not a constant
7488   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7489   // different constants.
7490   if (V->isConstant())
7491     return false;
7492   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7493     if (V->getOperand(i).isUndef())
7494       return false;
7495     // We want to expand nodes that represent load-and-splat even if the
7496     // loaded value is a floating point truncation or conversion to int.
7497     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7498         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7499          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7500         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7501          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7502         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7503          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7504       IsLoad = true;
7505     // If the operands are different or the input is not a load and has more
7506     // uses than just this BV node, then it isn't a splat.
7507     if (V->getOperand(i) != Op0 ||
7508         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7509       IsSplat = false;
7510   }
7511   return !(IsSplat && IsLoad);
7512 }
7513 
7514 // If this is a case we can't handle, return null and let the default
7515 // expansion code take care of it.  If we CAN select this case, and if it
7516 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7517 // this case more efficiently than a constant pool load, lower it to the
7518 // sequence of ops that should be used.
7519 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7520                                              SelectionDAG &DAG) const {
7521   SDLoc dl(Op);
7522   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7523   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7524 
7525   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7526     // We first build an i32 vector, load it into a QPX register,
7527     // then convert it to a floating-point vector and compare it
7528     // to a zero vector to get the boolean result.
7529     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7530     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7531     MachinePointerInfo PtrInfo =
7532         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7533     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7534     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7535 
7536     assert(BVN->getNumOperands() == 4 &&
7537       "BUILD_VECTOR for v4i1 does not have 4 operands");
7538 
7539     bool IsConst = true;
7540     for (unsigned i = 0; i < 4; ++i) {
7541       if (BVN->getOperand(i).isUndef()) continue;
7542       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7543         IsConst = false;
7544         break;
7545       }
7546     }
7547 
7548     if (IsConst) {
7549       Constant *One =
7550         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7551       Constant *NegOne =
7552         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7553 
7554       Constant *CV[4];
7555       for (unsigned i = 0; i < 4; ++i) {
7556         if (BVN->getOperand(i).isUndef())
7557           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7558         else if (isNullConstant(BVN->getOperand(i)))
7559           CV[i] = NegOne;
7560         else
7561           CV[i] = One;
7562       }
7563 
7564       Constant *CP = ConstantVector::get(CV);
7565       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7566                                           16 /* alignment */);
7567 
7568       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7569       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7570       return DAG.getMemIntrinsicNode(
7571           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7572           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7573     }
7574 
7575     SmallVector<SDValue, 4> Stores;
7576     for (unsigned i = 0; i < 4; ++i) {
7577       if (BVN->getOperand(i).isUndef()) continue;
7578 
7579       unsigned Offset = 4*i;
7580       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7581       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7582 
7583       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7584       if (StoreSize > 4) {
7585         Stores.push_back(
7586             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7587                               PtrInfo.getWithOffset(Offset), MVT::i32));
7588       } else {
7589         SDValue StoreValue = BVN->getOperand(i);
7590         if (StoreSize < 4)
7591           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7592 
7593         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7594                                       PtrInfo.getWithOffset(Offset)));
7595       }
7596     }
7597 
7598     SDValue StoreChain;
7599     if (!Stores.empty())
7600       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7601     else
7602       StoreChain = DAG.getEntryNode();
7603 
7604     // Now load from v4i32 into the QPX register; this will extend it to
7605     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7606     // is typed as v4f64 because the QPX register integer states are not
7607     // explicitly represented.
7608 
7609     SDValue Ops[] = {StoreChain,
7610                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7611                      FIdx};
7612     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7613 
7614     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7615       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7616     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7617       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7618       LoadedVect);
7619 
7620     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7621 
7622     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7623   }
7624 
7625   // All other QPX vectors are handled by generic code.
7626   if (Subtarget.hasQPX())
7627     return SDValue();
7628 
7629   // Check if this is a splat of a constant value.
7630   APInt APSplatBits, APSplatUndef;
7631   unsigned SplatBitSize;
7632   bool HasAnyUndefs;
7633   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7634                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7635       SplatBitSize > 32) {
7636     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7637     // lowered to VSX instructions under certain conditions.
7638     // Without VSX, there is no pattern more efficient than expanding the node.
7639     if (Subtarget.hasVSX() &&
7640         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7641                                         Subtarget.hasP8Vector()))
7642       return Op;
7643     return SDValue();
7644   }
7645 
7646   unsigned SplatBits = APSplatBits.getZExtValue();
7647   unsigned SplatUndef = APSplatUndef.getZExtValue();
7648   unsigned SplatSize = SplatBitSize / 8;
7649 
7650   // First, handle single instruction cases.
7651 
7652   // All zeros?
7653   if (SplatBits == 0) {
7654     // Canonicalize all zero vectors to be v4i32.
7655     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7656       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7657       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7658     }
7659     return Op;
7660   }
7661 
7662   // We have XXSPLTIB for constant splats one byte wide
7663   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7664     // This is a splat of 1-byte elements with some elements potentially undef.
7665     // Rather than trying to match undef in the SDAG patterns, ensure that all
7666     // elements are the same constant.
7667     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7668       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7669                                                        dl, MVT::i32));
7670       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7671       if (Op.getValueType() != MVT::v16i8)
7672         return DAG.getBitcast(Op.getValueType(), NewBV);
7673       return NewBV;
7674     }
7675 
7676     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7677     // detect that constant splats like v8i16: 0xABAB are really just splats
7678     // of a 1-byte constant. In this case, we need to convert the node to a
7679     // splat of v16i8 and a bitcast.
7680     if (Op.getValueType() != MVT::v16i8)
7681       return DAG.getBitcast(Op.getValueType(),
7682                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
7683 
7684     return Op;
7685   }
7686 
7687   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7688   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7689                     (32-SplatBitSize));
7690   if (SextVal >= -16 && SextVal <= 15)
7691     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7692 
7693   // Two instruction sequences.
7694 
7695   // If this value is in the range [-32,30] and is even, use:
7696   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7697   // If this value is in the range [17,31] and is odd, use:
7698   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7699   // If this value is in the range [-31,-17] and is odd, use:
7700   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7701   // Note the last two are three-instruction sequences.
7702   if (SextVal >= -32 && SextVal <= 31) {
7703     // To avoid having these optimizations undone by constant folding,
7704     // we convert to a pseudo that will be expanded later into one of
7705     // the above forms.
7706     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7707     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7708               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7709     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7710     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7711     if (VT == Op.getValueType())
7712       return RetVal;
7713     else
7714       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7715   }
7716 
7717   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7718   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7719   // for fneg/fabs.
7720   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7721     // Make -1 and vspltisw -1:
7722     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7723 
7724     // Make the VSLW intrinsic, computing 0x8000_0000.
7725     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7726                                    OnesV, DAG, dl);
7727 
7728     // xor by OnesV to invert it.
7729     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7730     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7731   }
7732 
7733   // Check to see if this is a wide variety of vsplti*, binop self cases.
7734   static const signed char SplatCsts[] = {
7735     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7736     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7737   };
7738 
7739   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7740     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7741     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7742     int i = SplatCsts[idx];
7743 
7744     // Figure out what shift amount will be used by altivec if shifted by i in
7745     // this splat size.
7746     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7747 
7748     // vsplti + shl self.
7749     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7750       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7751       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7752         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7753         Intrinsic::ppc_altivec_vslw
7754       };
7755       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7756       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7757     }
7758 
7759     // vsplti + srl self.
7760     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7761       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7762       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7763         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7764         Intrinsic::ppc_altivec_vsrw
7765       };
7766       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7767       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7768     }
7769 
7770     // vsplti + sra self.
7771     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7772       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7773       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7774         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7775         Intrinsic::ppc_altivec_vsraw
7776       };
7777       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7778       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7779     }
7780 
7781     // vsplti + rol self.
7782     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7783                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7784       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7785       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7786         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7787         Intrinsic::ppc_altivec_vrlw
7788       };
7789       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7790       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7791     }
7792 
7793     // t = vsplti c, result = vsldoi t, t, 1
7794     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7795       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7796       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7797       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7798     }
7799     // t = vsplti c, result = vsldoi t, t, 2
7800     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7801       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7802       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7803       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7804     }
7805     // t = vsplti c, result = vsldoi t, t, 3
7806     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7807       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7808       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7809       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7810     }
7811   }
7812 
7813   return SDValue();
7814 }
7815 
7816 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7817 /// the specified operations to build the shuffle.
7818 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7819                                       SDValue RHS, SelectionDAG &DAG,
7820                                       const SDLoc &dl) {
7821   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7822   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7823   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7824 
7825   enum {
7826     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7827     OP_VMRGHW,
7828     OP_VMRGLW,
7829     OP_VSPLTISW0,
7830     OP_VSPLTISW1,
7831     OP_VSPLTISW2,
7832     OP_VSPLTISW3,
7833     OP_VSLDOI4,
7834     OP_VSLDOI8,
7835     OP_VSLDOI12
7836   };
7837 
7838   if (OpNum == OP_COPY) {
7839     if (LHSID == (1*9+2)*9+3) return LHS;
7840     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7841     return RHS;
7842   }
7843 
7844   SDValue OpLHS, OpRHS;
7845   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7846   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7847 
7848   int ShufIdxs[16];
7849   switch (OpNum) {
7850   default: llvm_unreachable("Unknown i32 permute!");
7851   case OP_VMRGHW:
7852     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7853     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7854     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7855     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7856     break;
7857   case OP_VMRGLW:
7858     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7859     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7860     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7861     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7862     break;
7863   case OP_VSPLTISW0:
7864     for (unsigned i = 0; i != 16; ++i)
7865       ShufIdxs[i] = (i&3)+0;
7866     break;
7867   case OP_VSPLTISW1:
7868     for (unsigned i = 0; i != 16; ++i)
7869       ShufIdxs[i] = (i&3)+4;
7870     break;
7871   case OP_VSPLTISW2:
7872     for (unsigned i = 0; i != 16; ++i)
7873       ShufIdxs[i] = (i&3)+8;
7874     break;
7875   case OP_VSPLTISW3:
7876     for (unsigned i = 0; i != 16; ++i)
7877       ShufIdxs[i] = (i&3)+12;
7878     break;
7879   case OP_VSLDOI4:
7880     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7881   case OP_VSLDOI8:
7882     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7883   case OP_VSLDOI12:
7884     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7885   }
7886   EVT VT = OpLHS.getValueType();
7887   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7888   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7889   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7890   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7891 }
7892 
7893 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
7894 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
7895 /// SDValue.
7896 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
7897                                            SelectionDAG &DAG) const {
7898   const unsigned BytesInVector = 16;
7899   bool IsLE = Subtarget.isLittleEndian();
7900   SDLoc dl(N);
7901   SDValue V1 = N->getOperand(0);
7902   SDValue V2 = N->getOperand(1);
7903   unsigned ShiftElts = 0, InsertAtByte = 0;
7904   bool Swap = false;
7905 
7906   // Shifts required to get the byte we want at element 7.
7907   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
7908                                    0, 15, 14, 13, 12, 11, 10, 9};
7909   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
7910                                 1, 2,  3,  4,  5,  6,  7,  8};
7911 
7912   ArrayRef<int> Mask = N->getMask();
7913   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
7914 
7915   // For each mask element, find out if we're just inserting something
7916   // from V2 into V1 or vice versa.
7917   // Possible permutations inserting an element from V2 into V1:
7918   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
7919   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
7920   //   ...
7921   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
7922   // Inserting from V1 into V2 will be similar, except mask range will be
7923   // [16,31].
7924 
7925   bool FoundCandidate = false;
7926   // If both vector operands for the shuffle are the same vector, the mask
7927   // will contain only elements from the first one and the second one will be
7928   // undef.
7929   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
7930   // Go through the mask of half-words to find an element that's being moved
7931   // from one vector to the other.
7932   for (unsigned i = 0; i < BytesInVector; ++i) {
7933     unsigned CurrentElement = Mask[i];
7934     // If 2nd operand is undefined, we should only look for element 7 in the
7935     // Mask.
7936     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
7937       continue;
7938 
7939     bool OtherElementsInOrder = true;
7940     // Examine the other elements in the Mask to see if they're in original
7941     // order.
7942     for (unsigned j = 0; j < BytesInVector; ++j) {
7943       if (j == i)
7944         continue;
7945       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
7946       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
7947       // in which we always assume we're always picking from the 1st operand.
7948       int MaskOffset =
7949           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
7950       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
7951         OtherElementsInOrder = false;
7952         break;
7953       }
7954     }
7955     // If other elements are in original order, we record the number of shifts
7956     // we need to get the element we want into element 7. Also record which byte
7957     // in the vector we should insert into.
7958     if (OtherElementsInOrder) {
7959       // If 2nd operand is undefined, we assume no shifts and no swapping.
7960       if (V2.isUndef()) {
7961         ShiftElts = 0;
7962         Swap = false;
7963       } else {
7964         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
7965         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
7966                          : BigEndianShifts[CurrentElement & 0xF];
7967         Swap = CurrentElement < BytesInVector;
7968       }
7969       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
7970       FoundCandidate = true;
7971       break;
7972     }
7973   }
7974 
7975   if (!FoundCandidate)
7976     return SDValue();
7977 
7978   // Candidate found, construct the proper SDAG sequence with VINSERTB,
7979   // optionally with VECSHL if shift is required.
7980   if (Swap)
7981     std::swap(V1, V2);
7982   if (V2.isUndef())
7983     V2 = V1;
7984   if (ShiftElts) {
7985     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
7986                               DAG.getConstant(ShiftElts, dl, MVT::i32));
7987     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
7988                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
7989   }
7990   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
7991                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
7992 }
7993 
7994 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
7995 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
7996 /// SDValue.
7997 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
7998                                            SelectionDAG &DAG) const {
7999   const unsigned NumHalfWords = 8;
8000   const unsigned BytesInVector = NumHalfWords * 2;
8001   // Check that the shuffle is on half-words.
8002   if (!isNByteElemShuffleMask(N, 2, 1))
8003     return SDValue();
8004 
8005   bool IsLE = Subtarget.isLittleEndian();
8006   SDLoc dl(N);
8007   SDValue V1 = N->getOperand(0);
8008   SDValue V2 = N->getOperand(1);
8009   unsigned ShiftElts = 0, InsertAtByte = 0;
8010   bool Swap = false;
8011 
8012   // Shifts required to get the half-word we want at element 3.
8013   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8014   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8015 
8016   uint32_t Mask = 0;
8017   uint32_t OriginalOrderLow = 0x1234567;
8018   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8019   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8020   // 32-bit space, only need 4-bit nibbles per element.
8021   for (unsigned i = 0; i < NumHalfWords; ++i) {
8022     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8023     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8024   }
8025 
8026   // For each mask element, find out if we're just inserting something
8027   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8028   // from V2 into V1:
8029   //   X, 1, 2, 3, 4, 5, 6, 7
8030   //   0, X, 2, 3, 4, 5, 6, 7
8031   //   0, 1, X, 3, 4, 5, 6, 7
8032   //   0, 1, 2, X, 4, 5, 6, 7
8033   //   0, 1, 2, 3, X, 5, 6, 7
8034   //   0, 1, 2, 3, 4, X, 6, 7
8035   //   0, 1, 2, 3, 4, 5, X, 7
8036   //   0, 1, 2, 3, 4, 5, 6, X
8037   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8038 
8039   bool FoundCandidate = false;
8040   // Go through the mask of half-words to find an element that's being moved
8041   // from one vector to the other.
8042   for (unsigned i = 0; i < NumHalfWords; ++i) {
8043     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8044     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8045     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8046     uint32_t TargetOrder = 0x0;
8047 
8048     // If both vector operands for the shuffle are the same vector, the mask
8049     // will contain only elements from the first one and the second one will be
8050     // undef.
8051     if (V2.isUndef()) {
8052       ShiftElts = 0;
8053       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8054       TargetOrder = OriginalOrderLow;
8055       Swap = false;
8056       // Skip if not the correct element or mask of other elements don't equal
8057       // to our expected order.
8058       if (MaskOneElt == VINSERTHSrcElem &&
8059           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8060         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8061         FoundCandidate = true;
8062         break;
8063       }
8064     } else { // If both operands are defined.
8065       // Target order is [8,15] if the current mask is between [0,7].
8066       TargetOrder =
8067           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8068       // Skip if mask of other elements don't equal our expected order.
8069       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8070         // We only need the last 3 bits for the number of shifts.
8071         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8072                          : BigEndianShifts[MaskOneElt & 0x7];
8073         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8074         Swap = MaskOneElt < NumHalfWords;
8075         FoundCandidate = true;
8076         break;
8077       }
8078     }
8079   }
8080 
8081   if (!FoundCandidate)
8082     return SDValue();
8083 
8084   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8085   // optionally with VECSHL if shift is required.
8086   if (Swap)
8087     std::swap(V1, V2);
8088   if (V2.isUndef())
8089     V2 = V1;
8090   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8091   if (ShiftElts) {
8092     // Double ShiftElts because we're left shifting on v16i8 type.
8093     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8094                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8095     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8096     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8097                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8098     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8099   }
8100   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8101   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8102                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8103   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8104 }
8105 
8106 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8107 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8108 /// return the code it can be lowered into.  Worst case, it can always be
8109 /// lowered into a vperm.
8110 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8111                                                SelectionDAG &DAG) const {
8112   SDLoc dl(Op);
8113   SDValue V1 = Op.getOperand(0);
8114   SDValue V2 = Op.getOperand(1);
8115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8116   EVT VT = Op.getValueType();
8117   bool isLittleEndian = Subtarget.isLittleEndian();
8118 
8119   unsigned ShiftElts, InsertAtByte;
8120   bool Swap = false;
8121   if (Subtarget.hasP9Vector() &&
8122       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8123                            isLittleEndian)) {
8124     if (Swap)
8125       std::swap(V1, V2);
8126     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8127     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8128     if (ShiftElts) {
8129       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8130                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8131       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8132                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8133       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8134     }
8135     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8136                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8137     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8138   }
8139 
8140   if (Subtarget.hasP9Altivec()) {
8141     SDValue NewISDNode;
8142     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8143       return NewISDNode;
8144 
8145     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8146       return NewISDNode;
8147   }
8148 
8149   if (Subtarget.hasVSX() &&
8150       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8151     if (Swap)
8152       std::swap(V1, V2);
8153     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8154     SDValue Conv2 =
8155         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8156 
8157     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8158                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8159     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8160   }
8161 
8162   if (Subtarget.hasVSX() &&
8163     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8164     if (Swap)
8165       std::swap(V1, V2);
8166     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8167     SDValue Conv2 =
8168         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8169 
8170     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8171                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8172     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8173   }
8174 
8175   if (Subtarget.hasP9Vector()) {
8176      if (PPC::isXXBRHShuffleMask(SVOp)) {
8177       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8178       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8179       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8180     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8181       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8182       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8183       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8184     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8185       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8186       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8187       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8188     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8189       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8190       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8191       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8192     }
8193   }
8194 
8195   if (Subtarget.hasVSX()) {
8196     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8197       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8198 
8199       // If the source for the shuffle is a scalar_to_vector that came from a
8200       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
8201       if (Subtarget.hasP9Vector() &&
8202           ((isLittleEndian && SplatIdx == 3) ||
8203            (!isLittleEndian && SplatIdx == 0))) {
8204         SDValue Src = V1.getOperand(0);
8205         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8206             Src.getOperand(0).getOpcode() == ISD::LOAD &&
8207             Src.getOperand(0).hasOneUse())
8208           return V1;
8209       }
8210       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8211       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8212                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8213       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8214     }
8215 
8216     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8217     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8218       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8219       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8220       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8221     }
8222   }
8223 
8224   if (Subtarget.hasQPX()) {
8225     if (VT.getVectorNumElements() != 4)
8226       return SDValue();
8227 
8228     if (V2.isUndef()) V2 = V1;
8229 
8230     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8231     if (AlignIdx != -1) {
8232       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8233                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8234     } else if (SVOp->isSplat()) {
8235       int SplatIdx = SVOp->getSplatIndex();
8236       if (SplatIdx >= 4) {
8237         std::swap(V1, V2);
8238         SplatIdx -= 4;
8239       }
8240 
8241       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8242                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8243     }
8244 
8245     // Lower this into a qvgpci/qvfperm pair.
8246 
8247     // Compute the qvgpci literal
8248     unsigned idx = 0;
8249     for (unsigned i = 0; i < 4; ++i) {
8250       int m = SVOp->getMaskElt(i);
8251       unsigned mm = m >= 0 ? (unsigned) m : i;
8252       idx |= mm << (3-i)*3;
8253     }
8254 
8255     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8256                              DAG.getConstant(idx, dl, MVT::i32));
8257     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8258   }
8259 
8260   // Cases that are handled by instructions that take permute immediates
8261   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8262   // selected by the instruction selector.
8263   if (V2.isUndef()) {
8264     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8265         PPC::isSplatShuffleMask(SVOp, 2) ||
8266         PPC::isSplatShuffleMask(SVOp, 4) ||
8267         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8268         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8269         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8270         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8271         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8272         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8273         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8274         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8275         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8276         (Subtarget.hasP8Altivec() && (
8277          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8278          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8279          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8280       return Op;
8281     }
8282   }
8283 
8284   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8285   // and produce a fixed permutation.  If any of these match, do not lower to
8286   // VPERM.
8287   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8288   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8289       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8290       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8291       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8292       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8293       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8294       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8295       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8296       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8297       (Subtarget.hasP8Altivec() && (
8298        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8299        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8300        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8301     return Op;
8302 
8303   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8304   // perfect shuffle table to emit an optimal matching sequence.
8305   ArrayRef<int> PermMask = SVOp->getMask();
8306 
8307   unsigned PFIndexes[4];
8308   bool isFourElementShuffle = true;
8309   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8310     unsigned EltNo = 8;   // Start out undef.
8311     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8312       if (PermMask[i*4+j] < 0)
8313         continue;   // Undef, ignore it.
8314 
8315       unsigned ByteSource = PermMask[i*4+j];
8316       if ((ByteSource & 3) != j) {
8317         isFourElementShuffle = false;
8318         break;
8319       }
8320 
8321       if (EltNo == 8) {
8322         EltNo = ByteSource/4;
8323       } else if (EltNo != ByteSource/4) {
8324         isFourElementShuffle = false;
8325         break;
8326       }
8327     }
8328     PFIndexes[i] = EltNo;
8329   }
8330 
8331   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8332   // perfect shuffle vector to determine if it is cost effective to do this as
8333   // discrete instructions, or whether we should use a vperm.
8334   // For now, we skip this for little endian until such time as we have a
8335   // little-endian perfect shuffle table.
8336   if (isFourElementShuffle && !isLittleEndian) {
8337     // Compute the index in the perfect shuffle table.
8338     unsigned PFTableIndex =
8339       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8340 
8341     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8342     unsigned Cost  = (PFEntry >> 30);
8343 
8344     // Determining when to avoid vperm is tricky.  Many things affect the cost
8345     // of vperm, particularly how many times the perm mask needs to be computed.
8346     // For example, if the perm mask can be hoisted out of a loop or is already
8347     // used (perhaps because there are multiple permutes with the same shuffle
8348     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8349     // the loop requires an extra register.
8350     //
8351     // As a compromise, we only emit discrete instructions if the shuffle can be
8352     // generated in 3 or fewer operations.  When we have loop information
8353     // available, if this block is within a loop, we should avoid using vperm
8354     // for 3-operation perms and use a constant pool load instead.
8355     if (Cost < 3)
8356       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8357   }
8358 
8359   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8360   // vector that will get spilled to the constant pool.
8361   if (V2.isUndef()) V2 = V1;
8362 
8363   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8364   // that it is in input element units, not in bytes.  Convert now.
8365 
8366   // For little endian, the order of the input vectors is reversed, and
8367   // the permutation mask is complemented with respect to 31.  This is
8368   // necessary to produce proper semantics with the big-endian-biased vperm
8369   // instruction.
8370   EVT EltVT = V1.getValueType().getVectorElementType();
8371   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8372 
8373   SmallVector<SDValue, 16> ResultMask;
8374   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8375     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8376 
8377     for (unsigned j = 0; j != BytesPerElement; ++j)
8378       if (isLittleEndian)
8379         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8380                                              dl, MVT::i32));
8381       else
8382         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8383                                              MVT::i32));
8384   }
8385 
8386   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8387   if (isLittleEndian)
8388     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8389                        V2, V1, VPermMask);
8390   else
8391     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8392                        V1, V2, VPermMask);
8393 }
8394 
8395 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8396 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8397 /// information about the intrinsic.
8398 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8399                                  bool &isDot, const PPCSubtarget &Subtarget) {
8400   unsigned IntrinsicID =
8401       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8402   CompareOpc = -1;
8403   isDot = false;
8404   switch (IntrinsicID) {
8405   default:
8406     return false;
8407   // Comparison predicates.
8408   case Intrinsic::ppc_altivec_vcmpbfp_p:
8409     CompareOpc = 966;
8410     isDot = true;
8411     break;
8412   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8413     CompareOpc = 198;
8414     isDot = true;
8415     break;
8416   case Intrinsic::ppc_altivec_vcmpequb_p:
8417     CompareOpc = 6;
8418     isDot = true;
8419     break;
8420   case Intrinsic::ppc_altivec_vcmpequh_p:
8421     CompareOpc = 70;
8422     isDot = true;
8423     break;
8424   case Intrinsic::ppc_altivec_vcmpequw_p:
8425     CompareOpc = 134;
8426     isDot = true;
8427     break;
8428   case Intrinsic::ppc_altivec_vcmpequd_p:
8429     if (Subtarget.hasP8Altivec()) {
8430       CompareOpc = 199;
8431       isDot = true;
8432     } else
8433       return false;
8434     break;
8435   case Intrinsic::ppc_altivec_vcmpneb_p:
8436   case Intrinsic::ppc_altivec_vcmpneh_p:
8437   case Intrinsic::ppc_altivec_vcmpnew_p:
8438   case Intrinsic::ppc_altivec_vcmpnezb_p:
8439   case Intrinsic::ppc_altivec_vcmpnezh_p:
8440   case Intrinsic::ppc_altivec_vcmpnezw_p:
8441     if (Subtarget.hasP9Altivec()) {
8442       switch (IntrinsicID) {
8443       default:
8444         llvm_unreachable("Unknown comparison intrinsic.");
8445       case Intrinsic::ppc_altivec_vcmpneb_p:
8446         CompareOpc = 7;
8447         break;
8448       case Intrinsic::ppc_altivec_vcmpneh_p:
8449         CompareOpc = 71;
8450         break;
8451       case Intrinsic::ppc_altivec_vcmpnew_p:
8452         CompareOpc = 135;
8453         break;
8454       case Intrinsic::ppc_altivec_vcmpnezb_p:
8455         CompareOpc = 263;
8456         break;
8457       case Intrinsic::ppc_altivec_vcmpnezh_p:
8458         CompareOpc = 327;
8459         break;
8460       case Intrinsic::ppc_altivec_vcmpnezw_p:
8461         CompareOpc = 391;
8462         break;
8463       }
8464       isDot = true;
8465     } else
8466       return false;
8467     break;
8468   case Intrinsic::ppc_altivec_vcmpgefp_p:
8469     CompareOpc = 454;
8470     isDot = true;
8471     break;
8472   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8473     CompareOpc = 710;
8474     isDot = true;
8475     break;
8476   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8477     CompareOpc = 774;
8478     isDot = true;
8479     break;
8480   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8481     CompareOpc = 838;
8482     isDot = true;
8483     break;
8484   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8485     CompareOpc = 902;
8486     isDot = true;
8487     break;
8488   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8489     if (Subtarget.hasP8Altivec()) {
8490       CompareOpc = 967;
8491       isDot = true;
8492     } else
8493       return false;
8494     break;
8495   case Intrinsic::ppc_altivec_vcmpgtub_p:
8496     CompareOpc = 518;
8497     isDot = true;
8498     break;
8499   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8500     CompareOpc = 582;
8501     isDot = true;
8502     break;
8503   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8504     CompareOpc = 646;
8505     isDot = true;
8506     break;
8507   case Intrinsic::ppc_altivec_vcmpgtud_p:
8508     if (Subtarget.hasP8Altivec()) {
8509       CompareOpc = 711;
8510       isDot = true;
8511     } else
8512       return false;
8513     break;
8514 
8515   // VSX predicate comparisons use the same infrastructure
8516   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8517   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8518   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8519   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8520   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8521   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8522     if (Subtarget.hasVSX()) {
8523       switch (IntrinsicID) {
8524       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8525         CompareOpc = 99;
8526         break;
8527       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8528         CompareOpc = 115;
8529         break;
8530       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8531         CompareOpc = 107;
8532         break;
8533       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8534         CompareOpc = 67;
8535         break;
8536       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8537         CompareOpc = 83;
8538         break;
8539       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8540         CompareOpc = 75;
8541         break;
8542       }
8543       isDot = true;
8544     } else
8545       return false;
8546     break;
8547 
8548   // Normal Comparisons.
8549   case Intrinsic::ppc_altivec_vcmpbfp:
8550     CompareOpc = 966;
8551     break;
8552   case Intrinsic::ppc_altivec_vcmpeqfp:
8553     CompareOpc = 198;
8554     break;
8555   case Intrinsic::ppc_altivec_vcmpequb:
8556     CompareOpc = 6;
8557     break;
8558   case Intrinsic::ppc_altivec_vcmpequh:
8559     CompareOpc = 70;
8560     break;
8561   case Intrinsic::ppc_altivec_vcmpequw:
8562     CompareOpc = 134;
8563     break;
8564   case Intrinsic::ppc_altivec_vcmpequd:
8565     if (Subtarget.hasP8Altivec())
8566       CompareOpc = 199;
8567     else
8568       return false;
8569     break;
8570   case Intrinsic::ppc_altivec_vcmpneb:
8571   case Intrinsic::ppc_altivec_vcmpneh:
8572   case Intrinsic::ppc_altivec_vcmpnew:
8573   case Intrinsic::ppc_altivec_vcmpnezb:
8574   case Intrinsic::ppc_altivec_vcmpnezh:
8575   case Intrinsic::ppc_altivec_vcmpnezw:
8576     if (Subtarget.hasP9Altivec())
8577       switch (IntrinsicID) {
8578       default:
8579         llvm_unreachable("Unknown comparison intrinsic.");
8580       case Intrinsic::ppc_altivec_vcmpneb:
8581         CompareOpc = 7;
8582         break;
8583       case Intrinsic::ppc_altivec_vcmpneh:
8584         CompareOpc = 71;
8585         break;
8586       case Intrinsic::ppc_altivec_vcmpnew:
8587         CompareOpc = 135;
8588         break;
8589       case Intrinsic::ppc_altivec_vcmpnezb:
8590         CompareOpc = 263;
8591         break;
8592       case Intrinsic::ppc_altivec_vcmpnezh:
8593         CompareOpc = 327;
8594         break;
8595       case Intrinsic::ppc_altivec_vcmpnezw:
8596         CompareOpc = 391;
8597         break;
8598       }
8599     else
8600       return false;
8601     break;
8602   case Intrinsic::ppc_altivec_vcmpgefp:
8603     CompareOpc = 454;
8604     break;
8605   case Intrinsic::ppc_altivec_vcmpgtfp:
8606     CompareOpc = 710;
8607     break;
8608   case Intrinsic::ppc_altivec_vcmpgtsb:
8609     CompareOpc = 774;
8610     break;
8611   case Intrinsic::ppc_altivec_vcmpgtsh:
8612     CompareOpc = 838;
8613     break;
8614   case Intrinsic::ppc_altivec_vcmpgtsw:
8615     CompareOpc = 902;
8616     break;
8617   case Intrinsic::ppc_altivec_vcmpgtsd:
8618     if (Subtarget.hasP8Altivec())
8619       CompareOpc = 967;
8620     else
8621       return false;
8622     break;
8623   case Intrinsic::ppc_altivec_vcmpgtub:
8624     CompareOpc = 518;
8625     break;
8626   case Intrinsic::ppc_altivec_vcmpgtuh:
8627     CompareOpc = 582;
8628     break;
8629   case Intrinsic::ppc_altivec_vcmpgtuw:
8630     CompareOpc = 646;
8631     break;
8632   case Intrinsic::ppc_altivec_vcmpgtud:
8633     if (Subtarget.hasP8Altivec())
8634       CompareOpc = 711;
8635     else
8636       return false;
8637     break;
8638   }
8639   return true;
8640 }
8641 
8642 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8643 /// lower, do it, otherwise return null.
8644 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8645                                                    SelectionDAG &DAG) const {
8646   unsigned IntrinsicID =
8647     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8648 
8649   SDLoc dl(Op);
8650 
8651   if (IntrinsicID == Intrinsic::thread_pointer) {
8652     // Reads the thread pointer register, used for __builtin_thread_pointer.
8653     if (Subtarget.isPPC64())
8654       return DAG.getRegister(PPC::X13, MVT::i64);
8655     return DAG.getRegister(PPC::R2, MVT::i32);
8656   }
8657 
8658   // We are looking for absolute values here.
8659   // The idea is to try to fit one of two patterns:
8660   //  max (a, (0-a))  OR  max ((0-a), a)
8661   if (Subtarget.hasP9Vector() &&
8662       (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8663        IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8664        IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8665     SDValue V1 = Op.getOperand(1);
8666     SDValue V2 = Op.getOperand(2);
8667     if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8668         (V1.getSimpleValueType() == MVT::v4i32 ||
8669          V1.getSimpleValueType() == MVT::v8i16 ||
8670          V1.getSimpleValueType() == MVT::v16i8)) {
8671       if ( V1.getOpcode() == ISD::SUB &&
8672            ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8673            V1.getOperand(1) == V2 ) {
8674         // Generate the abs instruction with the operands
8675         return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8676       }
8677 
8678       if ( V2.getOpcode() == ISD::SUB &&
8679            ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8680            V2.getOperand(1) == V1 ) {
8681         // Generate the abs instruction with the operands
8682         return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8683       }
8684     }
8685   }
8686 
8687   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8688   // opcode number of the comparison.
8689   int CompareOpc;
8690   bool isDot;
8691   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8692     return SDValue();    // Don't custom lower most intrinsics.
8693 
8694   // If this is a non-dot comparison, make the VCMP node and we are done.
8695   if (!isDot) {
8696     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8697                               Op.getOperand(1), Op.getOperand(2),
8698                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8699     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8700   }
8701 
8702   // Create the PPCISD altivec 'dot' comparison node.
8703   SDValue Ops[] = {
8704     Op.getOperand(2),  // LHS
8705     Op.getOperand(3),  // RHS
8706     DAG.getConstant(CompareOpc, dl, MVT::i32)
8707   };
8708   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8709   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8710 
8711   // Now that we have the comparison, emit a copy from the CR to a GPR.
8712   // This is flagged to the above dot comparison.
8713   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8714                                 DAG.getRegister(PPC::CR6, MVT::i32),
8715                                 CompNode.getValue(1));
8716 
8717   // Unpack the result based on how the target uses it.
8718   unsigned BitNo;   // Bit # of CR6.
8719   bool InvertBit;   // Invert result?
8720   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8721   default:  // Can't happen, don't crash on invalid number though.
8722   case 0:   // Return the value of the EQ bit of CR6.
8723     BitNo = 0; InvertBit = false;
8724     break;
8725   case 1:   // Return the inverted value of the EQ bit of CR6.
8726     BitNo = 0; InvertBit = true;
8727     break;
8728   case 2:   // Return the value of the LT bit of CR6.
8729     BitNo = 2; InvertBit = false;
8730     break;
8731   case 3:   // Return the inverted value of the LT bit of CR6.
8732     BitNo = 2; InvertBit = true;
8733     break;
8734   }
8735 
8736   // Shift the bit into the low position.
8737   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8738                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8739   // Isolate the bit.
8740   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8741                       DAG.getConstant(1, dl, MVT::i32));
8742 
8743   // If we are supposed to, toggle the bit.
8744   if (InvertBit)
8745     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8746                         DAG.getConstant(1, dl, MVT::i32));
8747   return Flags;
8748 }
8749 
8750 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8751                                                SelectionDAG &DAG) const {
8752   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8753   // the beginning of the argument list.
8754   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8755   SDLoc DL(Op);
8756   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8757   case Intrinsic::ppc_cfence: {
8758     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8759     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8760     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8761                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8762                                                   Op.getOperand(ArgStart + 1)),
8763                                       Op.getOperand(0)),
8764                    0);
8765   }
8766   default:
8767     break;
8768   }
8769   return SDValue();
8770 }
8771 
8772 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
8773   // Check for a DIV with the same operands as this REM.
8774   for (auto UI : Op.getOperand(1)->uses()) {
8775     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
8776         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
8777       if (UI->getOperand(0) == Op.getOperand(0) &&
8778           UI->getOperand(1) == Op.getOperand(1))
8779         return SDValue();
8780   }
8781   return Op;
8782 }
8783 
8784 // Lower scalar BSWAP64 to xxbrd.
8785 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
8786   SDLoc dl(Op);
8787   // MTVSRDD
8788   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
8789                    Op.getOperand(0));
8790   // XXBRD
8791   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
8792   // MFVSRD
8793   int VectorIndex = 0;
8794   if (Subtarget.isLittleEndian())
8795     VectorIndex = 1;
8796   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
8797                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
8798   return Op;
8799 }
8800 
8801 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8802                                                   SelectionDAG &DAG) const {
8803   SDLoc dl(Op);
8804   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8805   // instructions), but for smaller types, we need to first extend up to v2i32
8806   // before doing going farther.
8807   if (Op.getValueType() == MVT::v2i64) {
8808     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8809     if (ExtVT != MVT::v2i32) {
8810       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8811       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8812                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8813                                         ExtVT.getVectorElementType(), 4)));
8814       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8815       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8816                        DAG.getValueType(MVT::v2i32));
8817     }
8818 
8819     return Op;
8820   }
8821 
8822   return SDValue();
8823 }
8824 
8825 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8826                                                  SelectionDAG &DAG) const {
8827   SDLoc dl(Op);
8828   // Create a stack slot that is 16-byte aligned.
8829   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8830   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8831   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8832   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8833 
8834   // Store the input value into Value#0 of the stack slot.
8835   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8836                                MachinePointerInfo());
8837   // Load it out.
8838   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8839 }
8840 
8841 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8842                                                   SelectionDAG &DAG) const {
8843   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8844          "Should only be called for ISD::INSERT_VECTOR_ELT");
8845   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8846   // We have legal lowering for constant indices but not for variable ones.
8847   if (C)
8848     return Op;
8849   return SDValue();
8850 }
8851 
8852 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8853                                                    SelectionDAG &DAG) const {
8854   SDLoc dl(Op);
8855   SDNode *N = Op.getNode();
8856 
8857   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8858          "Unknown extract_vector_elt type");
8859 
8860   SDValue Value = N->getOperand(0);
8861 
8862   // The first part of this is like the store lowering except that we don't
8863   // need to track the chain.
8864 
8865   // The values are now known to be -1 (false) or 1 (true). To convert this
8866   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8867   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8868   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8869 
8870   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8871   // understand how to form the extending load.
8872   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8873 
8874   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8875 
8876   // Now convert to an integer and store.
8877   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8878     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8879     Value);
8880 
8881   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8882   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8883   MachinePointerInfo PtrInfo =
8884       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8885   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8886   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8887 
8888   SDValue StoreChain = DAG.getEntryNode();
8889   SDValue Ops[] = {StoreChain,
8890                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8891                    Value, FIdx};
8892   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8893 
8894   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8895     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8896 
8897   // Extract the value requested.
8898   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8899   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8900   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8901 
8902   SDValue IntVal =
8903       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8904 
8905   if (!Subtarget.useCRBits())
8906     return IntVal;
8907 
8908   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8909 }
8910 
8911 /// Lowering for QPX v4i1 loads
8912 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8913                                            SelectionDAG &DAG) const {
8914   SDLoc dl(Op);
8915   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8916   SDValue LoadChain = LN->getChain();
8917   SDValue BasePtr = LN->getBasePtr();
8918 
8919   if (Op.getValueType() == MVT::v4f64 ||
8920       Op.getValueType() == MVT::v4f32) {
8921     EVT MemVT = LN->getMemoryVT();
8922     unsigned Alignment = LN->getAlignment();
8923 
8924     // If this load is properly aligned, then it is legal.
8925     if (Alignment >= MemVT.getStoreSize())
8926       return Op;
8927 
8928     EVT ScalarVT = Op.getValueType().getScalarType(),
8929         ScalarMemVT = MemVT.getScalarType();
8930     unsigned Stride = ScalarMemVT.getStoreSize();
8931 
8932     SDValue Vals[4], LoadChains[4];
8933     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8934       SDValue Load;
8935       if (ScalarVT != ScalarMemVT)
8936         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8937                               BasePtr,
8938                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8939                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8940                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8941       else
8942         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8943                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8944                            MinAlign(Alignment, Idx * Stride),
8945                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8946 
8947       if (Idx == 0 && LN->isIndexed()) {
8948         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8949                "Unknown addressing mode on vector load");
8950         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8951                                   LN->getAddressingMode());
8952       }
8953 
8954       Vals[Idx] = Load;
8955       LoadChains[Idx] = Load.getValue(1);
8956 
8957       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8958                             DAG.getConstant(Stride, dl,
8959                                             BasePtr.getValueType()));
8960     }
8961 
8962     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8963     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8964 
8965     if (LN->isIndexed()) {
8966       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8967       return DAG.getMergeValues(RetOps, dl);
8968     }
8969 
8970     SDValue RetOps[] = { Value, TF };
8971     return DAG.getMergeValues(RetOps, dl);
8972   }
8973 
8974   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8975   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8976 
8977   // To lower v4i1 from a byte array, we load the byte elements of the
8978   // vector and then reuse the BUILD_VECTOR logic.
8979 
8980   SDValue VectElmts[4], VectElmtChains[4];
8981   for (unsigned i = 0; i < 4; ++i) {
8982     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8983     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8984 
8985     VectElmts[i] = DAG.getExtLoad(
8986         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8987         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8988         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8989     VectElmtChains[i] = VectElmts[i].getValue(1);
8990   }
8991 
8992   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8993   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8994 
8995   SDValue RVals[] = { Value, LoadChain };
8996   return DAG.getMergeValues(RVals, dl);
8997 }
8998 
8999 /// Lowering for QPX v4i1 stores
9000 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9001                                             SelectionDAG &DAG) const {
9002   SDLoc dl(Op);
9003   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9004   SDValue StoreChain = SN->getChain();
9005   SDValue BasePtr = SN->getBasePtr();
9006   SDValue Value = SN->getValue();
9007 
9008   if (Value.getValueType() == MVT::v4f64 ||
9009       Value.getValueType() == MVT::v4f32) {
9010     EVT MemVT = SN->getMemoryVT();
9011     unsigned Alignment = SN->getAlignment();
9012 
9013     // If this store is properly aligned, then it is legal.
9014     if (Alignment >= MemVT.getStoreSize())
9015       return Op;
9016 
9017     EVT ScalarVT = Value.getValueType().getScalarType(),
9018         ScalarMemVT = MemVT.getScalarType();
9019     unsigned Stride = ScalarMemVT.getStoreSize();
9020 
9021     SDValue Stores[4];
9022     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9023       SDValue Ex = DAG.getNode(
9024           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9025           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9026       SDValue Store;
9027       if (ScalarVT != ScalarMemVT)
9028         Store =
9029             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9030                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9031                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9032                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9033       else
9034         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9035                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9036                              MinAlign(Alignment, Idx * Stride),
9037                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9038 
9039       if (Idx == 0 && SN->isIndexed()) {
9040         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9041                "Unknown addressing mode on vector store");
9042         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9043                                     SN->getAddressingMode());
9044       }
9045 
9046       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9047                             DAG.getConstant(Stride, dl,
9048                                             BasePtr.getValueType()));
9049       Stores[Idx] = Store;
9050     }
9051 
9052     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9053 
9054     if (SN->isIndexed()) {
9055       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9056       return DAG.getMergeValues(RetOps, dl);
9057     }
9058 
9059     return TF;
9060   }
9061 
9062   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9063   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9064 
9065   // The values are now known to be -1 (false) or 1 (true). To convert this
9066   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9067   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9068   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9069 
9070   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9071   // understand how to form the extending load.
9072   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9073 
9074   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9075 
9076   // Now convert to an integer and store.
9077   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9078     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9079     Value);
9080 
9081   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9082   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9083   MachinePointerInfo PtrInfo =
9084       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9085   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9086   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9087 
9088   SDValue Ops[] = {StoreChain,
9089                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9090                    Value, FIdx};
9091   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9092 
9093   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9094     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9095 
9096   // Move data into the byte array.
9097   SDValue Loads[4], LoadChains[4];
9098   for (unsigned i = 0; i < 4; ++i) {
9099     unsigned Offset = 4*i;
9100     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9101     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9102 
9103     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9104                            PtrInfo.getWithOffset(Offset));
9105     LoadChains[i] = Loads[i].getValue(1);
9106   }
9107 
9108   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9109 
9110   SDValue Stores[4];
9111   for (unsigned i = 0; i < 4; ++i) {
9112     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9113     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9114 
9115     Stores[i] = DAG.getTruncStore(
9116         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9117         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9118         SN->getAAInfo());
9119   }
9120 
9121   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9122 
9123   return StoreChain;
9124 }
9125 
9126 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9127   SDLoc dl(Op);
9128   if (Op.getValueType() == MVT::v4i32) {
9129     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9130 
9131     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9132     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9133 
9134     SDValue RHSSwap =   // = vrlw RHS, 16
9135       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9136 
9137     // Shrinkify inputs to v8i16.
9138     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9139     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9140     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9141 
9142     // Low parts multiplied together, generating 32-bit results (we ignore the
9143     // top parts).
9144     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9145                                         LHS, RHS, DAG, dl, MVT::v4i32);
9146 
9147     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9148                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9149     // Shift the high parts up 16 bits.
9150     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9151                               Neg16, DAG, dl);
9152     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9153   } else if (Op.getValueType() == MVT::v8i16) {
9154     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9155 
9156     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9157 
9158     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9159                             LHS, RHS, Zero, DAG, dl);
9160   } else if (Op.getValueType() == MVT::v16i8) {
9161     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9162     bool isLittleEndian = Subtarget.isLittleEndian();
9163 
9164     // Multiply the even 8-bit parts, producing 16-bit sums.
9165     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9166                                            LHS, RHS, DAG, dl, MVT::v8i16);
9167     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9168 
9169     // Multiply the odd 8-bit parts, producing 16-bit sums.
9170     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9171                                           LHS, RHS, DAG, dl, MVT::v8i16);
9172     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9173 
9174     // Merge the results together.  Because vmuleub and vmuloub are
9175     // instructions with a big-endian bias, we must reverse the
9176     // element numbering and reverse the meaning of "odd" and "even"
9177     // when generating little endian code.
9178     int Ops[16];
9179     for (unsigned i = 0; i != 8; ++i) {
9180       if (isLittleEndian) {
9181         Ops[i*2  ] = 2*i;
9182         Ops[i*2+1] = 2*i+16;
9183       } else {
9184         Ops[i*2  ] = 2*i+1;
9185         Ops[i*2+1] = 2*i+1+16;
9186       }
9187     }
9188     if (isLittleEndian)
9189       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9190     else
9191       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9192   } else {
9193     llvm_unreachable("Unknown mul to lower!");
9194   }
9195 }
9196 
9197 /// LowerOperation - Provide custom lowering hooks for some operations.
9198 ///
9199 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9200   switch (Op.getOpcode()) {
9201   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9202   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9203   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9204   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9205   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9206   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9207   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9208   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9209   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9210   case ISD::VASTART:
9211     return LowerVASTART(Op, DAG);
9212 
9213   case ISD::VAARG:
9214     return LowerVAARG(Op, DAG);
9215 
9216   case ISD::VACOPY:
9217     return LowerVACOPY(Op, DAG);
9218 
9219   case ISD::STACKRESTORE:
9220     return LowerSTACKRESTORE(Op, DAG);
9221 
9222   case ISD::DYNAMIC_STACKALLOC:
9223     return LowerDYNAMIC_STACKALLOC(Op, DAG);
9224 
9225   case ISD::GET_DYNAMIC_AREA_OFFSET:
9226     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9227 
9228   case ISD::EH_DWARF_CFA:
9229     return LowerEH_DWARF_CFA(Op, DAG);
9230 
9231   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9232   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9233 
9234   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9235   case ISD::STORE:              return LowerSTORE(Op, DAG);
9236   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9237   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9238   case ISD::FP_TO_UINT:
9239   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
9240                                                       SDLoc(Op));
9241   case ISD::UINT_TO_FP:
9242   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9243   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9244 
9245   // Lower 64-bit shifts.
9246   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9247   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9248   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9249 
9250   // Vector-related lowering.
9251   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9252   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9253   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9254   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9255   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
9256   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9257   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9258   case ISD::MUL:                return LowerMUL(Op, DAG);
9259 
9260   // For counter-based loop handling.
9261   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9262 
9263   // Frame & Return address.
9264   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9265   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9266 
9267   case ISD::INTRINSIC_VOID:
9268     return LowerINTRINSIC_VOID(Op, DAG);
9269   case ISD::SREM:
9270   case ISD::UREM:
9271     return LowerREM(Op, DAG);
9272   case ISD::BSWAP:
9273     return LowerBSWAP(Op, DAG);
9274   }
9275 }
9276 
9277 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9278                                            SmallVectorImpl<SDValue>&Results,
9279                                            SelectionDAG &DAG) const {
9280   SDLoc dl(N);
9281   switch (N->getOpcode()) {
9282   default:
9283     llvm_unreachable("Do not know how to custom type legalize this operation!");
9284   case ISD::READCYCLECOUNTER: {
9285     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9286     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9287 
9288     Results.push_back(RTB);
9289     Results.push_back(RTB.getValue(1));
9290     Results.push_back(RTB.getValue(2));
9291     break;
9292   }
9293   case ISD::INTRINSIC_W_CHAIN: {
9294     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9295         Intrinsic::ppc_is_decremented_ctr_nonzero)
9296       break;
9297 
9298     assert(N->getValueType(0) == MVT::i1 &&
9299            "Unexpected result type for CTR decrement intrinsic");
9300     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9301                                  N->getValueType(0));
9302     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9303     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9304                                  N->getOperand(1));
9305 
9306     Results.push_back(NewInt);
9307     Results.push_back(NewInt.getValue(1));
9308     break;
9309   }
9310   case ISD::VAARG: {
9311     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9312       return;
9313 
9314     EVT VT = N->getValueType(0);
9315 
9316     if (VT == MVT::i64) {
9317       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9318 
9319       Results.push_back(NewNode);
9320       Results.push_back(NewNode.getValue(1));
9321     }
9322     return;
9323   }
9324   case ISD::FP_ROUND_INREG: {
9325     assert(N->getValueType(0) == MVT::ppcf128);
9326     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
9327     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
9328                              MVT::f64, N->getOperand(0),
9329                              DAG.getIntPtrConstant(0, dl));
9330     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
9331                              MVT::f64, N->getOperand(0),
9332                              DAG.getIntPtrConstant(1, dl));
9333 
9334     // Add the two halves of the long double in round-to-zero mode.
9335     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
9336 
9337     // We know the low half is about to be thrown away, so just use something
9338     // convenient.
9339     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
9340                                 FPreg, FPreg));
9341     return;
9342   }
9343   case ISD::FP_TO_SINT:
9344   case ISD::FP_TO_UINT:
9345     // LowerFP_TO_INT() can only handle f32 and f64.
9346     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9347       return;
9348     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9349     return;
9350   }
9351 }
9352 
9353 //===----------------------------------------------------------------------===//
9354 //  Other Lowering Code
9355 //===----------------------------------------------------------------------===//
9356 
9357 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9358   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9359   Function *Func = Intrinsic::getDeclaration(M, Id);
9360   return Builder.CreateCall(Func, {});
9361 }
9362 
9363 // The mappings for emitLeading/TrailingFence is taken from
9364 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9365 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9366                                                  Instruction *Inst,
9367                                                  AtomicOrdering Ord) const {
9368   if (Ord == AtomicOrdering::SequentiallyConsistent)
9369     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9370   if (isReleaseOrStronger(Ord))
9371     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9372   return nullptr;
9373 }
9374 
9375 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9376                                                   Instruction *Inst,
9377                                                   AtomicOrdering Ord) const {
9378   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9379     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9380     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9381     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9382     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9383       return Builder.CreateCall(
9384           Intrinsic::getDeclaration(
9385               Builder.GetInsertBlock()->getParent()->getParent(),
9386               Intrinsic::ppc_cfence, {Inst->getType()}),
9387           {Inst});
9388     // FIXME: Can use isync for rmw operation.
9389     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9390   }
9391   return nullptr;
9392 }
9393 
9394 MachineBasicBlock *
9395 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9396                                     unsigned AtomicSize,
9397                                     unsigned BinOpcode,
9398                                     unsigned CmpOpcode,
9399                                     unsigned CmpPred) const {
9400   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9401   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9402 
9403   auto LoadMnemonic = PPC::LDARX;
9404   auto StoreMnemonic = PPC::STDCX;
9405   switch (AtomicSize) {
9406   default:
9407     llvm_unreachable("Unexpected size of atomic entity");
9408   case 1:
9409     LoadMnemonic = PPC::LBARX;
9410     StoreMnemonic = PPC::STBCX;
9411     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9412     break;
9413   case 2:
9414     LoadMnemonic = PPC::LHARX;
9415     StoreMnemonic = PPC::STHCX;
9416     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9417     break;
9418   case 4:
9419     LoadMnemonic = PPC::LWARX;
9420     StoreMnemonic = PPC::STWCX;
9421     break;
9422   case 8:
9423     LoadMnemonic = PPC::LDARX;
9424     StoreMnemonic = PPC::STDCX;
9425     break;
9426   }
9427 
9428   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9429   MachineFunction *F = BB->getParent();
9430   MachineFunction::iterator It = ++BB->getIterator();
9431 
9432   unsigned dest = MI.getOperand(0).getReg();
9433   unsigned ptrA = MI.getOperand(1).getReg();
9434   unsigned ptrB = MI.getOperand(2).getReg();
9435   unsigned incr = MI.getOperand(3).getReg();
9436   DebugLoc dl = MI.getDebugLoc();
9437 
9438   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9439   MachineBasicBlock *loop2MBB =
9440     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9441   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9442   F->insert(It, loopMBB);
9443   if (CmpOpcode)
9444     F->insert(It, loop2MBB);
9445   F->insert(It, exitMBB);
9446   exitMBB->splice(exitMBB->begin(), BB,
9447                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9448   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9449 
9450   MachineRegisterInfo &RegInfo = F->getRegInfo();
9451   unsigned TmpReg = (!BinOpcode) ? incr :
9452     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9453                                            : &PPC::GPRCRegClass);
9454 
9455   //  thisMBB:
9456   //   ...
9457   //   fallthrough --> loopMBB
9458   BB->addSuccessor(loopMBB);
9459 
9460   //  loopMBB:
9461   //   l[wd]arx dest, ptr
9462   //   add r0, dest, incr
9463   //   st[wd]cx. r0, ptr
9464   //   bne- loopMBB
9465   //   fallthrough --> exitMBB
9466 
9467   // For max/min...
9468   //  loopMBB:
9469   //   l[wd]arx dest, ptr
9470   //   cmpl?[wd] incr, dest
9471   //   bgt exitMBB
9472   //  loop2MBB:
9473   //   st[wd]cx. dest, ptr
9474   //   bne- loopMBB
9475   //   fallthrough --> exitMBB
9476 
9477   BB = loopMBB;
9478   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9479     .addReg(ptrA).addReg(ptrB);
9480   if (BinOpcode)
9481     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9482   if (CmpOpcode) {
9483     // Signed comparisons of byte or halfword values must be sign-extended.
9484     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9485       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9486       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9487               ExtReg).addReg(dest);
9488       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9489         .addReg(incr).addReg(ExtReg);
9490     } else
9491       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9492         .addReg(incr).addReg(dest);
9493 
9494     BuildMI(BB, dl, TII->get(PPC::BCC))
9495       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9496     BB->addSuccessor(loop2MBB);
9497     BB->addSuccessor(exitMBB);
9498     BB = loop2MBB;
9499   }
9500   BuildMI(BB, dl, TII->get(StoreMnemonic))
9501     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9502   BuildMI(BB, dl, TII->get(PPC::BCC))
9503     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9504   BB->addSuccessor(loopMBB);
9505   BB->addSuccessor(exitMBB);
9506 
9507   //  exitMBB:
9508   //   ...
9509   BB = exitMBB;
9510   return BB;
9511 }
9512 
9513 MachineBasicBlock *
9514 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9515                                             MachineBasicBlock *BB,
9516                                             bool is8bit, // operation
9517                                             unsigned BinOpcode,
9518                                             unsigned CmpOpcode,
9519                                             unsigned CmpPred) const {
9520   // If we support part-word atomic mnemonics, just use them
9521   if (Subtarget.hasPartwordAtomics())
9522     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9523                             CmpOpcode, CmpPred);
9524 
9525   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9526   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9527   // In 64 bit mode we have to use 64 bits for addresses, even though the
9528   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9529   // registers without caring whether they're 32 or 64, but here we're
9530   // doing actual arithmetic on the addresses.
9531   bool is64bit = Subtarget.isPPC64();
9532   bool isLittleEndian = Subtarget.isLittleEndian();
9533   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9534 
9535   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9536   MachineFunction *F = BB->getParent();
9537   MachineFunction::iterator It = ++BB->getIterator();
9538 
9539   unsigned dest = MI.getOperand(0).getReg();
9540   unsigned ptrA = MI.getOperand(1).getReg();
9541   unsigned ptrB = MI.getOperand(2).getReg();
9542   unsigned incr = MI.getOperand(3).getReg();
9543   DebugLoc dl = MI.getDebugLoc();
9544 
9545   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9546   MachineBasicBlock *loop2MBB =
9547     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9548   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9549   F->insert(It, loopMBB);
9550   if (CmpOpcode)
9551     F->insert(It, loop2MBB);
9552   F->insert(It, exitMBB);
9553   exitMBB->splice(exitMBB->begin(), BB,
9554                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9555   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9556 
9557   MachineRegisterInfo &RegInfo = F->getRegInfo();
9558   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9559                                           : &PPC::GPRCRegClass;
9560   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9561   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9562   unsigned ShiftReg =
9563     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9564   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9565   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9566   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9567   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9568   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9569   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9570   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9571   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9572   unsigned Ptr1Reg;
9573   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9574 
9575   //  thisMBB:
9576   //   ...
9577   //   fallthrough --> loopMBB
9578   BB->addSuccessor(loopMBB);
9579 
9580   // The 4-byte load must be aligned, while a char or short may be
9581   // anywhere in the word.  Hence all this nasty bookkeeping code.
9582   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9583   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9584   //   xori shift, shift1, 24 [16]
9585   //   rlwinm ptr, ptr1, 0, 0, 29
9586   //   slw incr2, incr, shift
9587   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9588   //   slw mask, mask2, shift
9589   //  loopMBB:
9590   //   lwarx tmpDest, ptr
9591   //   add tmp, tmpDest, incr2
9592   //   andc tmp2, tmpDest, mask
9593   //   and tmp3, tmp, mask
9594   //   or tmp4, tmp3, tmp2
9595   //   stwcx. tmp4, ptr
9596   //   bne- loopMBB
9597   //   fallthrough --> exitMBB
9598   //   srw dest, tmpDest, shift
9599   if (ptrA != ZeroReg) {
9600     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9601     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9602       .addReg(ptrA).addReg(ptrB);
9603   } else {
9604     Ptr1Reg = ptrB;
9605   }
9606   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9607       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9608   if (!isLittleEndian)
9609     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9610         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9611   if (is64bit)
9612     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9613       .addReg(Ptr1Reg).addImm(0).addImm(61);
9614   else
9615     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9616       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9617   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9618       .addReg(incr).addReg(ShiftReg);
9619   if (is8bit)
9620     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9621   else {
9622     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9623     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9624   }
9625   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9626       .addReg(Mask2Reg).addReg(ShiftReg);
9627 
9628   BB = loopMBB;
9629   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9630     .addReg(ZeroReg).addReg(PtrReg);
9631   if (BinOpcode)
9632     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9633       .addReg(Incr2Reg).addReg(TmpDestReg);
9634   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9635     .addReg(TmpDestReg).addReg(MaskReg);
9636   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9637     .addReg(TmpReg).addReg(MaskReg);
9638   if (CmpOpcode) {
9639     // For unsigned comparisons, we can directly compare the shifted values.
9640     // For signed comparisons we shift and sign extend.
9641     unsigned SReg = RegInfo.createVirtualRegister(RC);
9642     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9643       .addReg(TmpDestReg).addReg(MaskReg);
9644     unsigned ValueReg = SReg;
9645     unsigned CmpReg = Incr2Reg;
9646     if (CmpOpcode == PPC::CMPW) {
9647       ValueReg = RegInfo.createVirtualRegister(RC);
9648       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9649         .addReg(SReg).addReg(ShiftReg);
9650       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9651       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9652         .addReg(ValueReg);
9653       ValueReg = ValueSReg;
9654       CmpReg = incr;
9655     }
9656     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9657       .addReg(CmpReg).addReg(ValueReg);
9658     BuildMI(BB, dl, TII->get(PPC::BCC))
9659       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9660     BB->addSuccessor(loop2MBB);
9661     BB->addSuccessor(exitMBB);
9662     BB = loop2MBB;
9663   }
9664   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9665     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9666   BuildMI(BB, dl, TII->get(PPC::STWCX))
9667     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9668   BuildMI(BB, dl, TII->get(PPC::BCC))
9669     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9670   BB->addSuccessor(loopMBB);
9671   BB->addSuccessor(exitMBB);
9672 
9673   //  exitMBB:
9674   //   ...
9675   BB = exitMBB;
9676   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9677     .addReg(ShiftReg);
9678   return BB;
9679 }
9680 
9681 llvm::MachineBasicBlock *
9682 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9683                                     MachineBasicBlock *MBB) const {
9684   DebugLoc DL = MI.getDebugLoc();
9685   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9686   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9687 
9688   MachineFunction *MF = MBB->getParent();
9689   MachineRegisterInfo &MRI = MF->getRegInfo();
9690 
9691   const BasicBlock *BB = MBB->getBasicBlock();
9692   MachineFunction::iterator I = ++MBB->getIterator();
9693 
9694   // Memory Reference
9695   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9696   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9697 
9698   unsigned DstReg = MI.getOperand(0).getReg();
9699   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9700   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9701   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9702   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9703 
9704   MVT PVT = getPointerTy(MF->getDataLayout());
9705   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9706          "Invalid Pointer Size!");
9707   // For v = setjmp(buf), we generate
9708   //
9709   // thisMBB:
9710   //  SjLjSetup mainMBB
9711   //  bl mainMBB
9712   //  v_restore = 1
9713   //  b sinkMBB
9714   //
9715   // mainMBB:
9716   //  buf[LabelOffset] = LR
9717   //  v_main = 0
9718   //
9719   // sinkMBB:
9720   //  v = phi(main, restore)
9721   //
9722 
9723   MachineBasicBlock *thisMBB = MBB;
9724   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9725   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9726   MF->insert(I, mainMBB);
9727   MF->insert(I, sinkMBB);
9728 
9729   MachineInstrBuilder MIB;
9730 
9731   // Transfer the remainder of BB and its successor edges to sinkMBB.
9732   sinkMBB->splice(sinkMBB->begin(), MBB,
9733                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9734   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9735 
9736   // Note that the structure of the jmp_buf used here is not compatible
9737   // with that used by libc, and is not designed to be. Specifically, it
9738   // stores only those 'reserved' registers that LLVM does not otherwise
9739   // understand how to spill. Also, by convention, by the time this
9740   // intrinsic is called, Clang has already stored the frame address in the
9741   // first slot of the buffer and stack address in the third. Following the
9742   // X86 target code, we'll store the jump address in the second slot. We also
9743   // need to save the TOC pointer (R2) to handle jumps between shared
9744   // libraries, and that will be stored in the fourth slot. The thread
9745   // identifier (R13) is not affected.
9746 
9747   // thisMBB:
9748   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9749   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9750   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9751 
9752   // Prepare IP either in reg.
9753   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9754   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9755   unsigned BufReg = MI.getOperand(1).getReg();
9756 
9757   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9758     setUsesTOCBasePtr(*MBB->getParent());
9759     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9760             .addReg(PPC::X2)
9761             .addImm(TOCOffset)
9762             .addReg(BufReg);
9763     MIB.setMemRefs(MMOBegin, MMOEnd);
9764   }
9765 
9766   // Naked functions never have a base pointer, and so we use r1. For all
9767   // other functions, this decision must be delayed until during PEI.
9768   unsigned BaseReg;
9769   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9770     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9771   else
9772     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9773 
9774   MIB = BuildMI(*thisMBB, MI, DL,
9775                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9776             .addReg(BaseReg)
9777             .addImm(BPOffset)
9778             .addReg(BufReg);
9779   MIB.setMemRefs(MMOBegin, MMOEnd);
9780 
9781   // Setup
9782   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9783   MIB.addRegMask(TRI->getNoPreservedMask());
9784 
9785   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9786 
9787   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9788           .addMBB(mainMBB);
9789   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9790 
9791   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9792   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9793 
9794   // mainMBB:
9795   //  mainDstReg = 0
9796   MIB =
9797       BuildMI(mainMBB, DL,
9798               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9799 
9800   // Store IP
9801   if (Subtarget.isPPC64()) {
9802     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9803             .addReg(LabelReg)
9804             .addImm(LabelOffset)
9805             .addReg(BufReg);
9806   } else {
9807     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9808             .addReg(LabelReg)
9809             .addImm(LabelOffset)
9810             .addReg(BufReg);
9811   }
9812 
9813   MIB.setMemRefs(MMOBegin, MMOEnd);
9814 
9815   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9816   mainMBB->addSuccessor(sinkMBB);
9817 
9818   // sinkMBB:
9819   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9820           TII->get(PPC::PHI), DstReg)
9821     .addReg(mainDstReg).addMBB(mainMBB)
9822     .addReg(restoreDstReg).addMBB(thisMBB);
9823 
9824   MI.eraseFromParent();
9825   return sinkMBB;
9826 }
9827 
9828 MachineBasicBlock *
9829 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9830                                      MachineBasicBlock *MBB) const {
9831   DebugLoc DL = MI.getDebugLoc();
9832   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9833 
9834   MachineFunction *MF = MBB->getParent();
9835   MachineRegisterInfo &MRI = MF->getRegInfo();
9836 
9837   // Memory Reference
9838   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9839   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9840 
9841   MVT PVT = getPointerTy(MF->getDataLayout());
9842   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9843          "Invalid Pointer Size!");
9844 
9845   const TargetRegisterClass *RC =
9846     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9847   unsigned Tmp = MRI.createVirtualRegister(RC);
9848   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9849   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9850   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9851   unsigned BP =
9852       (PVT == MVT::i64)
9853           ? PPC::X30
9854           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9855                                                               : PPC::R30);
9856 
9857   MachineInstrBuilder MIB;
9858 
9859   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9860   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9861   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9862   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9863 
9864   unsigned BufReg = MI.getOperand(0).getReg();
9865 
9866   // Reload FP (the jumped-to function may not have had a
9867   // frame pointer, and if so, then its r31 will be restored
9868   // as necessary).
9869   if (PVT == MVT::i64) {
9870     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9871             .addImm(0)
9872             .addReg(BufReg);
9873   } else {
9874     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9875             .addImm(0)
9876             .addReg(BufReg);
9877   }
9878   MIB.setMemRefs(MMOBegin, MMOEnd);
9879 
9880   // Reload IP
9881   if (PVT == MVT::i64) {
9882     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9883             .addImm(LabelOffset)
9884             .addReg(BufReg);
9885   } else {
9886     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9887             .addImm(LabelOffset)
9888             .addReg(BufReg);
9889   }
9890   MIB.setMemRefs(MMOBegin, MMOEnd);
9891 
9892   // Reload SP
9893   if (PVT == MVT::i64) {
9894     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9895             .addImm(SPOffset)
9896             .addReg(BufReg);
9897   } else {
9898     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9899             .addImm(SPOffset)
9900             .addReg(BufReg);
9901   }
9902   MIB.setMemRefs(MMOBegin, MMOEnd);
9903 
9904   // Reload BP
9905   if (PVT == MVT::i64) {
9906     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9907             .addImm(BPOffset)
9908             .addReg(BufReg);
9909   } else {
9910     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9911             .addImm(BPOffset)
9912             .addReg(BufReg);
9913   }
9914   MIB.setMemRefs(MMOBegin, MMOEnd);
9915 
9916   // Reload TOC
9917   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9918     setUsesTOCBasePtr(*MBB->getParent());
9919     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9920             .addImm(TOCOffset)
9921             .addReg(BufReg);
9922 
9923     MIB.setMemRefs(MMOBegin, MMOEnd);
9924   }
9925 
9926   // Jump
9927   BuildMI(*MBB, MI, DL,
9928           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9929   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9930 
9931   MI.eraseFromParent();
9932   return MBB;
9933 }
9934 
9935 MachineBasicBlock *
9936 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9937                                                MachineBasicBlock *BB) const {
9938   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9939       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9940     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9941         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9942       // Call lowering should have added an r2 operand to indicate a dependence
9943       // on the TOC base pointer value. It can't however, because there is no
9944       // way to mark the dependence as implicit there, and so the stackmap code
9945       // will confuse it with a regular operand. Instead, add the dependence
9946       // here.
9947       setUsesTOCBasePtr(*BB->getParent());
9948       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9949     }
9950 
9951     return emitPatchPoint(MI, BB);
9952   }
9953 
9954   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9955       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9956     return emitEHSjLjSetJmp(MI, BB);
9957   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9958              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9959     return emitEHSjLjLongJmp(MI, BB);
9960   }
9961 
9962   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9963 
9964   // To "insert" these instructions we actually have to insert their
9965   // control-flow patterns.
9966   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9967   MachineFunction::iterator It = ++BB->getIterator();
9968 
9969   MachineFunction *F = BB->getParent();
9970 
9971   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9972        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9973        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9974     SmallVector<MachineOperand, 2> Cond;
9975     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9976         MI.getOpcode() == PPC::SELECT_CC_I8)
9977       Cond.push_back(MI.getOperand(4));
9978     else
9979       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9980     Cond.push_back(MI.getOperand(1));
9981 
9982     DebugLoc dl = MI.getDebugLoc();
9983     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9984                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9985   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9986              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9987              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9988              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9989              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9990              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9991              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9992              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9993              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9994              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9995              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9996              MI.getOpcode() == PPC::SELECT_I4 ||
9997              MI.getOpcode() == PPC::SELECT_I8 ||
9998              MI.getOpcode() == PPC::SELECT_F4 ||
9999              MI.getOpcode() == PPC::SELECT_F8 ||
10000              MI.getOpcode() == PPC::SELECT_QFRC ||
10001              MI.getOpcode() == PPC::SELECT_QSRC ||
10002              MI.getOpcode() == PPC::SELECT_QBRC ||
10003              MI.getOpcode() == PPC::SELECT_VRRC ||
10004              MI.getOpcode() == PPC::SELECT_VSFRC ||
10005              MI.getOpcode() == PPC::SELECT_VSSRC ||
10006              MI.getOpcode() == PPC::SELECT_VSRC) {
10007     // The incoming instruction knows the destination vreg to set, the
10008     // condition code register to branch on, the true/false values to
10009     // select between, and a branch opcode to use.
10010 
10011     //  thisMBB:
10012     //  ...
10013     //   TrueVal = ...
10014     //   cmpTY ccX, r1, r2
10015     //   bCC copy1MBB
10016     //   fallthrough --> copy0MBB
10017     MachineBasicBlock *thisMBB = BB;
10018     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10019     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10020     DebugLoc dl = MI.getDebugLoc();
10021     F->insert(It, copy0MBB);
10022     F->insert(It, sinkMBB);
10023 
10024     // Transfer the remainder of BB and its successor edges to sinkMBB.
10025     sinkMBB->splice(sinkMBB->begin(), BB,
10026                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10027     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10028 
10029     // Next, add the true and fallthrough blocks as its successors.
10030     BB->addSuccessor(copy0MBB);
10031     BB->addSuccessor(sinkMBB);
10032 
10033     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10034         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10035         MI.getOpcode() == PPC::SELECT_QFRC ||
10036         MI.getOpcode() == PPC::SELECT_QSRC ||
10037         MI.getOpcode() == PPC::SELECT_QBRC ||
10038         MI.getOpcode() == PPC::SELECT_VRRC ||
10039         MI.getOpcode() == PPC::SELECT_VSFRC ||
10040         MI.getOpcode() == PPC::SELECT_VSSRC ||
10041         MI.getOpcode() == PPC::SELECT_VSRC) {
10042       BuildMI(BB, dl, TII->get(PPC::BC))
10043           .addReg(MI.getOperand(1).getReg())
10044           .addMBB(sinkMBB);
10045     } else {
10046       unsigned SelectPred = MI.getOperand(4).getImm();
10047       BuildMI(BB, dl, TII->get(PPC::BCC))
10048           .addImm(SelectPred)
10049           .addReg(MI.getOperand(1).getReg())
10050           .addMBB(sinkMBB);
10051     }
10052 
10053     //  copy0MBB:
10054     //   %FalseValue = ...
10055     //   # fallthrough to sinkMBB
10056     BB = copy0MBB;
10057 
10058     // Update machine-CFG edges
10059     BB->addSuccessor(sinkMBB);
10060 
10061     //  sinkMBB:
10062     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10063     //  ...
10064     BB = sinkMBB;
10065     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10066         .addReg(MI.getOperand(3).getReg())
10067         .addMBB(copy0MBB)
10068         .addReg(MI.getOperand(2).getReg())
10069         .addMBB(thisMBB);
10070   } else if (MI.getOpcode() == PPC::ReadTB) {
10071     // To read the 64-bit time-base register on a 32-bit target, we read the
10072     // two halves. Should the counter have wrapped while it was being read, we
10073     // need to try again.
10074     // ...
10075     // readLoop:
10076     // mfspr Rx,TBU # load from TBU
10077     // mfspr Ry,TB  # load from TB
10078     // mfspr Rz,TBU # load from TBU
10079     // cmpw crX,Rx,Rz # check if 'old'='new'
10080     // bne readLoop   # branch if they're not equal
10081     // ...
10082 
10083     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10084     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10085     DebugLoc dl = MI.getDebugLoc();
10086     F->insert(It, readMBB);
10087     F->insert(It, sinkMBB);
10088 
10089     // Transfer the remainder of BB and its successor edges to sinkMBB.
10090     sinkMBB->splice(sinkMBB->begin(), BB,
10091                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10092     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10093 
10094     BB->addSuccessor(readMBB);
10095     BB = readMBB;
10096 
10097     MachineRegisterInfo &RegInfo = F->getRegInfo();
10098     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10099     unsigned LoReg = MI.getOperand(0).getReg();
10100     unsigned HiReg = MI.getOperand(1).getReg();
10101 
10102     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10103     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10104     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10105 
10106     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10107 
10108     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10109       .addReg(HiReg).addReg(ReadAgainReg);
10110     BuildMI(BB, dl, TII->get(PPC::BCC))
10111       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
10112 
10113     BB->addSuccessor(readMBB);
10114     BB->addSuccessor(sinkMBB);
10115   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10116     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10117   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10118     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10119   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10120     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10121   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10122     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10123 
10124   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10125     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10126   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10127     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10128   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10129     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10130   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10131     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10132 
10133   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10134     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10135   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10136     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10137   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10138     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10139   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10140     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10141 
10142   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10143     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10144   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10145     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10146   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10147     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10148   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10149     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10150 
10151   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10152     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10153   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10154     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10155   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10156     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10157   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10158     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10159 
10160   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10161     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10162   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10163     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10164   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10165     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10166   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10167     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10168 
10169   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10170     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10171   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10172     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10173   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10174     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10175   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10176     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10177 
10178   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10179     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10180   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10181     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10182   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10183     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10184   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10185     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10186 
10187   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10188     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10189   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10190     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10191   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10192     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10193   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10194     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10195 
10196   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10197     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10198   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10199     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10200   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10201     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10202   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10203     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10204 
10205   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10206     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10207   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10208     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10209   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10210     BB = EmitAtomicBinary(MI, BB, 4, 0);
10211   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10212     BB = EmitAtomicBinary(MI, BB, 8, 0);
10213   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10214            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10215            (Subtarget.hasPartwordAtomics() &&
10216             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10217            (Subtarget.hasPartwordAtomics() &&
10218             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10219     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10220 
10221     auto LoadMnemonic = PPC::LDARX;
10222     auto StoreMnemonic = PPC::STDCX;
10223     switch (MI.getOpcode()) {
10224     default:
10225       llvm_unreachable("Compare and swap of unknown size");
10226     case PPC::ATOMIC_CMP_SWAP_I8:
10227       LoadMnemonic = PPC::LBARX;
10228       StoreMnemonic = PPC::STBCX;
10229       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10230       break;
10231     case PPC::ATOMIC_CMP_SWAP_I16:
10232       LoadMnemonic = PPC::LHARX;
10233       StoreMnemonic = PPC::STHCX;
10234       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10235       break;
10236     case PPC::ATOMIC_CMP_SWAP_I32:
10237       LoadMnemonic = PPC::LWARX;
10238       StoreMnemonic = PPC::STWCX;
10239       break;
10240     case PPC::ATOMIC_CMP_SWAP_I64:
10241       LoadMnemonic = PPC::LDARX;
10242       StoreMnemonic = PPC::STDCX;
10243       break;
10244     }
10245     unsigned dest = MI.getOperand(0).getReg();
10246     unsigned ptrA = MI.getOperand(1).getReg();
10247     unsigned ptrB = MI.getOperand(2).getReg();
10248     unsigned oldval = MI.getOperand(3).getReg();
10249     unsigned newval = MI.getOperand(4).getReg();
10250     DebugLoc dl = MI.getDebugLoc();
10251 
10252     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10253     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10254     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10255     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10256     F->insert(It, loop1MBB);
10257     F->insert(It, loop2MBB);
10258     F->insert(It, midMBB);
10259     F->insert(It, exitMBB);
10260     exitMBB->splice(exitMBB->begin(), BB,
10261                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10262     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10263 
10264     //  thisMBB:
10265     //   ...
10266     //   fallthrough --> loopMBB
10267     BB->addSuccessor(loop1MBB);
10268 
10269     // loop1MBB:
10270     //   l[bhwd]arx dest, ptr
10271     //   cmp[wd] dest, oldval
10272     //   bne- midMBB
10273     // loop2MBB:
10274     //   st[bhwd]cx. newval, ptr
10275     //   bne- loopMBB
10276     //   b exitBB
10277     // midMBB:
10278     //   st[bhwd]cx. dest, ptr
10279     // exitBB:
10280     BB = loop1MBB;
10281     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10282       .addReg(ptrA).addReg(ptrB);
10283     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10284       .addReg(oldval).addReg(dest);
10285     BuildMI(BB, dl, TII->get(PPC::BCC))
10286       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10287     BB->addSuccessor(loop2MBB);
10288     BB->addSuccessor(midMBB);
10289 
10290     BB = loop2MBB;
10291     BuildMI(BB, dl, TII->get(StoreMnemonic))
10292       .addReg(newval).addReg(ptrA).addReg(ptrB);
10293     BuildMI(BB, dl, TII->get(PPC::BCC))
10294       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10295     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10296     BB->addSuccessor(loop1MBB);
10297     BB->addSuccessor(exitMBB);
10298 
10299     BB = midMBB;
10300     BuildMI(BB, dl, TII->get(StoreMnemonic))
10301       .addReg(dest).addReg(ptrA).addReg(ptrB);
10302     BB->addSuccessor(exitMBB);
10303 
10304     //  exitMBB:
10305     //   ...
10306     BB = exitMBB;
10307   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10308              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10309     // We must use 64-bit registers for addresses when targeting 64-bit,
10310     // since we're actually doing arithmetic on them.  Other registers
10311     // can be 32-bit.
10312     bool is64bit = Subtarget.isPPC64();
10313     bool isLittleEndian = Subtarget.isLittleEndian();
10314     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10315 
10316     unsigned dest = MI.getOperand(0).getReg();
10317     unsigned ptrA = MI.getOperand(1).getReg();
10318     unsigned ptrB = MI.getOperand(2).getReg();
10319     unsigned oldval = MI.getOperand(3).getReg();
10320     unsigned newval = MI.getOperand(4).getReg();
10321     DebugLoc dl = MI.getDebugLoc();
10322 
10323     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10324     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10325     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10326     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10327     F->insert(It, loop1MBB);
10328     F->insert(It, loop2MBB);
10329     F->insert(It, midMBB);
10330     F->insert(It, exitMBB);
10331     exitMBB->splice(exitMBB->begin(), BB,
10332                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10333     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10334 
10335     MachineRegisterInfo &RegInfo = F->getRegInfo();
10336     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10337                                             : &PPC::GPRCRegClass;
10338     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10339     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10340     unsigned ShiftReg =
10341       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10342     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10343     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10344     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10345     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10346     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10347     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10348     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10349     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10350     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10351     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10352     unsigned Ptr1Reg;
10353     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10354     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10355     //  thisMBB:
10356     //   ...
10357     //   fallthrough --> loopMBB
10358     BB->addSuccessor(loop1MBB);
10359 
10360     // The 4-byte load must be aligned, while a char or short may be
10361     // anywhere in the word.  Hence all this nasty bookkeeping code.
10362     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10363     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10364     //   xori shift, shift1, 24 [16]
10365     //   rlwinm ptr, ptr1, 0, 0, 29
10366     //   slw newval2, newval, shift
10367     //   slw oldval2, oldval,shift
10368     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10369     //   slw mask, mask2, shift
10370     //   and newval3, newval2, mask
10371     //   and oldval3, oldval2, mask
10372     // loop1MBB:
10373     //   lwarx tmpDest, ptr
10374     //   and tmp, tmpDest, mask
10375     //   cmpw tmp, oldval3
10376     //   bne- midMBB
10377     // loop2MBB:
10378     //   andc tmp2, tmpDest, mask
10379     //   or tmp4, tmp2, newval3
10380     //   stwcx. tmp4, ptr
10381     //   bne- loop1MBB
10382     //   b exitBB
10383     // midMBB:
10384     //   stwcx. tmpDest, ptr
10385     // exitBB:
10386     //   srw dest, tmpDest, shift
10387     if (ptrA != ZeroReg) {
10388       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10389       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10390         .addReg(ptrA).addReg(ptrB);
10391     } else {
10392       Ptr1Reg = ptrB;
10393     }
10394     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10395         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10396     if (!isLittleEndian)
10397       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10398           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10399     if (is64bit)
10400       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10401         .addReg(Ptr1Reg).addImm(0).addImm(61);
10402     else
10403       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10404         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10405     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10406         .addReg(newval).addReg(ShiftReg);
10407     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10408         .addReg(oldval).addReg(ShiftReg);
10409     if (is8bit)
10410       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10411     else {
10412       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10413       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10414         .addReg(Mask3Reg).addImm(65535);
10415     }
10416     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10417         .addReg(Mask2Reg).addReg(ShiftReg);
10418     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10419         .addReg(NewVal2Reg).addReg(MaskReg);
10420     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10421         .addReg(OldVal2Reg).addReg(MaskReg);
10422 
10423     BB = loop1MBB;
10424     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10425         .addReg(ZeroReg).addReg(PtrReg);
10426     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10427         .addReg(TmpDestReg).addReg(MaskReg);
10428     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10429         .addReg(TmpReg).addReg(OldVal3Reg);
10430     BuildMI(BB, dl, TII->get(PPC::BCC))
10431         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10432     BB->addSuccessor(loop2MBB);
10433     BB->addSuccessor(midMBB);
10434 
10435     BB = loop2MBB;
10436     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10437         .addReg(TmpDestReg).addReg(MaskReg);
10438     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10439         .addReg(Tmp2Reg).addReg(NewVal3Reg);
10440     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10441         .addReg(ZeroReg).addReg(PtrReg);
10442     BuildMI(BB, dl, TII->get(PPC::BCC))
10443       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10444     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10445     BB->addSuccessor(loop1MBB);
10446     BB->addSuccessor(exitMBB);
10447 
10448     BB = midMBB;
10449     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10450       .addReg(ZeroReg).addReg(PtrReg);
10451     BB->addSuccessor(exitMBB);
10452 
10453     //  exitMBB:
10454     //   ...
10455     BB = exitMBB;
10456     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10457       .addReg(ShiftReg);
10458   } else if (MI.getOpcode() == PPC::FADDrtz) {
10459     // This pseudo performs an FADD with rounding mode temporarily forced
10460     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10461     // is not modeled at the SelectionDAG level.
10462     unsigned Dest = MI.getOperand(0).getReg();
10463     unsigned Src1 = MI.getOperand(1).getReg();
10464     unsigned Src2 = MI.getOperand(2).getReg();
10465     DebugLoc dl = MI.getDebugLoc();
10466 
10467     MachineRegisterInfo &RegInfo = F->getRegInfo();
10468     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10469 
10470     // Save FPSCR value.
10471     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10472 
10473     // Set rounding mode to round-to-zero.
10474     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10475     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10476 
10477     // Perform addition.
10478     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10479 
10480     // Restore FPSCR value.
10481     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10482   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10483              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10484              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10485              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10486     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10487                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10488                           ? PPC::ANDIo8
10489                           : PPC::ANDIo;
10490     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10491                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10492 
10493     MachineRegisterInfo &RegInfo = F->getRegInfo();
10494     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10495                                                   &PPC::GPRCRegClass :
10496                                                   &PPC::G8RCRegClass);
10497 
10498     DebugLoc dl = MI.getDebugLoc();
10499     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10500         .addReg(MI.getOperand(1).getReg())
10501         .addImm(1);
10502     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10503             MI.getOperand(0).getReg())
10504         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10505   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10506     DebugLoc Dl = MI.getDebugLoc();
10507     MachineRegisterInfo &RegInfo = F->getRegInfo();
10508     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10509     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10510     return BB;
10511   } else {
10512     llvm_unreachable("Unexpected instr type to insert");
10513   }
10514 
10515   MI.eraseFromParent(); // The pseudo instruction is gone now.
10516   return BB;
10517 }
10518 
10519 //===----------------------------------------------------------------------===//
10520 // Target Optimization Hooks
10521 //===----------------------------------------------------------------------===//
10522 
10523 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10524   // For the estimates, convergence is quadratic, so we essentially double the
10525   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10526   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10527   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10528   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10529   if (VT.getScalarType() == MVT::f64)
10530     RefinementSteps++;
10531   return RefinementSteps;
10532 }
10533 
10534 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10535                                            int Enabled, int &RefinementSteps,
10536                                            bool &UseOneConstNR,
10537                                            bool Reciprocal) const {
10538   EVT VT = Operand.getValueType();
10539   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10540       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10541       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10542       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10543       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10544       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10545     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10546       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10547 
10548     UseOneConstNR = true;
10549     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10550   }
10551   return SDValue();
10552 }
10553 
10554 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10555                                             int Enabled,
10556                                             int &RefinementSteps) const {
10557   EVT VT = Operand.getValueType();
10558   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10559       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10560       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10561       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10562       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10563       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10564     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10565       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10566     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10567   }
10568   return SDValue();
10569 }
10570 
10571 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10572   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10573   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10574   // enabled for division), this functionality is redundant with the default
10575   // combiner logic (once the division -> reciprocal/multiply transformation
10576   // has taken place). As a result, this matters more for older cores than for
10577   // newer ones.
10578 
10579   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10580   // reciprocal if there are two or more FDIVs (for embedded cores with only
10581   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10582   switch (Subtarget.getDarwinDirective()) {
10583   default:
10584     return 3;
10585   case PPC::DIR_440:
10586   case PPC::DIR_A2:
10587   case PPC::DIR_E500mc:
10588   case PPC::DIR_E5500:
10589     return 2;
10590   }
10591 }
10592 
10593 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10594 // collapsed, and so we need to look through chains of them.
10595 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10596                                      int64_t& Offset, SelectionDAG &DAG) {
10597   if (DAG.isBaseWithConstantOffset(Loc)) {
10598     Base = Loc.getOperand(0);
10599     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10600 
10601     // The base might itself be a base plus an offset, and if so, accumulate
10602     // that as well.
10603     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10604   }
10605 }
10606 
10607 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10608                             unsigned Bytes, int Dist,
10609                             SelectionDAG &DAG) {
10610   if (VT.getSizeInBits() / 8 != Bytes)
10611     return false;
10612 
10613   SDValue BaseLoc = Base->getBasePtr();
10614   if (Loc.getOpcode() == ISD::FrameIndex) {
10615     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10616       return false;
10617     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10618     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10619     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10620     int FS  = MFI.getObjectSize(FI);
10621     int BFS = MFI.getObjectSize(BFI);
10622     if (FS != BFS || FS != (int)Bytes) return false;
10623     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10624   }
10625 
10626   SDValue Base1 = Loc, Base2 = BaseLoc;
10627   int64_t Offset1 = 0, Offset2 = 0;
10628   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10629   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10630   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10631     return true;
10632 
10633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10634   const GlobalValue *GV1 = nullptr;
10635   const GlobalValue *GV2 = nullptr;
10636   Offset1 = 0;
10637   Offset2 = 0;
10638   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10639   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10640   if (isGA1 && isGA2 && GV1 == GV2)
10641     return Offset1 == (Offset2 + Dist*Bytes);
10642   return false;
10643 }
10644 
10645 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10646 // not enforce equality of the chain operands.
10647 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10648                             unsigned Bytes, int Dist,
10649                             SelectionDAG &DAG) {
10650   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10651     EVT VT = LS->getMemoryVT();
10652     SDValue Loc = LS->getBasePtr();
10653     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10654   }
10655 
10656   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10657     EVT VT;
10658     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10659     default: return false;
10660     case Intrinsic::ppc_qpx_qvlfd:
10661     case Intrinsic::ppc_qpx_qvlfda:
10662       VT = MVT::v4f64;
10663       break;
10664     case Intrinsic::ppc_qpx_qvlfs:
10665     case Intrinsic::ppc_qpx_qvlfsa:
10666       VT = MVT::v4f32;
10667       break;
10668     case Intrinsic::ppc_qpx_qvlfcd:
10669     case Intrinsic::ppc_qpx_qvlfcda:
10670       VT = MVT::v2f64;
10671       break;
10672     case Intrinsic::ppc_qpx_qvlfcs:
10673     case Intrinsic::ppc_qpx_qvlfcsa:
10674       VT = MVT::v2f32;
10675       break;
10676     case Intrinsic::ppc_qpx_qvlfiwa:
10677     case Intrinsic::ppc_qpx_qvlfiwz:
10678     case Intrinsic::ppc_altivec_lvx:
10679     case Intrinsic::ppc_altivec_lvxl:
10680     case Intrinsic::ppc_vsx_lxvw4x:
10681     case Intrinsic::ppc_vsx_lxvw4x_be:
10682       VT = MVT::v4i32;
10683       break;
10684     case Intrinsic::ppc_vsx_lxvd2x:
10685     case Intrinsic::ppc_vsx_lxvd2x_be:
10686       VT = MVT::v2f64;
10687       break;
10688     case Intrinsic::ppc_altivec_lvebx:
10689       VT = MVT::i8;
10690       break;
10691     case Intrinsic::ppc_altivec_lvehx:
10692       VT = MVT::i16;
10693       break;
10694     case Intrinsic::ppc_altivec_lvewx:
10695       VT = MVT::i32;
10696       break;
10697     }
10698 
10699     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10700   }
10701 
10702   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10703     EVT VT;
10704     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10705     default: return false;
10706     case Intrinsic::ppc_qpx_qvstfd:
10707     case Intrinsic::ppc_qpx_qvstfda:
10708       VT = MVT::v4f64;
10709       break;
10710     case Intrinsic::ppc_qpx_qvstfs:
10711     case Intrinsic::ppc_qpx_qvstfsa:
10712       VT = MVT::v4f32;
10713       break;
10714     case Intrinsic::ppc_qpx_qvstfcd:
10715     case Intrinsic::ppc_qpx_qvstfcda:
10716       VT = MVT::v2f64;
10717       break;
10718     case Intrinsic::ppc_qpx_qvstfcs:
10719     case Intrinsic::ppc_qpx_qvstfcsa:
10720       VT = MVT::v2f32;
10721       break;
10722     case Intrinsic::ppc_qpx_qvstfiw:
10723     case Intrinsic::ppc_qpx_qvstfiwa:
10724     case Intrinsic::ppc_altivec_stvx:
10725     case Intrinsic::ppc_altivec_stvxl:
10726     case Intrinsic::ppc_vsx_stxvw4x:
10727       VT = MVT::v4i32;
10728       break;
10729     case Intrinsic::ppc_vsx_stxvd2x:
10730       VT = MVT::v2f64;
10731       break;
10732     case Intrinsic::ppc_vsx_stxvw4x_be:
10733       VT = MVT::v4i32;
10734       break;
10735     case Intrinsic::ppc_vsx_stxvd2x_be:
10736       VT = MVT::v2f64;
10737       break;
10738     case Intrinsic::ppc_altivec_stvebx:
10739       VT = MVT::i8;
10740       break;
10741     case Intrinsic::ppc_altivec_stvehx:
10742       VT = MVT::i16;
10743       break;
10744     case Intrinsic::ppc_altivec_stvewx:
10745       VT = MVT::i32;
10746       break;
10747     }
10748 
10749     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10750   }
10751 
10752   return false;
10753 }
10754 
10755 // Return true is there is a nearyby consecutive load to the one provided
10756 // (regardless of alignment). We search up and down the chain, looking though
10757 // token factors and other loads (but nothing else). As a result, a true result
10758 // indicates that it is safe to create a new consecutive load adjacent to the
10759 // load provided.
10760 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10761   SDValue Chain = LD->getChain();
10762   EVT VT = LD->getMemoryVT();
10763 
10764   SmallSet<SDNode *, 16> LoadRoots;
10765   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10766   SmallSet<SDNode *, 16> Visited;
10767 
10768   // First, search up the chain, branching to follow all token-factor operands.
10769   // If we find a consecutive load, then we're done, otherwise, record all
10770   // nodes just above the top-level loads and token factors.
10771   while (!Queue.empty()) {
10772     SDNode *ChainNext = Queue.pop_back_val();
10773     if (!Visited.insert(ChainNext).second)
10774       continue;
10775 
10776     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10777       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10778         return true;
10779 
10780       if (!Visited.count(ChainLD->getChain().getNode()))
10781         Queue.push_back(ChainLD->getChain().getNode());
10782     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10783       for (const SDUse &O : ChainNext->ops())
10784         if (!Visited.count(O.getNode()))
10785           Queue.push_back(O.getNode());
10786     } else
10787       LoadRoots.insert(ChainNext);
10788   }
10789 
10790   // Second, search down the chain, starting from the top-level nodes recorded
10791   // in the first phase. These top-level nodes are the nodes just above all
10792   // loads and token factors. Starting with their uses, recursively look though
10793   // all loads (just the chain uses) and token factors to find a consecutive
10794   // load.
10795   Visited.clear();
10796   Queue.clear();
10797 
10798   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10799        IE = LoadRoots.end(); I != IE; ++I) {
10800     Queue.push_back(*I);
10801 
10802     while (!Queue.empty()) {
10803       SDNode *LoadRoot = Queue.pop_back_val();
10804       if (!Visited.insert(LoadRoot).second)
10805         continue;
10806 
10807       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10808         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10809           return true;
10810 
10811       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10812            UE = LoadRoot->use_end(); UI != UE; ++UI)
10813         if (((isa<MemSDNode>(*UI) &&
10814             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10815             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10816           Queue.push_back(*UI);
10817     }
10818   }
10819 
10820   return false;
10821 }
10822 
10823 /// This function is called when we have proved that a SETCC node can be replaced
10824 /// by subtraction (and other supporting instructions) so that the result of
10825 /// comparison is kept in a GPR instead of CR. This function is purely for
10826 /// codegen purposes and has some flags to guide the codegen process.
10827 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10828                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10829   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10830 
10831   // Zero extend the operands to the largest legal integer. Originally, they
10832   // must be of a strictly smaller size.
10833   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10834                          DAG.getConstant(Size, DL, MVT::i32));
10835   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10836                          DAG.getConstant(Size, DL, MVT::i32));
10837 
10838   // Swap if needed. Depends on the condition code.
10839   if (Swap)
10840     std::swap(Op0, Op1);
10841 
10842   // Subtract extended integers.
10843   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10844 
10845   // Move the sign bit to the least significant position and zero out the rest.
10846   // Now the least significant bit carries the result of original comparison.
10847   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10848                              DAG.getConstant(Size - 1, DL, MVT::i32));
10849   auto Final = Shifted;
10850 
10851   // Complement the result if needed. Based on the condition code.
10852   if (Complement)
10853     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10854                         DAG.getConstant(1, DL, MVT::i64));
10855 
10856   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10857 }
10858 
10859 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10860                                                   DAGCombinerInfo &DCI) const {
10861   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10862 
10863   SelectionDAG &DAG = DCI.DAG;
10864   SDLoc DL(N);
10865 
10866   // Size of integers being compared has a critical role in the following
10867   // analysis, so we prefer to do this when all types are legal.
10868   if (!DCI.isAfterLegalizeVectorOps())
10869     return SDValue();
10870 
10871   // If all users of SETCC extend its value to a legal integer type
10872   // then we replace SETCC with a subtraction
10873   for (SDNode::use_iterator UI = N->use_begin(),
10874        UE = N->use_end(); UI != UE; ++UI) {
10875     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10876       return SDValue();
10877   }
10878 
10879   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10880   auto OpSize = N->getOperand(0).getValueSizeInBits();
10881 
10882   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10883 
10884   if (OpSize < Size) {
10885     switch (CC) {
10886     default: break;
10887     case ISD::SETULT:
10888       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10889     case ISD::SETULE:
10890       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10891     case ISD::SETUGT:
10892       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10893     case ISD::SETUGE:
10894       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10895     }
10896   }
10897 
10898   return SDValue();
10899 }
10900 
10901 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10902                                                   DAGCombinerInfo &DCI) const {
10903   SelectionDAG &DAG = DCI.DAG;
10904   SDLoc dl(N);
10905 
10906   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10907   // If we're tracking CR bits, we need to be careful that we don't have:
10908   //   trunc(binary-ops(zext(x), zext(y)))
10909   // or
10910   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10911   // such that we're unnecessarily moving things into GPRs when it would be
10912   // better to keep them in CR bits.
10913 
10914   // Note that trunc here can be an actual i1 trunc, or can be the effective
10915   // truncation that comes from a setcc or select_cc.
10916   if (N->getOpcode() == ISD::TRUNCATE &&
10917       N->getValueType(0) != MVT::i1)
10918     return SDValue();
10919 
10920   if (N->getOperand(0).getValueType() != MVT::i32 &&
10921       N->getOperand(0).getValueType() != MVT::i64)
10922     return SDValue();
10923 
10924   if (N->getOpcode() == ISD::SETCC ||
10925       N->getOpcode() == ISD::SELECT_CC) {
10926     // If we're looking at a comparison, then we need to make sure that the
10927     // high bits (all except for the first) don't matter the result.
10928     ISD::CondCode CC =
10929       cast<CondCodeSDNode>(N->getOperand(
10930         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10931     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10932 
10933     if (ISD::isSignedIntSetCC(CC)) {
10934       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10935           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10936         return SDValue();
10937     } else if (ISD::isUnsignedIntSetCC(CC)) {
10938       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10939                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10940           !DAG.MaskedValueIsZero(N->getOperand(1),
10941                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10942         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10943                                              : SDValue());
10944     } else {
10945       // This is neither a signed nor an unsigned comparison, just make sure
10946       // that the high bits are equal.
10947       KnownBits Op1Known, Op2Known;
10948       DAG.computeKnownBits(N->getOperand(0), Op1Known);
10949       DAG.computeKnownBits(N->getOperand(1), Op2Known);
10950 
10951       // We don't really care about what is known about the first bit (if
10952       // anything), so clear it in all masks prior to comparing them.
10953       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10954       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10955 
10956       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10957         return SDValue();
10958     }
10959   }
10960 
10961   // We now know that the higher-order bits are irrelevant, we just need to
10962   // make sure that all of the intermediate operations are bit operations, and
10963   // all inputs are extensions.
10964   if (N->getOperand(0).getOpcode() != ISD::AND &&
10965       N->getOperand(0).getOpcode() != ISD::OR  &&
10966       N->getOperand(0).getOpcode() != ISD::XOR &&
10967       N->getOperand(0).getOpcode() != ISD::SELECT &&
10968       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10969       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10970       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10971       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10972       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10973     return SDValue();
10974 
10975   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10976       N->getOperand(1).getOpcode() != ISD::AND &&
10977       N->getOperand(1).getOpcode() != ISD::OR  &&
10978       N->getOperand(1).getOpcode() != ISD::XOR &&
10979       N->getOperand(1).getOpcode() != ISD::SELECT &&
10980       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10981       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10982       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10983       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10984       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10985     return SDValue();
10986 
10987   SmallVector<SDValue, 4> Inputs;
10988   SmallVector<SDValue, 8> BinOps, PromOps;
10989   SmallPtrSet<SDNode *, 16> Visited;
10990 
10991   for (unsigned i = 0; i < 2; ++i) {
10992     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10993           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10994           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10995           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10996         isa<ConstantSDNode>(N->getOperand(i)))
10997       Inputs.push_back(N->getOperand(i));
10998     else
10999       BinOps.push_back(N->getOperand(i));
11000 
11001     if (N->getOpcode() == ISD::TRUNCATE)
11002       break;
11003   }
11004 
11005   // Visit all inputs, collect all binary operations (and, or, xor and
11006   // select) that are all fed by extensions.
11007   while (!BinOps.empty()) {
11008     SDValue BinOp = BinOps.back();
11009     BinOps.pop_back();
11010 
11011     if (!Visited.insert(BinOp.getNode()).second)
11012       continue;
11013 
11014     PromOps.push_back(BinOp);
11015 
11016     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11017       // The condition of the select is not promoted.
11018       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11019         continue;
11020       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11021         continue;
11022 
11023       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11024             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11025             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11026            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11027           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11028         Inputs.push_back(BinOp.getOperand(i));
11029       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11030                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11031                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11032                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11033                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11034                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11035                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11036                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11037                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11038         BinOps.push_back(BinOp.getOperand(i));
11039       } else {
11040         // We have an input that is not an extension or another binary
11041         // operation; we'll abort this transformation.
11042         return SDValue();
11043       }
11044     }
11045   }
11046 
11047   // Make sure that this is a self-contained cluster of operations (which
11048   // is not quite the same thing as saying that everything has only one
11049   // use).
11050   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11051     if (isa<ConstantSDNode>(Inputs[i]))
11052       continue;
11053 
11054     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11055                               UE = Inputs[i].getNode()->use_end();
11056          UI != UE; ++UI) {
11057       SDNode *User = *UI;
11058       if (User != N && !Visited.count(User))
11059         return SDValue();
11060 
11061       // Make sure that we're not going to promote the non-output-value
11062       // operand(s) or SELECT or SELECT_CC.
11063       // FIXME: Although we could sometimes handle this, and it does occur in
11064       // practice that one of the condition inputs to the select is also one of
11065       // the outputs, we currently can't deal with this.
11066       if (User->getOpcode() == ISD::SELECT) {
11067         if (User->getOperand(0) == Inputs[i])
11068           return SDValue();
11069       } else if (User->getOpcode() == ISD::SELECT_CC) {
11070         if (User->getOperand(0) == Inputs[i] ||
11071             User->getOperand(1) == Inputs[i])
11072           return SDValue();
11073       }
11074     }
11075   }
11076 
11077   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11078     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11079                               UE = PromOps[i].getNode()->use_end();
11080          UI != UE; ++UI) {
11081       SDNode *User = *UI;
11082       if (User != N && !Visited.count(User))
11083         return SDValue();
11084 
11085       // Make sure that we're not going to promote the non-output-value
11086       // operand(s) or SELECT or SELECT_CC.
11087       // FIXME: Although we could sometimes handle this, and it does occur in
11088       // practice that one of the condition inputs to the select is also one of
11089       // the outputs, we currently can't deal with this.
11090       if (User->getOpcode() == ISD::SELECT) {
11091         if (User->getOperand(0) == PromOps[i])
11092           return SDValue();
11093       } else if (User->getOpcode() == ISD::SELECT_CC) {
11094         if (User->getOperand(0) == PromOps[i] ||
11095             User->getOperand(1) == PromOps[i])
11096           return SDValue();
11097       }
11098     }
11099   }
11100 
11101   // Replace all inputs with the extension operand.
11102   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11103     // Constants may have users outside the cluster of to-be-promoted nodes,
11104     // and so we need to replace those as we do the promotions.
11105     if (isa<ConstantSDNode>(Inputs[i]))
11106       continue;
11107     else
11108       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11109   }
11110 
11111   std::list<HandleSDNode> PromOpHandles;
11112   for (auto &PromOp : PromOps)
11113     PromOpHandles.emplace_back(PromOp);
11114 
11115   // Replace all operations (these are all the same, but have a different
11116   // (i1) return type). DAG.getNode will validate that the types of
11117   // a binary operator match, so go through the list in reverse so that
11118   // we've likely promoted both operands first. Any intermediate truncations or
11119   // extensions disappear.
11120   while (!PromOpHandles.empty()) {
11121     SDValue PromOp = PromOpHandles.back().getValue();
11122     PromOpHandles.pop_back();
11123 
11124     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11125         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11126         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11127         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11128       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11129           PromOp.getOperand(0).getValueType() != MVT::i1) {
11130         // The operand is not yet ready (see comment below).
11131         PromOpHandles.emplace_front(PromOp);
11132         continue;
11133       }
11134 
11135       SDValue RepValue = PromOp.getOperand(0);
11136       if (isa<ConstantSDNode>(RepValue))
11137         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11138 
11139       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11140       continue;
11141     }
11142 
11143     unsigned C;
11144     switch (PromOp.getOpcode()) {
11145     default:             C = 0; break;
11146     case ISD::SELECT:    C = 1; break;
11147     case ISD::SELECT_CC: C = 2; break;
11148     }
11149 
11150     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11151          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11152         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11153          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11154       // The to-be-promoted operands of this node have not yet been
11155       // promoted (this should be rare because we're going through the
11156       // list backward, but if one of the operands has several users in
11157       // this cluster of to-be-promoted nodes, it is possible).
11158       PromOpHandles.emplace_front(PromOp);
11159       continue;
11160     }
11161 
11162     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11163                                 PromOp.getNode()->op_end());
11164 
11165     // If there are any constant inputs, make sure they're replaced now.
11166     for (unsigned i = 0; i < 2; ++i)
11167       if (isa<ConstantSDNode>(Ops[C+i]))
11168         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11169 
11170     DAG.ReplaceAllUsesOfValueWith(PromOp,
11171       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11172   }
11173 
11174   // Now we're left with the initial truncation itself.
11175   if (N->getOpcode() == ISD::TRUNCATE)
11176     return N->getOperand(0);
11177 
11178   // Otherwise, this is a comparison. The operands to be compared have just
11179   // changed type (to i1), but everything else is the same.
11180   return SDValue(N, 0);
11181 }
11182 
11183 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11184                                                   DAGCombinerInfo &DCI) const {
11185   SelectionDAG &DAG = DCI.DAG;
11186   SDLoc dl(N);
11187 
11188   // If we're tracking CR bits, we need to be careful that we don't have:
11189   //   zext(binary-ops(trunc(x), trunc(y)))
11190   // or
11191   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11192   // such that we're unnecessarily moving things into CR bits that can more
11193   // efficiently stay in GPRs. Note that if we're not certain that the high
11194   // bits are set as required by the final extension, we still may need to do
11195   // some masking to get the proper behavior.
11196 
11197   // This same functionality is important on PPC64 when dealing with
11198   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11199   // the return values of functions. Because it is so similar, it is handled
11200   // here as well.
11201 
11202   if (N->getValueType(0) != MVT::i32 &&
11203       N->getValueType(0) != MVT::i64)
11204     return SDValue();
11205 
11206   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11207         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11208     return SDValue();
11209 
11210   if (N->getOperand(0).getOpcode() != ISD::AND &&
11211       N->getOperand(0).getOpcode() != ISD::OR  &&
11212       N->getOperand(0).getOpcode() != ISD::XOR &&
11213       N->getOperand(0).getOpcode() != ISD::SELECT &&
11214       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11215     return SDValue();
11216 
11217   SmallVector<SDValue, 4> Inputs;
11218   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11219   SmallPtrSet<SDNode *, 16> Visited;
11220 
11221   // Visit all inputs, collect all binary operations (and, or, xor and
11222   // select) that are all fed by truncations.
11223   while (!BinOps.empty()) {
11224     SDValue BinOp = BinOps.back();
11225     BinOps.pop_back();
11226 
11227     if (!Visited.insert(BinOp.getNode()).second)
11228       continue;
11229 
11230     PromOps.push_back(BinOp);
11231 
11232     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11233       // The condition of the select is not promoted.
11234       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11235         continue;
11236       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11237         continue;
11238 
11239       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11240           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11241         Inputs.push_back(BinOp.getOperand(i));
11242       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11243                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11244                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11245                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11246                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11247         BinOps.push_back(BinOp.getOperand(i));
11248       } else {
11249         // We have an input that is not a truncation or another binary
11250         // operation; we'll abort this transformation.
11251         return SDValue();
11252       }
11253     }
11254   }
11255 
11256   // The operands of a select that must be truncated when the select is
11257   // promoted because the operand is actually part of the to-be-promoted set.
11258   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11259 
11260   // Make sure that this is a self-contained cluster of operations (which
11261   // is not quite the same thing as saying that everything has only one
11262   // use).
11263   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11264     if (isa<ConstantSDNode>(Inputs[i]))
11265       continue;
11266 
11267     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11268                               UE = Inputs[i].getNode()->use_end();
11269          UI != UE; ++UI) {
11270       SDNode *User = *UI;
11271       if (User != N && !Visited.count(User))
11272         return SDValue();
11273 
11274       // If we're going to promote the non-output-value operand(s) or SELECT or
11275       // SELECT_CC, record them for truncation.
11276       if (User->getOpcode() == ISD::SELECT) {
11277         if (User->getOperand(0) == Inputs[i])
11278           SelectTruncOp[0].insert(std::make_pair(User,
11279                                     User->getOperand(0).getValueType()));
11280       } else if (User->getOpcode() == ISD::SELECT_CC) {
11281         if (User->getOperand(0) == Inputs[i])
11282           SelectTruncOp[0].insert(std::make_pair(User,
11283                                     User->getOperand(0).getValueType()));
11284         if (User->getOperand(1) == Inputs[i])
11285           SelectTruncOp[1].insert(std::make_pair(User,
11286                                     User->getOperand(1).getValueType()));
11287       }
11288     }
11289   }
11290 
11291   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11292     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11293                               UE = PromOps[i].getNode()->use_end();
11294          UI != UE; ++UI) {
11295       SDNode *User = *UI;
11296       if (User != N && !Visited.count(User))
11297         return SDValue();
11298 
11299       // If we're going to promote the non-output-value operand(s) or SELECT or
11300       // SELECT_CC, record them for truncation.
11301       if (User->getOpcode() == ISD::SELECT) {
11302         if (User->getOperand(0) == PromOps[i])
11303           SelectTruncOp[0].insert(std::make_pair(User,
11304                                     User->getOperand(0).getValueType()));
11305       } else if (User->getOpcode() == ISD::SELECT_CC) {
11306         if (User->getOperand(0) == PromOps[i])
11307           SelectTruncOp[0].insert(std::make_pair(User,
11308                                     User->getOperand(0).getValueType()));
11309         if (User->getOperand(1) == PromOps[i])
11310           SelectTruncOp[1].insert(std::make_pair(User,
11311                                     User->getOperand(1).getValueType()));
11312       }
11313     }
11314   }
11315 
11316   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11317   bool ReallyNeedsExt = false;
11318   if (N->getOpcode() != ISD::ANY_EXTEND) {
11319     // If all of the inputs are not already sign/zero extended, then
11320     // we'll still need to do that at the end.
11321     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11322       if (isa<ConstantSDNode>(Inputs[i]))
11323         continue;
11324 
11325       unsigned OpBits =
11326         Inputs[i].getOperand(0).getValueSizeInBits();
11327       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11328 
11329       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11330            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11331                                   APInt::getHighBitsSet(OpBits,
11332                                                         OpBits-PromBits))) ||
11333           (N->getOpcode() == ISD::SIGN_EXTEND &&
11334            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11335              (OpBits-(PromBits-1)))) {
11336         ReallyNeedsExt = true;
11337         break;
11338       }
11339     }
11340   }
11341 
11342   // Replace all inputs, either with the truncation operand, or a
11343   // truncation or extension to the final output type.
11344   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11345     // Constant inputs need to be replaced with the to-be-promoted nodes that
11346     // use them because they might have users outside of the cluster of
11347     // promoted nodes.
11348     if (isa<ConstantSDNode>(Inputs[i]))
11349       continue;
11350 
11351     SDValue InSrc = Inputs[i].getOperand(0);
11352     if (Inputs[i].getValueType() == N->getValueType(0))
11353       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11354     else if (N->getOpcode() == ISD::SIGN_EXTEND)
11355       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11356         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11357     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11358       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11359         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11360     else
11361       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11362         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11363   }
11364 
11365   std::list<HandleSDNode> PromOpHandles;
11366   for (auto &PromOp : PromOps)
11367     PromOpHandles.emplace_back(PromOp);
11368 
11369   // Replace all operations (these are all the same, but have a different
11370   // (promoted) return type). DAG.getNode will validate that the types of
11371   // a binary operator match, so go through the list in reverse so that
11372   // we've likely promoted both operands first.
11373   while (!PromOpHandles.empty()) {
11374     SDValue PromOp = PromOpHandles.back().getValue();
11375     PromOpHandles.pop_back();
11376 
11377     unsigned C;
11378     switch (PromOp.getOpcode()) {
11379     default:             C = 0; break;
11380     case ISD::SELECT:    C = 1; break;
11381     case ISD::SELECT_CC: C = 2; break;
11382     }
11383 
11384     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11385          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11386         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11387          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11388       // The to-be-promoted operands of this node have not yet been
11389       // promoted (this should be rare because we're going through the
11390       // list backward, but if one of the operands has several users in
11391       // this cluster of to-be-promoted nodes, it is possible).
11392       PromOpHandles.emplace_front(PromOp);
11393       continue;
11394     }
11395 
11396     // For SELECT and SELECT_CC nodes, we do a similar check for any
11397     // to-be-promoted comparison inputs.
11398     if (PromOp.getOpcode() == ISD::SELECT ||
11399         PromOp.getOpcode() == ISD::SELECT_CC) {
11400       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11401            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11402           (SelectTruncOp[1].count(PromOp.getNode()) &&
11403            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11404         PromOpHandles.emplace_front(PromOp);
11405         continue;
11406       }
11407     }
11408 
11409     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11410                                 PromOp.getNode()->op_end());
11411 
11412     // If this node has constant inputs, then they'll need to be promoted here.
11413     for (unsigned i = 0; i < 2; ++i) {
11414       if (!isa<ConstantSDNode>(Ops[C+i]))
11415         continue;
11416       if (Ops[C+i].getValueType() == N->getValueType(0))
11417         continue;
11418 
11419       if (N->getOpcode() == ISD::SIGN_EXTEND)
11420         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11421       else if (N->getOpcode() == ISD::ZERO_EXTEND)
11422         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11423       else
11424         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11425     }
11426 
11427     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11428     // truncate them again to the original value type.
11429     if (PromOp.getOpcode() == ISD::SELECT ||
11430         PromOp.getOpcode() == ISD::SELECT_CC) {
11431       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11432       if (SI0 != SelectTruncOp[0].end())
11433         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11434       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11435       if (SI1 != SelectTruncOp[1].end())
11436         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11437     }
11438 
11439     DAG.ReplaceAllUsesOfValueWith(PromOp,
11440       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11441   }
11442 
11443   // Now we're left with the initial extension itself.
11444   if (!ReallyNeedsExt)
11445     return N->getOperand(0);
11446 
11447   // To zero extend, just mask off everything except for the first bit (in the
11448   // i1 case).
11449   if (N->getOpcode() == ISD::ZERO_EXTEND)
11450     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11451                        DAG.getConstant(APInt::getLowBitsSet(
11452                                          N->getValueSizeInBits(0), PromBits),
11453                                        dl, N->getValueType(0)));
11454 
11455   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11456          "Invalid extension type");
11457   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11458   SDValue ShiftCst =
11459       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11460   return DAG.getNode(
11461       ISD::SRA, dl, N->getValueType(0),
11462       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11463       ShiftCst);
11464 }
11465 
11466 /// \brief Reduces the number of fp-to-int conversion when building a vector.
11467 ///
11468 /// If this vector is built out of floating to integer conversions,
11469 /// transform it to a vector built out of floating point values followed by a
11470 /// single floating to integer conversion of the vector.
11471 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
11472 /// becomes (fptosi (build_vector ($A, $B, ...)))
11473 SDValue PPCTargetLowering::
11474 combineElementTruncationToVectorTruncation(SDNode *N,
11475                                            DAGCombinerInfo &DCI) const {
11476   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11477          "Should be called with a BUILD_VECTOR node");
11478 
11479   SelectionDAG &DAG = DCI.DAG;
11480   SDLoc dl(N);
11481 
11482   SDValue FirstInput = N->getOperand(0);
11483   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11484          "The input operand must be an fp-to-int conversion.");
11485 
11486   // This combine happens after legalization so the fp_to_[su]i nodes are
11487   // already converted to PPCSISD nodes.
11488   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11489   if (FirstConversion == PPCISD::FCTIDZ ||
11490       FirstConversion == PPCISD::FCTIDUZ ||
11491       FirstConversion == PPCISD::FCTIWZ ||
11492       FirstConversion == PPCISD::FCTIWUZ) {
11493     bool IsSplat = true;
11494     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11495       FirstConversion == PPCISD::FCTIWUZ;
11496     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11497     SmallVector<SDValue, 4> Ops;
11498     EVT TargetVT = N->getValueType(0);
11499     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11500       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11501         return SDValue();
11502       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11503       if (NextConversion != FirstConversion)
11504         return SDValue();
11505       if (N->getOperand(i) != FirstInput)
11506         IsSplat = false;
11507     }
11508 
11509     // If this is a splat, we leave it as-is since there will be only a single
11510     // fp-to-int conversion followed by a splat of the integer. This is better
11511     // for 32-bit and smaller ints and neutral for 64-bit ints.
11512     if (IsSplat)
11513       return SDValue();
11514 
11515     // Now that we know we have the right type of node, get its operands
11516     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11517       SDValue In = N->getOperand(i).getOperand(0);
11518       // For 32-bit values, we need to add an FP_ROUND node.
11519       if (Is32Bit) {
11520         if (In.isUndef())
11521           Ops.push_back(DAG.getUNDEF(SrcVT));
11522         else {
11523           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11524                                       MVT::f32, In.getOperand(0),
11525                                       DAG.getIntPtrConstant(1, dl));
11526           Ops.push_back(Trunc);
11527         }
11528       } else
11529         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11530     }
11531 
11532     unsigned Opcode;
11533     if (FirstConversion == PPCISD::FCTIDZ ||
11534         FirstConversion == PPCISD::FCTIWZ)
11535       Opcode = ISD::FP_TO_SINT;
11536     else
11537       Opcode = ISD::FP_TO_UINT;
11538 
11539     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11540     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11541     return DAG.getNode(Opcode, dl, TargetVT, BV);
11542   }
11543   return SDValue();
11544 }
11545 
11546 /// \brief Reduce the number of loads when building a vector.
11547 ///
11548 /// Building a vector out of multiple loads can be converted to a load
11549 /// of the vector type if the loads are consecutive. If the loads are
11550 /// consecutive but in descending order, a shuffle is added at the end
11551 /// to reorder the vector.
11552 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11553   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11554          "Should be called with a BUILD_VECTOR node");
11555 
11556   SDLoc dl(N);
11557   bool InputsAreConsecutiveLoads = true;
11558   bool InputsAreReverseConsecutive = true;
11559   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11560   SDValue FirstInput = N->getOperand(0);
11561   bool IsRoundOfExtLoad = false;
11562 
11563   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11564       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11565     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11566     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11567   }
11568   // Not a build vector of (possibly fp_rounded) loads.
11569   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11570     return SDValue();
11571 
11572   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11573     // If any inputs are fp_round(extload), they all must be.
11574     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11575       return SDValue();
11576 
11577     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11578       N->getOperand(i);
11579     if (NextInput.getOpcode() != ISD::LOAD)
11580       return SDValue();
11581 
11582     SDValue PreviousInput =
11583       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11584     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11585     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11586 
11587     // If any inputs are fp_round(extload), they all must be.
11588     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11589       return SDValue();
11590 
11591     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11592       InputsAreConsecutiveLoads = false;
11593     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11594       InputsAreReverseConsecutive = false;
11595 
11596     // Exit early if the loads are neither consecutive nor reverse consecutive.
11597     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11598       return SDValue();
11599   }
11600 
11601   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11602          "The loads cannot be both consecutive and reverse consecutive.");
11603 
11604   SDValue FirstLoadOp =
11605     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11606   SDValue LastLoadOp =
11607     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11608                        N->getOperand(N->getNumOperands()-1);
11609 
11610   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11611   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11612   if (InputsAreConsecutiveLoads) {
11613     assert(LD1 && "Input needs to be a LoadSDNode.");
11614     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11615                        LD1->getBasePtr(), LD1->getPointerInfo(),
11616                        LD1->getAlignment());
11617   }
11618   if (InputsAreReverseConsecutive) {
11619     assert(LDL && "Input needs to be a LoadSDNode.");
11620     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11621                                LDL->getBasePtr(), LDL->getPointerInfo(),
11622                                LDL->getAlignment());
11623     SmallVector<int, 16> Ops;
11624     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11625       Ops.push_back(i);
11626 
11627     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11628                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11629   }
11630   return SDValue();
11631 }
11632 
11633 // This function adds the required vector_shuffle needed to get
11634 // the elements of the vector extract in the correct position
11635 // as specified by the CorrectElems encoding.
11636 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11637                                       SDValue Input, uint64_t Elems,
11638                                       uint64_t CorrectElems) {
11639   SDLoc dl(N);
11640 
11641   unsigned NumElems = Input.getValueType().getVectorNumElements();
11642   SmallVector<int, 16> ShuffleMask(NumElems, -1);
11643 
11644   // Knowing the element indices being extracted from the original
11645   // vector and the order in which they're being inserted, just put
11646   // them at element indices required for the instruction.
11647   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11648     if (DAG.getDataLayout().isLittleEndian())
11649       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11650     else
11651       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11652     CorrectElems = CorrectElems >> 8;
11653     Elems = Elems >> 8;
11654   }
11655 
11656   SDValue Shuffle =
11657       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11658                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11659 
11660   EVT Ty = N->getValueType(0);
11661   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11662   return BV;
11663 }
11664 
11665 // Look for build vector patterns where input operands come from sign
11666 // extended vector_extract elements of specific indices. If the correct indices
11667 // aren't used, add a vector shuffle to fix up the indices and create a new
11668 // PPCISD:SExtVElems node which selects the vector sign extend instructions
11669 // during instruction selection.
11670 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
11671   // This array encodes the indices that the vector sign extend instructions
11672   // extract from when extending from one type to another for both BE and LE.
11673   // The right nibble of each byte corresponds to the LE incides.
11674   // and the left nibble of each byte corresponds to the BE incides.
11675   // For example: 0x3074B8FC  byte->word
11676   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
11677   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
11678   // For example: 0x000070F8  byte->double word
11679   // For LE: the allowed indices are: 0x0,0x8
11680   // For BE: the allowed indices are: 0x7,0xF
11681   uint64_t TargetElems[] = {
11682       0x3074B8FC, // b->w
11683       0x000070F8, // b->d
11684       0x10325476, // h->w
11685       0x00003074, // h->d
11686       0x00001032, // w->d
11687   };
11688 
11689   uint64_t Elems = 0;
11690   int Index;
11691   SDValue Input;
11692 
11693   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
11694     if (!Op)
11695       return false;
11696     if (Op.getOpcode() != ISD::SIGN_EXTEND)
11697       return false;
11698 
11699     SDValue Extract = Op.getOperand(0);
11700     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11701       return false;
11702 
11703     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
11704     if (!ExtOp)
11705       return false;
11706 
11707     Index = ExtOp->getZExtValue();
11708     if (Input && Input != Extract.getOperand(0))
11709       return false;
11710 
11711     if (!Input)
11712       Input = Extract.getOperand(0);
11713 
11714     Elems = Elems << 8;
11715     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
11716     Elems |= Index;
11717 
11718     return true;
11719   };
11720 
11721   // If the build vector operands aren't sign extended vector extracts,
11722   // of the same input vector, then return.
11723   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11724     if (!isSExtOfVecExtract(N->getOperand(i))) {
11725       return SDValue();
11726     }
11727   }
11728 
11729   // If the vector extract indicies are not correct, add the appropriate
11730   // vector_shuffle.
11731   int TgtElemArrayIdx;
11732   int InputSize = Input.getValueType().getScalarSizeInBits();
11733   int OutputSize = N->getValueType(0).getScalarSizeInBits();
11734   if (InputSize + OutputSize == 40)
11735     TgtElemArrayIdx = 0;
11736   else if (InputSize + OutputSize == 72)
11737     TgtElemArrayIdx = 1;
11738   else if (InputSize + OutputSize == 48)
11739     TgtElemArrayIdx = 2;
11740   else if (InputSize + OutputSize == 80)
11741     TgtElemArrayIdx = 3;
11742   else if (InputSize + OutputSize == 96)
11743     TgtElemArrayIdx = 4;
11744   else
11745     return SDValue();
11746 
11747   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
11748   CorrectElems = DAG.getDataLayout().isLittleEndian()
11749                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
11750                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
11751   if (Elems != CorrectElems) {
11752     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
11753   }
11754 
11755   // Regular lowering will catch cases where a shuffle is not needed.
11756   return SDValue();
11757 }
11758 
11759 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11760                                                  DAGCombinerInfo &DCI) const {
11761   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11762          "Should be called with a BUILD_VECTOR node");
11763 
11764   SelectionDAG &DAG = DCI.DAG;
11765   SDLoc dl(N);
11766 
11767   if (!Subtarget.hasVSX())
11768     return SDValue();
11769 
11770   // The target independent DAG combiner will leave a build_vector of
11771   // float-to-int conversions intact. We can generate MUCH better code for
11772   // a float-to-int conversion of a vector of floats.
11773   SDValue FirstInput = N->getOperand(0);
11774   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11775     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11776     if (Reduced)
11777       return Reduced;
11778   }
11779 
11780   // If we're building a vector out of consecutive loads, just load that
11781   // vector type.
11782   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11783   if (Reduced)
11784     return Reduced;
11785 
11786   // If we're building a vector out of extended elements from another vector
11787   // we have P9 vector integer extend instructions.
11788   if (Subtarget.hasP9Altivec()) {
11789     Reduced = combineBVOfVecSExt(N, DAG);
11790     if (Reduced)
11791       return Reduced;
11792   }
11793 
11794 
11795   if (N->getValueType(0) != MVT::v2f64)
11796     return SDValue();
11797 
11798   // Looking for:
11799   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11800   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11801       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11802     return SDValue();
11803   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11804       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11805     return SDValue();
11806   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11807     return SDValue();
11808 
11809   SDValue Ext1 = FirstInput.getOperand(0);
11810   SDValue Ext2 = N->getOperand(1).getOperand(0);
11811   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11812      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11813     return SDValue();
11814 
11815   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11816   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11817   if (!Ext1Op || !Ext2Op)
11818     return SDValue();
11819   if (Ext1.getValueType() != MVT::i32 ||
11820       Ext2.getValueType() != MVT::i32)
11821   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11822     return SDValue();
11823 
11824   int FirstElem = Ext1Op->getZExtValue();
11825   int SecondElem = Ext2Op->getZExtValue();
11826   int SubvecIdx;
11827   if (FirstElem == 0 && SecondElem == 1)
11828     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11829   else if (FirstElem == 2 && SecondElem == 3)
11830     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11831   else
11832     return SDValue();
11833 
11834   SDValue SrcVec = Ext1.getOperand(0);
11835   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11836     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11837   return DAG.getNode(NodeType, dl, MVT::v2f64,
11838                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11839 }
11840 
11841 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11842                                               DAGCombinerInfo &DCI) const {
11843   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11844           N->getOpcode() == ISD::UINT_TO_FP) &&
11845          "Need an int -> FP conversion node here");
11846 
11847   if (useSoftFloat() || !Subtarget.has64BitSupport())
11848     return SDValue();
11849 
11850   SelectionDAG &DAG = DCI.DAG;
11851   SDLoc dl(N);
11852   SDValue Op(N, 0);
11853 
11854   SDValue FirstOperand(Op.getOperand(0));
11855   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11856     (FirstOperand.getValueType() == MVT::i8 ||
11857      FirstOperand.getValueType() == MVT::i16);
11858   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11859     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11860     bool DstDouble = Op.getValueType() == MVT::f64;
11861     unsigned ConvOp = Signed ?
11862       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11863       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11864     SDValue WidthConst =
11865       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11866                             dl, false);
11867     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11868     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11869     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11870                                          DAG.getVTList(MVT::f64, MVT::Other),
11871                                          Ops, MVT::i8, LDN->getMemOperand());
11872 
11873     // For signed conversion, we need to sign-extend the value in the VSR
11874     if (Signed) {
11875       SDValue ExtOps[] = { Ld, WidthConst };
11876       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11877       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11878     } else
11879       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11880   }
11881 
11882   // Don't handle ppc_fp128 here or i1 conversions.
11883   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11884     return SDValue();
11885   if (Op.getOperand(0).getValueType() == MVT::i1)
11886     return SDValue();
11887 
11888   // For i32 intermediate values, unfortunately, the conversion functions
11889   // leave the upper 32 bits of the value are undefined. Within the set of
11890   // scalar instructions, we have no method for zero- or sign-extending the
11891   // value. Thus, we cannot handle i32 intermediate values here.
11892   if (Op.getOperand(0).getValueType() == MVT::i32)
11893     return SDValue();
11894 
11895   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11896          "UINT_TO_FP is supported only with FPCVT");
11897 
11898   // If we have FCFIDS, then use it when converting to single-precision.
11899   // Otherwise, convert to double-precision and then round.
11900   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11901                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11902                                                             : PPCISD::FCFIDS)
11903                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11904                                                             : PPCISD::FCFID);
11905   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11906                   ? MVT::f32
11907                   : MVT::f64;
11908 
11909   // If we're converting from a float, to an int, and back to a float again,
11910   // then we don't need the store/load pair at all.
11911   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11912        Subtarget.hasFPCVT()) ||
11913       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11914     SDValue Src = Op.getOperand(0).getOperand(0);
11915     if (Src.getValueType() == MVT::f32) {
11916       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11917       DCI.AddToWorklist(Src.getNode());
11918     } else if (Src.getValueType() != MVT::f64) {
11919       // Make sure that we don't pick up a ppc_fp128 source value.
11920       return SDValue();
11921     }
11922 
11923     unsigned FCTOp =
11924       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11925                                                         PPCISD::FCTIDUZ;
11926 
11927     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11928     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11929 
11930     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11931       FP = DAG.getNode(ISD::FP_ROUND, dl,
11932                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11933       DCI.AddToWorklist(FP.getNode());
11934     }
11935 
11936     return FP;
11937   }
11938 
11939   return SDValue();
11940 }
11941 
11942 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11943 // builtins) into loads with swaps.
11944 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11945                                               DAGCombinerInfo &DCI) const {
11946   SelectionDAG &DAG = DCI.DAG;
11947   SDLoc dl(N);
11948   SDValue Chain;
11949   SDValue Base;
11950   MachineMemOperand *MMO;
11951 
11952   switch (N->getOpcode()) {
11953   default:
11954     llvm_unreachable("Unexpected opcode for little endian VSX load");
11955   case ISD::LOAD: {
11956     LoadSDNode *LD = cast<LoadSDNode>(N);
11957     Chain = LD->getChain();
11958     Base = LD->getBasePtr();
11959     MMO = LD->getMemOperand();
11960     // If the MMO suggests this isn't a load of a full vector, leave
11961     // things alone.  For a built-in, we have to make the change for
11962     // correctness, so if there is a size problem that will be a bug.
11963     if (MMO->getSize() < 16)
11964       return SDValue();
11965     break;
11966   }
11967   case ISD::INTRINSIC_W_CHAIN: {
11968     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11969     Chain = Intrin->getChain();
11970     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11971     // us what we want. Get operand 2 instead.
11972     Base = Intrin->getOperand(2);
11973     MMO = Intrin->getMemOperand();
11974     break;
11975   }
11976   }
11977 
11978   MVT VecTy = N->getValueType(0).getSimpleVT();
11979 
11980   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11981   // aligned and the type is a vector with elements up to 4 bytes
11982   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11983       && VecTy.getScalarSizeInBits() <= 32 ) {
11984     return SDValue();
11985   }
11986 
11987   SDValue LoadOps[] = { Chain, Base };
11988   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11989                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11990                                          LoadOps, MVT::v2f64, MMO);
11991 
11992   DCI.AddToWorklist(Load.getNode());
11993   Chain = Load.getValue(1);
11994   SDValue Swap = DAG.getNode(
11995       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11996   DCI.AddToWorklist(Swap.getNode());
11997 
11998   // Add a bitcast if the resulting load type doesn't match v2f64.
11999   if (VecTy != MVT::v2f64) {
12000     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12001     DCI.AddToWorklist(N.getNode());
12002     // Package {bitcast value, swap's chain} to match Load's shape.
12003     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12004                        N, Swap.getValue(1));
12005   }
12006 
12007   return Swap;
12008 }
12009 
12010 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12011 // builtins) into stores with swaps.
12012 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12013                                                DAGCombinerInfo &DCI) const {
12014   SelectionDAG &DAG = DCI.DAG;
12015   SDLoc dl(N);
12016   SDValue Chain;
12017   SDValue Base;
12018   unsigned SrcOpnd;
12019   MachineMemOperand *MMO;
12020 
12021   switch (N->getOpcode()) {
12022   default:
12023     llvm_unreachable("Unexpected opcode for little endian VSX store");
12024   case ISD::STORE: {
12025     StoreSDNode *ST = cast<StoreSDNode>(N);
12026     Chain = ST->getChain();
12027     Base = ST->getBasePtr();
12028     MMO = ST->getMemOperand();
12029     SrcOpnd = 1;
12030     // If the MMO suggests this isn't a store of a full vector, leave
12031     // things alone.  For a built-in, we have to make the change for
12032     // correctness, so if there is a size problem that will be a bug.
12033     if (MMO->getSize() < 16)
12034       return SDValue();
12035     break;
12036   }
12037   case ISD::INTRINSIC_VOID: {
12038     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12039     Chain = Intrin->getChain();
12040     // Intrin->getBasePtr() oddly does not get what we want.
12041     Base = Intrin->getOperand(3);
12042     MMO = Intrin->getMemOperand();
12043     SrcOpnd = 2;
12044     break;
12045   }
12046   }
12047 
12048   SDValue Src = N->getOperand(SrcOpnd);
12049   MVT VecTy = Src.getValueType().getSimpleVT();
12050 
12051   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12052   // aligned and the type is a vector with elements up to 4 bytes
12053   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12054       && VecTy.getScalarSizeInBits() <= 32 ) {
12055     return SDValue();
12056   }
12057 
12058   // All stores are done as v2f64 and possible bit cast.
12059   if (VecTy != MVT::v2f64) {
12060     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12061     DCI.AddToWorklist(Src.getNode());
12062   }
12063 
12064   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12065                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12066   DCI.AddToWorklist(Swap.getNode());
12067   Chain = Swap.getValue(1);
12068   SDValue StoreOps[] = { Chain, Swap, Base };
12069   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12070                                           DAG.getVTList(MVT::Other),
12071                                           StoreOps, VecTy, MMO);
12072   DCI.AddToWorklist(Store.getNode());
12073   return Store;
12074 }
12075 
12076 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12077                                              DAGCombinerInfo &DCI) const {
12078   SelectionDAG &DAG = DCI.DAG;
12079   SDLoc dl(N);
12080   switch (N->getOpcode()) {
12081   default: break;
12082   case ISD::SHL:
12083     return combineSHL(N, DCI);
12084   case ISD::SRA:
12085     return combineSRA(N, DCI);
12086   case ISD::SRL:
12087     return combineSRL(N, DCI);
12088   case PPCISD::SHL:
12089     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12090         return N->getOperand(0);
12091     break;
12092   case PPCISD::SRL:
12093     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12094         return N->getOperand(0);
12095     break;
12096   case PPCISD::SRA:
12097     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12098       if (C->isNullValue() ||   //  0 >>s V -> 0.
12099           C->isAllOnesValue())    // -1 >>s V -> -1.
12100         return N->getOperand(0);
12101     }
12102     break;
12103   case ISD::SIGN_EXTEND:
12104   case ISD::ZERO_EXTEND:
12105   case ISD::ANY_EXTEND:
12106     return DAGCombineExtBoolTrunc(N, DCI);
12107   case ISD::TRUNCATE:
12108   case ISD::SETCC:
12109   case ISD::SELECT_CC:
12110     return DAGCombineTruncBoolExt(N, DCI);
12111   case ISD::SINT_TO_FP:
12112   case ISD::UINT_TO_FP:
12113     return combineFPToIntToFP(N, DCI);
12114   case ISD::STORE: {
12115     EVT Op1VT = N->getOperand(1).getValueType();
12116     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
12117       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
12118 
12119     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
12120     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
12121         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
12122         ValidTypeForStoreFltAsInt &&
12123         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
12124       SDValue Val = N->getOperand(1).getOperand(0);
12125       if (Val.getValueType() == MVT::f32) {
12126         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12127         DCI.AddToWorklist(Val.getNode());
12128       }
12129       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
12130       DCI.AddToWorklist(Val.getNode());
12131 
12132       if (Op1VT == MVT::i32) {
12133         SDValue Ops[] = {
12134           N->getOperand(0), Val, N->getOperand(2),
12135           DAG.getValueType(N->getOperand(1).getValueType())
12136         };
12137 
12138         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
12139                 DAG.getVTList(MVT::Other), Ops,
12140                 cast<StoreSDNode>(N)->getMemoryVT(),
12141                 cast<StoreSDNode>(N)->getMemOperand());
12142       } else {
12143         unsigned WidthInBytes =
12144           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
12145         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
12146 
12147         SDValue Ops[] = {
12148           N->getOperand(0), Val, N->getOperand(2), WidthConst,
12149           DAG.getValueType(N->getOperand(1).getValueType())
12150         };
12151         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
12152                                       DAG.getVTList(MVT::Other), Ops,
12153                                       cast<StoreSDNode>(N)->getMemoryVT(),
12154                                       cast<StoreSDNode>(N)->getMemOperand());
12155       }
12156 
12157       DCI.AddToWorklist(Val.getNode());
12158       return Val;
12159     }
12160 
12161     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12162     if (cast<StoreSDNode>(N)->isUnindexed() &&
12163         N->getOperand(1).getOpcode() == ISD::BSWAP &&
12164         N->getOperand(1).getNode()->hasOneUse() &&
12165         (N->getOperand(1).getValueType() == MVT::i32 ||
12166          N->getOperand(1).getValueType() == MVT::i16 ||
12167          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12168           N->getOperand(1).getValueType() == MVT::i64))) {
12169       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12170       // Do an any-extend to 32-bits if this is a half-word input.
12171       if (BSwapOp.getValueType() == MVT::i16)
12172         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12173 
12174       // If the type of BSWAP operand is wider than stored memory width
12175       // it need to be shifted to the right side before STBRX.
12176       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12177       if (Op1VT.bitsGT(mVT)) {
12178         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12179         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12180                               DAG.getConstant(Shift, dl, MVT::i32));
12181         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12182         if (Op1VT == MVT::i64)
12183           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12184       }
12185 
12186       SDValue Ops[] = {
12187         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12188       };
12189       return
12190         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12191                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12192                                 cast<StoreSDNode>(N)->getMemOperand());
12193     }
12194 
12195     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12196     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12197     EVT VT = N->getOperand(1).getValueType();
12198     if (VT.isSimple()) {
12199       MVT StoreVT = VT.getSimpleVT();
12200       if (Subtarget.needsSwapsForVSXMemOps() &&
12201           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12202            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12203         return expandVSXStoreForLE(N, DCI);
12204     }
12205     break;
12206   }
12207   case ISD::LOAD: {
12208     LoadSDNode *LD = cast<LoadSDNode>(N);
12209     EVT VT = LD->getValueType(0);
12210 
12211     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12212     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12213     if (VT.isSimple()) {
12214       MVT LoadVT = VT.getSimpleVT();
12215       if (Subtarget.needsSwapsForVSXMemOps() &&
12216           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12217            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12218         return expandVSXLoadForLE(N, DCI);
12219     }
12220 
12221     // We sometimes end up with a 64-bit integer load, from which we extract
12222     // two single-precision floating-point numbers. This happens with
12223     // std::complex<float>, and other similar structures, because of the way we
12224     // canonicalize structure copies. However, if we lack direct moves,
12225     // then the final bitcasts from the extracted integer values to the
12226     // floating-point numbers turn into store/load pairs. Even with direct moves,
12227     // just loading the two floating-point numbers is likely better.
12228     auto ReplaceTwoFloatLoad = [&]() {
12229       if (VT != MVT::i64)
12230         return false;
12231 
12232       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12233           LD->isVolatile())
12234         return false;
12235 
12236       //  We're looking for a sequence like this:
12237       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12238       //      t16: i64 = srl t13, Constant:i32<32>
12239       //    t17: i32 = truncate t16
12240       //  t18: f32 = bitcast t17
12241       //    t19: i32 = truncate t13
12242       //  t20: f32 = bitcast t19
12243 
12244       if (!LD->hasNUsesOfValue(2, 0))
12245         return false;
12246 
12247       auto UI = LD->use_begin();
12248       while (UI.getUse().getResNo() != 0) ++UI;
12249       SDNode *Trunc = *UI++;
12250       while (UI.getUse().getResNo() != 0) ++UI;
12251       SDNode *RightShift = *UI;
12252       if (Trunc->getOpcode() != ISD::TRUNCATE)
12253         std::swap(Trunc, RightShift);
12254 
12255       if (Trunc->getOpcode() != ISD::TRUNCATE ||
12256           Trunc->getValueType(0) != MVT::i32 ||
12257           !Trunc->hasOneUse())
12258         return false;
12259       if (RightShift->getOpcode() != ISD::SRL ||
12260           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12261           RightShift->getConstantOperandVal(1) != 32 ||
12262           !RightShift->hasOneUse())
12263         return false;
12264 
12265       SDNode *Trunc2 = *RightShift->use_begin();
12266       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12267           Trunc2->getValueType(0) != MVT::i32 ||
12268           !Trunc2->hasOneUse())
12269         return false;
12270 
12271       SDNode *Bitcast = *Trunc->use_begin();
12272       SDNode *Bitcast2 = *Trunc2->use_begin();
12273 
12274       if (Bitcast->getOpcode() != ISD::BITCAST ||
12275           Bitcast->getValueType(0) != MVT::f32)
12276         return false;
12277       if (Bitcast2->getOpcode() != ISD::BITCAST ||
12278           Bitcast2->getValueType(0) != MVT::f32)
12279         return false;
12280 
12281       if (Subtarget.isLittleEndian())
12282         std::swap(Bitcast, Bitcast2);
12283 
12284       // Bitcast has the second float (in memory-layout order) and Bitcast2
12285       // has the first one.
12286 
12287       SDValue BasePtr = LD->getBasePtr();
12288       if (LD->isIndexed()) {
12289         assert(LD->getAddressingMode() == ISD::PRE_INC &&
12290                "Non-pre-inc AM on PPC?");
12291         BasePtr =
12292           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12293                       LD->getOffset());
12294       }
12295 
12296       auto MMOFlags =
12297           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12298       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12299                                       LD->getPointerInfo(), LD->getAlignment(),
12300                                       MMOFlags, LD->getAAInfo());
12301       SDValue AddPtr =
12302         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12303                     BasePtr, DAG.getIntPtrConstant(4, dl));
12304       SDValue FloatLoad2 = DAG.getLoad(
12305           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12306           LD->getPointerInfo().getWithOffset(4),
12307           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12308 
12309       if (LD->isIndexed()) {
12310         // Note that DAGCombine should re-form any pre-increment load(s) from
12311         // what is produced here if that makes sense.
12312         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12313       }
12314 
12315       DCI.CombineTo(Bitcast2, FloatLoad);
12316       DCI.CombineTo(Bitcast, FloatLoad2);
12317 
12318       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12319                                     SDValue(FloatLoad2.getNode(), 1));
12320       return true;
12321     };
12322 
12323     if (ReplaceTwoFloatLoad())
12324       return SDValue(N, 0);
12325 
12326     EVT MemVT = LD->getMemoryVT();
12327     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12328     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12329     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12330     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12331     if (LD->isUnindexed() && VT.isVector() &&
12332         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12333           // P8 and later hardware should just use LOAD.
12334           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12335                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12336          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12337           LD->getAlignment() >= ScalarABIAlignment)) &&
12338         LD->getAlignment() < ABIAlignment) {
12339       // This is a type-legal unaligned Altivec or QPX load.
12340       SDValue Chain = LD->getChain();
12341       SDValue Ptr = LD->getBasePtr();
12342       bool isLittleEndian = Subtarget.isLittleEndian();
12343 
12344       // This implements the loading of unaligned vectors as described in
12345       // the venerable Apple Velocity Engine overview. Specifically:
12346       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12347       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12348       //
12349       // The general idea is to expand a sequence of one or more unaligned
12350       // loads into an alignment-based permutation-control instruction (lvsl
12351       // or lvsr), a series of regular vector loads (which always truncate
12352       // their input address to an aligned address), and a series of
12353       // permutations.  The results of these permutations are the requested
12354       // loaded values.  The trick is that the last "extra" load is not taken
12355       // from the address you might suspect (sizeof(vector) bytes after the
12356       // last requested load), but rather sizeof(vector) - 1 bytes after the
12357       // last requested vector. The point of this is to avoid a page fault if
12358       // the base address happened to be aligned. This works because if the
12359       // base address is aligned, then adding less than a full vector length
12360       // will cause the last vector in the sequence to be (re)loaded.
12361       // Otherwise, the next vector will be fetched as you might suspect was
12362       // necessary.
12363 
12364       // We might be able to reuse the permutation generation from
12365       // a different base address offset from this one by an aligned amount.
12366       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12367       // optimization later.
12368       Intrinsic::ID Intr, IntrLD, IntrPerm;
12369       MVT PermCntlTy, PermTy, LDTy;
12370       if (Subtarget.hasAltivec()) {
12371         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
12372                                  Intrinsic::ppc_altivec_lvsl;
12373         IntrLD = Intrinsic::ppc_altivec_lvx;
12374         IntrPerm = Intrinsic::ppc_altivec_vperm;
12375         PermCntlTy = MVT::v16i8;
12376         PermTy = MVT::v4i32;
12377         LDTy = MVT::v4i32;
12378       } else {
12379         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12380                                        Intrinsic::ppc_qpx_qvlpcls;
12381         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12382                                        Intrinsic::ppc_qpx_qvlfs;
12383         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12384         PermCntlTy = MVT::v4f64;
12385         PermTy = MVT::v4f64;
12386         LDTy = MemVT.getSimpleVT();
12387       }
12388 
12389       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12390 
12391       // Create the new MMO for the new base load. It is like the original MMO,
12392       // but represents an area in memory almost twice the vector size centered
12393       // on the original address. If the address is unaligned, we might start
12394       // reading up to (sizeof(vector)-1) bytes below the address of the
12395       // original unaligned load.
12396       MachineFunction &MF = DAG.getMachineFunction();
12397       MachineMemOperand *BaseMMO =
12398         MF.getMachineMemOperand(LD->getMemOperand(),
12399                                 -(long)MemVT.getStoreSize()+1,
12400                                 2*MemVT.getStoreSize()-1);
12401 
12402       // Create the new base load.
12403       SDValue LDXIntID =
12404           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12405       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12406       SDValue BaseLoad =
12407         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12408                                 DAG.getVTList(PermTy, MVT::Other),
12409                                 BaseLoadOps, LDTy, BaseMMO);
12410 
12411       // Note that the value of IncOffset (which is provided to the next
12412       // load's pointer info offset value, and thus used to calculate the
12413       // alignment), and the value of IncValue (which is actually used to
12414       // increment the pointer value) are different! This is because we
12415       // require the next load to appear to be aligned, even though it
12416       // is actually offset from the base pointer by a lesser amount.
12417       int IncOffset = VT.getSizeInBits() / 8;
12418       int IncValue = IncOffset;
12419 
12420       // Walk (both up and down) the chain looking for another load at the real
12421       // (aligned) offset (the alignment of the other load does not matter in
12422       // this case). If found, then do not use the offset reduction trick, as
12423       // that will prevent the loads from being later combined (as they would
12424       // otherwise be duplicates).
12425       if (!findConsecutiveLoad(LD, DAG))
12426         --IncValue;
12427 
12428       SDValue Increment =
12429           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12430       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12431 
12432       MachineMemOperand *ExtraMMO =
12433         MF.getMachineMemOperand(LD->getMemOperand(),
12434                                 1, 2*MemVT.getStoreSize()-1);
12435       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12436       SDValue ExtraLoad =
12437         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12438                                 DAG.getVTList(PermTy, MVT::Other),
12439                                 ExtraLoadOps, LDTy, ExtraMMO);
12440 
12441       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12442         BaseLoad.getValue(1), ExtraLoad.getValue(1));
12443 
12444       // Because vperm has a big-endian bias, we must reverse the order
12445       // of the input vectors and complement the permute control vector
12446       // when generating little endian code.  We have already handled the
12447       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12448       // and ExtraLoad here.
12449       SDValue Perm;
12450       if (isLittleEndian)
12451         Perm = BuildIntrinsicOp(IntrPerm,
12452                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12453       else
12454         Perm = BuildIntrinsicOp(IntrPerm,
12455                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12456 
12457       if (VT != PermTy)
12458         Perm = Subtarget.hasAltivec() ?
12459                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12460                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12461                                DAG.getTargetConstant(1, dl, MVT::i64));
12462                                // second argument is 1 because this rounding
12463                                // is always exact.
12464 
12465       // The output of the permutation is our loaded result, the TokenFactor is
12466       // our new chain.
12467       DCI.CombineTo(N, Perm, TF);
12468       return SDValue(N, 0);
12469     }
12470     }
12471     break;
12472     case ISD::INTRINSIC_WO_CHAIN: {
12473       bool isLittleEndian = Subtarget.isLittleEndian();
12474       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12475       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12476                                            : Intrinsic::ppc_altivec_lvsl);
12477       if ((IID == Intr ||
12478            IID == Intrinsic::ppc_qpx_qvlpcld  ||
12479            IID == Intrinsic::ppc_qpx_qvlpcls) &&
12480         N->getOperand(1)->getOpcode() == ISD::ADD) {
12481         SDValue Add = N->getOperand(1);
12482 
12483         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12484                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12485 
12486         if (DAG.MaskedValueIsZero(Add->getOperand(1),
12487                                   APInt::getAllOnesValue(Bits /* alignment */)
12488                                       .zext(Add.getScalarValueSizeInBits()))) {
12489           SDNode *BasePtr = Add->getOperand(0).getNode();
12490           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12491                                     UE = BasePtr->use_end();
12492                UI != UE; ++UI) {
12493             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12494                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12495               // We've found another LVSL/LVSR, and this address is an aligned
12496               // multiple of that one. The results will be the same, so use the
12497               // one we've just found instead.
12498 
12499               return SDValue(*UI, 0);
12500             }
12501           }
12502         }
12503 
12504         if (isa<ConstantSDNode>(Add->getOperand(1))) {
12505           SDNode *BasePtr = Add->getOperand(0).getNode();
12506           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12507                UE = BasePtr->use_end(); UI != UE; ++UI) {
12508             if (UI->getOpcode() == ISD::ADD &&
12509                 isa<ConstantSDNode>(UI->getOperand(1)) &&
12510                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12511                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12512                 (1ULL << Bits) == 0) {
12513               SDNode *OtherAdd = *UI;
12514               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12515                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
12516                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12517                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12518                   return SDValue(*VI, 0);
12519                 }
12520               }
12521             }
12522           }
12523         }
12524       }
12525     }
12526 
12527     break;
12528   case ISD::INTRINSIC_W_CHAIN:
12529     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12530     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12531     if (Subtarget.needsSwapsForVSXMemOps()) {
12532       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12533       default:
12534         break;
12535       case Intrinsic::ppc_vsx_lxvw4x:
12536       case Intrinsic::ppc_vsx_lxvd2x:
12537         return expandVSXLoadForLE(N, DCI);
12538       }
12539     }
12540     break;
12541   case ISD::INTRINSIC_VOID:
12542     // For little endian, VSX stores require generating xxswapd/stxvd2x.
12543     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12544     if (Subtarget.needsSwapsForVSXMemOps()) {
12545       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12546       default:
12547         break;
12548       case Intrinsic::ppc_vsx_stxvw4x:
12549       case Intrinsic::ppc_vsx_stxvd2x:
12550         return expandVSXStoreForLE(N, DCI);
12551       }
12552     }
12553     break;
12554   case ISD::BSWAP:
12555     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12556     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12557         N->getOperand(0).hasOneUse() &&
12558         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12559          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12560           N->getValueType(0) == MVT::i64))) {
12561       SDValue Load = N->getOperand(0);
12562       LoadSDNode *LD = cast<LoadSDNode>(Load);
12563       // Create the byte-swapping load.
12564       SDValue Ops[] = {
12565         LD->getChain(),    // Chain
12566         LD->getBasePtr(),  // Ptr
12567         DAG.getValueType(N->getValueType(0)) // VT
12568       };
12569       SDValue BSLoad =
12570         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12571                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12572                                               MVT::i64 : MVT::i32, MVT::Other),
12573                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
12574 
12575       // If this is an i16 load, insert the truncate.
12576       SDValue ResVal = BSLoad;
12577       if (N->getValueType(0) == MVT::i16)
12578         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12579 
12580       // First, combine the bswap away.  This makes the value produced by the
12581       // load dead.
12582       DCI.CombineTo(N, ResVal);
12583 
12584       // Next, combine the load away, we give it a bogus result value but a real
12585       // chain result.  The result value is dead because the bswap is dead.
12586       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12587 
12588       // Return N so it doesn't get rechecked!
12589       return SDValue(N, 0);
12590     }
12591     break;
12592   case PPCISD::VCMP:
12593     // If a VCMPo node already exists with exactly the same operands as this
12594     // node, use its result instead of this node (VCMPo computes both a CR6 and
12595     // a normal output).
12596     //
12597     if (!N->getOperand(0).hasOneUse() &&
12598         !N->getOperand(1).hasOneUse() &&
12599         !N->getOperand(2).hasOneUse()) {
12600 
12601       // Scan all of the users of the LHS, looking for VCMPo's that match.
12602       SDNode *VCMPoNode = nullptr;
12603 
12604       SDNode *LHSN = N->getOperand(0).getNode();
12605       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12606            UI != E; ++UI)
12607         if (UI->getOpcode() == PPCISD::VCMPo &&
12608             UI->getOperand(1) == N->getOperand(1) &&
12609             UI->getOperand(2) == N->getOperand(2) &&
12610             UI->getOperand(0) == N->getOperand(0)) {
12611           VCMPoNode = *UI;
12612           break;
12613         }
12614 
12615       // If there is no VCMPo node, or if the flag value has a single use, don't
12616       // transform this.
12617       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
12618         break;
12619 
12620       // Look at the (necessarily single) use of the flag value.  If it has a
12621       // chain, this transformation is more complex.  Note that multiple things
12622       // could use the value result, which we should ignore.
12623       SDNode *FlagUser = nullptr;
12624       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
12625            FlagUser == nullptr; ++UI) {
12626         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
12627         SDNode *User = *UI;
12628         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
12629           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12630             FlagUser = User;
12631             break;
12632           }
12633         }
12634       }
12635 
12636       // If the user is a MFOCRF instruction, we know this is safe.
12637       // Otherwise we give up for right now.
12638       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12639         return SDValue(VCMPoNode, 0);
12640     }
12641     break;
12642   case ISD::BRCOND: {
12643     SDValue Cond = N->getOperand(1);
12644     SDValue Target = N->getOperand(2);
12645 
12646     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12647         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12648           Intrinsic::ppc_is_decremented_ctr_nonzero) {
12649 
12650       // We now need to make the intrinsic dead (it cannot be instruction
12651       // selected).
12652       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12653       assert(Cond.getNode()->hasOneUse() &&
12654              "Counter decrement has more than one use");
12655 
12656       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12657                          N->getOperand(0), Target);
12658     }
12659   }
12660   break;
12661   case ISD::BR_CC: {
12662     // If this is a branch on an altivec predicate comparison, lower this so
12663     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
12664     // lowering is done pre-legalize, because the legalizer lowers the predicate
12665     // compare down to code that is difficult to reassemble.
12666     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12667     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12668 
12669     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12670     // value. If so, pass-through the AND to get to the intrinsic.
12671     if (LHS.getOpcode() == ISD::AND &&
12672         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12673         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12674           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12675         isa<ConstantSDNode>(LHS.getOperand(1)) &&
12676         !isNullConstant(LHS.getOperand(1)))
12677       LHS = LHS.getOperand(0);
12678 
12679     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12680         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12681           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12682         isa<ConstantSDNode>(RHS)) {
12683       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12684              "Counter decrement comparison is not EQ or NE");
12685 
12686       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12687       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12688                     (CC == ISD::SETNE && !Val);
12689 
12690       // We now need to make the intrinsic dead (it cannot be instruction
12691       // selected).
12692       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12693       assert(LHS.getNode()->hasOneUse() &&
12694              "Counter decrement has more than one use");
12695 
12696       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12697                          N->getOperand(0), N->getOperand(4));
12698     }
12699 
12700     int CompareOpc;
12701     bool isDot;
12702 
12703     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12704         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12705         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12706       assert(isDot && "Can't compare against a vector result!");
12707 
12708       // If this is a comparison against something other than 0/1, then we know
12709       // that the condition is never/always true.
12710       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12711       if (Val != 0 && Val != 1) {
12712         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
12713           return N->getOperand(0);
12714         // Always !=, turn it into an unconditional branch.
12715         return DAG.getNode(ISD::BR, dl, MVT::Other,
12716                            N->getOperand(0), N->getOperand(4));
12717       }
12718 
12719       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12720 
12721       // Create the PPCISD altivec 'dot' comparison node.
12722       SDValue Ops[] = {
12723         LHS.getOperand(2),  // LHS of compare
12724         LHS.getOperand(3),  // RHS of compare
12725         DAG.getConstant(CompareOpc, dl, MVT::i32)
12726       };
12727       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12728       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12729 
12730       // Unpack the result based on how the target uses it.
12731       PPC::Predicate CompOpc;
12732       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12733       default:  // Can't happen, don't crash on invalid number though.
12734       case 0:   // Branch on the value of the EQ bit of CR6.
12735         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12736         break;
12737       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12738         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12739         break;
12740       case 2:   // Branch on the value of the LT bit of CR6.
12741         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12742         break;
12743       case 3:   // Branch on the inverted value of the LT bit of CR6.
12744         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12745         break;
12746       }
12747 
12748       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12749                          DAG.getConstant(CompOpc, dl, MVT::i32),
12750                          DAG.getRegister(PPC::CR6, MVT::i32),
12751                          N->getOperand(4), CompNode.getValue(1));
12752     }
12753     break;
12754   }
12755   case ISD::BUILD_VECTOR:
12756     return DAGCombineBuildVector(N, DCI);
12757   }
12758 
12759   return SDValue();
12760 }
12761 
12762 SDValue
12763 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12764                                   SelectionDAG &DAG,
12765                                   std::vector<SDNode *> *Created) const {
12766   // fold (sdiv X, pow2)
12767   EVT VT = N->getValueType(0);
12768   if (VT == MVT::i64 && !Subtarget.isPPC64())
12769     return SDValue();
12770   if ((VT != MVT::i32 && VT != MVT::i64) ||
12771       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12772     return SDValue();
12773 
12774   SDLoc DL(N);
12775   SDValue N0 = N->getOperand(0);
12776 
12777   bool IsNegPow2 = (-Divisor).isPowerOf2();
12778   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12779   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12780 
12781   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12782   if (Created)
12783     Created->push_back(Op.getNode());
12784 
12785   if (IsNegPow2) {
12786     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12787     if (Created)
12788       Created->push_back(Op.getNode());
12789   }
12790 
12791   return Op;
12792 }
12793 
12794 //===----------------------------------------------------------------------===//
12795 // Inline Assembly Support
12796 //===----------------------------------------------------------------------===//
12797 
12798 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12799                                                       KnownBits &Known,
12800                                                       const APInt &DemandedElts,
12801                                                       const SelectionDAG &DAG,
12802                                                       unsigned Depth) const {
12803   Known.resetAll();
12804   switch (Op.getOpcode()) {
12805   default: break;
12806   case PPCISD::LBRX: {
12807     // lhbrx is known to have the top bits cleared out.
12808     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12809       Known.Zero = 0xFFFF0000;
12810     break;
12811   }
12812   case ISD::INTRINSIC_WO_CHAIN: {
12813     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12814     default: break;
12815     case Intrinsic::ppc_altivec_vcmpbfp_p:
12816     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12817     case Intrinsic::ppc_altivec_vcmpequb_p:
12818     case Intrinsic::ppc_altivec_vcmpequh_p:
12819     case Intrinsic::ppc_altivec_vcmpequw_p:
12820     case Intrinsic::ppc_altivec_vcmpequd_p:
12821     case Intrinsic::ppc_altivec_vcmpgefp_p:
12822     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12823     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12824     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12825     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12826     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12827     case Intrinsic::ppc_altivec_vcmpgtub_p:
12828     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12829     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12830     case Intrinsic::ppc_altivec_vcmpgtud_p:
12831       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
12832       break;
12833     }
12834   }
12835   }
12836 }
12837 
12838 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12839   switch (Subtarget.getDarwinDirective()) {
12840   default: break;
12841   case PPC::DIR_970:
12842   case PPC::DIR_PWR4:
12843   case PPC::DIR_PWR5:
12844   case PPC::DIR_PWR5X:
12845   case PPC::DIR_PWR6:
12846   case PPC::DIR_PWR6X:
12847   case PPC::DIR_PWR7:
12848   case PPC::DIR_PWR8:
12849   case PPC::DIR_PWR9: {
12850     if (!ML)
12851       break;
12852 
12853     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12854 
12855     // For small loops (between 5 and 8 instructions), align to a 32-byte
12856     // boundary so that the entire loop fits in one instruction-cache line.
12857     uint64_t LoopSize = 0;
12858     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12859       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12860         LoopSize += TII->getInstSizeInBytes(*J);
12861         if (LoopSize > 32)
12862           break;
12863       }
12864 
12865     if (LoopSize > 16 && LoopSize <= 32)
12866       return 5;
12867 
12868     break;
12869   }
12870   }
12871 
12872   return TargetLowering::getPrefLoopAlignment(ML);
12873 }
12874 
12875 /// getConstraintType - Given a constraint, return the type of
12876 /// constraint it is for this target.
12877 PPCTargetLowering::ConstraintType
12878 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12879   if (Constraint.size() == 1) {
12880     switch (Constraint[0]) {
12881     default: break;
12882     case 'b':
12883     case 'r':
12884     case 'f':
12885     case 'd':
12886     case 'v':
12887     case 'y':
12888       return C_RegisterClass;
12889     case 'Z':
12890       // FIXME: While Z does indicate a memory constraint, it specifically
12891       // indicates an r+r address (used in conjunction with the 'y' modifier
12892       // in the replacement string). Currently, we're forcing the base
12893       // register to be r0 in the asm printer (which is interpreted as zero)
12894       // and forming the complete address in the second register. This is
12895       // suboptimal.
12896       return C_Memory;
12897     }
12898   } else if (Constraint == "wc") { // individual CR bits.
12899     return C_RegisterClass;
12900   } else if (Constraint == "wa" || Constraint == "wd" ||
12901              Constraint == "wf" || Constraint == "ws") {
12902     return C_RegisterClass; // VSX registers.
12903   }
12904   return TargetLowering::getConstraintType(Constraint);
12905 }
12906 
12907 /// Examine constraint type and operand type and determine a weight value.
12908 /// This object must already have been set up with the operand type
12909 /// and the current alternative constraint selected.
12910 TargetLowering::ConstraintWeight
12911 PPCTargetLowering::getSingleConstraintMatchWeight(
12912     AsmOperandInfo &info, const char *constraint) const {
12913   ConstraintWeight weight = CW_Invalid;
12914   Value *CallOperandVal = info.CallOperandVal;
12915     // If we don't have a value, we can't do a match,
12916     // but allow it at the lowest weight.
12917   if (!CallOperandVal)
12918     return CW_Default;
12919   Type *type = CallOperandVal->getType();
12920 
12921   // Look at the constraint type.
12922   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12923     return CW_Register; // an individual CR bit.
12924   else if ((StringRef(constraint) == "wa" ||
12925             StringRef(constraint) == "wd" ||
12926             StringRef(constraint) == "wf") &&
12927            type->isVectorTy())
12928     return CW_Register;
12929   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12930     return CW_Register;
12931 
12932   switch (*constraint) {
12933   default:
12934     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12935     break;
12936   case 'b':
12937     if (type->isIntegerTy())
12938       weight = CW_Register;
12939     break;
12940   case 'f':
12941     if (type->isFloatTy())
12942       weight = CW_Register;
12943     break;
12944   case 'd':
12945     if (type->isDoubleTy())
12946       weight = CW_Register;
12947     break;
12948   case 'v':
12949     if (type->isVectorTy())
12950       weight = CW_Register;
12951     break;
12952   case 'y':
12953     weight = CW_Register;
12954     break;
12955   case 'Z':
12956     weight = CW_Memory;
12957     break;
12958   }
12959   return weight;
12960 }
12961 
12962 std::pair<unsigned, const TargetRegisterClass *>
12963 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12964                                                 StringRef Constraint,
12965                                                 MVT VT) const {
12966   if (Constraint.size() == 1) {
12967     // GCC RS6000 Constraint Letters
12968     switch (Constraint[0]) {
12969     case 'b':   // R1-R31
12970       if (VT == MVT::i64 && Subtarget.isPPC64())
12971         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12972       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12973     case 'r':   // R0-R31
12974       if (VT == MVT::i64 && Subtarget.isPPC64())
12975         return std::make_pair(0U, &PPC::G8RCRegClass);
12976       return std::make_pair(0U, &PPC::GPRCRegClass);
12977     // 'd' and 'f' constraints are both defined to be "the floating point
12978     // registers", where one is for 32-bit and the other for 64-bit. We don't
12979     // really care overly much here so just give them all the same reg classes.
12980     case 'd':
12981     case 'f':
12982       if (VT == MVT::f32 || VT == MVT::i32)
12983         return std::make_pair(0U, &PPC::F4RCRegClass);
12984       if (VT == MVT::f64 || VT == MVT::i64)
12985         return std::make_pair(0U, &PPC::F8RCRegClass);
12986       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12987         return std::make_pair(0U, &PPC::QFRCRegClass);
12988       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12989         return std::make_pair(0U, &PPC::QSRCRegClass);
12990       break;
12991     case 'v':
12992       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12993         return std::make_pair(0U, &PPC::QFRCRegClass);
12994       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12995         return std::make_pair(0U, &PPC::QSRCRegClass);
12996       if (Subtarget.hasAltivec())
12997         return std::make_pair(0U, &PPC::VRRCRegClass);
12998     case 'y':   // crrc
12999       return std::make_pair(0U, &PPC::CRRCRegClass);
13000     }
13001   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13002     // An individual CR bit.
13003     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13004   } else if ((Constraint == "wa" || Constraint == "wd" ||
13005              Constraint == "wf") && Subtarget.hasVSX()) {
13006     return std::make_pair(0U, &PPC::VSRCRegClass);
13007   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13008     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13009       return std::make_pair(0U, &PPC::VSSRCRegClass);
13010     else
13011       return std::make_pair(0U, &PPC::VSFRCRegClass);
13012   }
13013 
13014   std::pair<unsigned, const TargetRegisterClass *> R =
13015       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13016 
13017   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13018   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13019   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13020   // register.
13021   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13022   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13023   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13024       PPC::GPRCRegClass.contains(R.first))
13025     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13026                             PPC::sub_32, &PPC::G8RCRegClass),
13027                           &PPC::G8RCRegClass);
13028 
13029   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13030   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13031     R.first = PPC::CR0;
13032     R.second = &PPC::CRRCRegClass;
13033   }
13034 
13035   return R;
13036 }
13037 
13038 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13039 /// vector.  If it is invalid, don't add anything to Ops.
13040 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13041                                                      std::string &Constraint,
13042                                                      std::vector<SDValue>&Ops,
13043                                                      SelectionDAG &DAG) const {
13044   SDValue Result;
13045 
13046   // Only support length 1 constraints.
13047   if (Constraint.length() > 1) return;
13048 
13049   char Letter = Constraint[0];
13050   switch (Letter) {
13051   default: break;
13052   case 'I':
13053   case 'J':
13054   case 'K':
13055   case 'L':
13056   case 'M':
13057   case 'N':
13058   case 'O':
13059   case 'P': {
13060     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13061     if (!CST) return; // Must be an immediate to match.
13062     SDLoc dl(Op);
13063     int64_t Value = CST->getSExtValue();
13064     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13065                          // numbers are printed as such.
13066     switch (Letter) {
13067     default: llvm_unreachable("Unknown constraint letter!");
13068     case 'I':  // "I" is a signed 16-bit constant.
13069       if (isInt<16>(Value))
13070         Result = DAG.getTargetConstant(Value, dl, TCVT);
13071       break;
13072     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13073       if (isShiftedUInt<16, 16>(Value))
13074         Result = DAG.getTargetConstant(Value, dl, TCVT);
13075       break;
13076     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13077       if (isShiftedInt<16, 16>(Value))
13078         Result = DAG.getTargetConstant(Value, dl, TCVT);
13079       break;
13080     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13081       if (isUInt<16>(Value))
13082         Result = DAG.getTargetConstant(Value, dl, TCVT);
13083       break;
13084     case 'M':  // "M" is a constant that is greater than 31.
13085       if (Value > 31)
13086         Result = DAG.getTargetConstant(Value, dl, TCVT);
13087       break;
13088     case 'N':  // "N" is a positive constant that is an exact power of two.
13089       if (Value > 0 && isPowerOf2_64(Value))
13090         Result = DAG.getTargetConstant(Value, dl, TCVT);
13091       break;
13092     case 'O':  // "O" is the constant zero.
13093       if (Value == 0)
13094         Result = DAG.getTargetConstant(Value, dl, TCVT);
13095       break;
13096     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13097       if (isInt<16>(-Value))
13098         Result = DAG.getTargetConstant(Value, dl, TCVT);
13099       break;
13100     }
13101     break;
13102   }
13103   }
13104 
13105   if (Result.getNode()) {
13106     Ops.push_back(Result);
13107     return;
13108   }
13109 
13110   // Handle standard constraint letters.
13111   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13112 }
13113 
13114 // isLegalAddressingMode - Return true if the addressing mode represented
13115 // by AM is legal for this target, for a load/store of the specified type.
13116 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13117                                               const AddrMode &AM, Type *Ty,
13118                                               unsigned AS, Instruction *I) const {
13119   // PPC does not allow r+i addressing modes for vectors!
13120   if (Ty->isVectorTy() && AM.BaseOffs != 0)
13121     return false;
13122 
13123   // PPC allows a sign-extended 16-bit immediate field.
13124   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13125     return false;
13126 
13127   // No global is ever allowed as a base.
13128   if (AM.BaseGV)
13129     return false;
13130 
13131   // PPC only support r+r,
13132   switch (AM.Scale) {
13133   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13134     break;
13135   case 1:
13136     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13137       return false;
13138     // Otherwise we have r+r or r+i.
13139     break;
13140   case 2:
13141     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13142       return false;
13143     // Allow 2*r as r+r.
13144     break;
13145   default:
13146     // No other scales are supported.
13147     return false;
13148   }
13149 
13150   return true;
13151 }
13152 
13153 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13154                                            SelectionDAG &DAG) const {
13155   MachineFunction &MF = DAG.getMachineFunction();
13156   MachineFrameInfo &MFI = MF.getFrameInfo();
13157   MFI.setReturnAddressIsTaken(true);
13158 
13159   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13160     return SDValue();
13161 
13162   SDLoc dl(Op);
13163   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13164 
13165   // Make sure the function does not optimize away the store of the RA to
13166   // the stack.
13167   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13168   FuncInfo->setLRStoreRequired();
13169   bool isPPC64 = Subtarget.isPPC64();
13170   auto PtrVT = getPointerTy(MF.getDataLayout());
13171 
13172   if (Depth > 0) {
13173     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13174     SDValue Offset =
13175         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13176                         isPPC64 ? MVT::i64 : MVT::i32);
13177     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13178                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13179                        MachinePointerInfo());
13180   }
13181 
13182   // Just load the return address off the stack.
13183   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13184   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13185                      MachinePointerInfo());
13186 }
13187 
13188 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13189                                           SelectionDAG &DAG) const {
13190   SDLoc dl(Op);
13191   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13192 
13193   MachineFunction &MF = DAG.getMachineFunction();
13194   MachineFrameInfo &MFI = MF.getFrameInfo();
13195   MFI.setFrameAddressIsTaken(true);
13196 
13197   EVT PtrVT = getPointerTy(MF.getDataLayout());
13198   bool isPPC64 = PtrVT == MVT::i64;
13199 
13200   // Naked functions never have a frame pointer, and so we use r1. For all
13201   // other functions, this decision must be delayed until during PEI.
13202   unsigned FrameReg;
13203   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
13204     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13205   else
13206     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13207 
13208   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13209                                          PtrVT);
13210   while (Depth--)
13211     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13212                             FrameAddr, MachinePointerInfo());
13213   return FrameAddr;
13214 }
13215 
13216 // FIXME? Maybe this could be a TableGen attribute on some registers and
13217 // this table could be generated automatically from RegInfo.
13218 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13219                                               SelectionDAG &DAG) const {
13220   bool isPPC64 = Subtarget.isPPC64();
13221   bool isDarwinABI = Subtarget.isDarwinABI();
13222 
13223   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13224       (!isPPC64 && VT != MVT::i32))
13225     report_fatal_error("Invalid register global variable type");
13226 
13227   bool is64Bit = isPPC64 && VT == MVT::i64;
13228   unsigned Reg = StringSwitch<unsigned>(RegName)
13229                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13230                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13231                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13232                                   (is64Bit ? PPC::X13 : PPC::R13))
13233                    .Default(0);
13234 
13235   if (Reg)
13236     return Reg;
13237   report_fatal_error("Invalid register name global variable");
13238 }
13239 
13240 bool
13241 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13242   // The PowerPC target isn't yet aware of offsets.
13243   return false;
13244 }
13245 
13246 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13247                                            const CallInst &I,
13248                                            unsigned Intrinsic) const {
13249   switch (Intrinsic) {
13250   case Intrinsic::ppc_qpx_qvlfd:
13251   case Intrinsic::ppc_qpx_qvlfs:
13252   case Intrinsic::ppc_qpx_qvlfcd:
13253   case Intrinsic::ppc_qpx_qvlfcs:
13254   case Intrinsic::ppc_qpx_qvlfiwa:
13255   case Intrinsic::ppc_qpx_qvlfiwz:
13256   case Intrinsic::ppc_altivec_lvx:
13257   case Intrinsic::ppc_altivec_lvxl:
13258   case Intrinsic::ppc_altivec_lvebx:
13259   case Intrinsic::ppc_altivec_lvehx:
13260   case Intrinsic::ppc_altivec_lvewx:
13261   case Intrinsic::ppc_vsx_lxvd2x:
13262   case Intrinsic::ppc_vsx_lxvw4x: {
13263     EVT VT;
13264     switch (Intrinsic) {
13265     case Intrinsic::ppc_altivec_lvebx:
13266       VT = MVT::i8;
13267       break;
13268     case Intrinsic::ppc_altivec_lvehx:
13269       VT = MVT::i16;
13270       break;
13271     case Intrinsic::ppc_altivec_lvewx:
13272       VT = MVT::i32;
13273       break;
13274     case Intrinsic::ppc_vsx_lxvd2x:
13275       VT = MVT::v2f64;
13276       break;
13277     case Intrinsic::ppc_qpx_qvlfd:
13278       VT = MVT::v4f64;
13279       break;
13280     case Intrinsic::ppc_qpx_qvlfs:
13281       VT = MVT::v4f32;
13282       break;
13283     case Intrinsic::ppc_qpx_qvlfcd:
13284       VT = MVT::v2f64;
13285       break;
13286     case Intrinsic::ppc_qpx_qvlfcs:
13287       VT = MVT::v2f32;
13288       break;
13289     default:
13290       VT = MVT::v4i32;
13291       break;
13292     }
13293 
13294     Info.opc = ISD::INTRINSIC_W_CHAIN;
13295     Info.memVT = VT;
13296     Info.ptrVal = I.getArgOperand(0);
13297     Info.offset = -VT.getStoreSize()+1;
13298     Info.size = 2*VT.getStoreSize()-1;
13299     Info.align = 1;
13300     Info.vol = false;
13301     Info.readMem = true;
13302     Info.writeMem = false;
13303     return true;
13304   }
13305   case Intrinsic::ppc_qpx_qvlfda:
13306   case Intrinsic::ppc_qpx_qvlfsa:
13307   case Intrinsic::ppc_qpx_qvlfcda:
13308   case Intrinsic::ppc_qpx_qvlfcsa:
13309   case Intrinsic::ppc_qpx_qvlfiwaa:
13310   case Intrinsic::ppc_qpx_qvlfiwza: {
13311     EVT VT;
13312     switch (Intrinsic) {
13313     case Intrinsic::ppc_qpx_qvlfda:
13314       VT = MVT::v4f64;
13315       break;
13316     case Intrinsic::ppc_qpx_qvlfsa:
13317       VT = MVT::v4f32;
13318       break;
13319     case Intrinsic::ppc_qpx_qvlfcda:
13320       VT = MVT::v2f64;
13321       break;
13322     case Intrinsic::ppc_qpx_qvlfcsa:
13323       VT = MVT::v2f32;
13324       break;
13325     default:
13326       VT = MVT::v4i32;
13327       break;
13328     }
13329 
13330     Info.opc = ISD::INTRINSIC_W_CHAIN;
13331     Info.memVT = VT;
13332     Info.ptrVal = I.getArgOperand(0);
13333     Info.offset = 0;
13334     Info.size = VT.getStoreSize();
13335     Info.align = 1;
13336     Info.vol = false;
13337     Info.readMem = true;
13338     Info.writeMem = false;
13339     return true;
13340   }
13341   case Intrinsic::ppc_qpx_qvstfd:
13342   case Intrinsic::ppc_qpx_qvstfs:
13343   case Intrinsic::ppc_qpx_qvstfcd:
13344   case Intrinsic::ppc_qpx_qvstfcs:
13345   case Intrinsic::ppc_qpx_qvstfiw:
13346   case Intrinsic::ppc_altivec_stvx:
13347   case Intrinsic::ppc_altivec_stvxl:
13348   case Intrinsic::ppc_altivec_stvebx:
13349   case Intrinsic::ppc_altivec_stvehx:
13350   case Intrinsic::ppc_altivec_stvewx:
13351   case Intrinsic::ppc_vsx_stxvd2x:
13352   case Intrinsic::ppc_vsx_stxvw4x: {
13353     EVT VT;
13354     switch (Intrinsic) {
13355     case Intrinsic::ppc_altivec_stvebx:
13356       VT = MVT::i8;
13357       break;
13358     case Intrinsic::ppc_altivec_stvehx:
13359       VT = MVT::i16;
13360       break;
13361     case Intrinsic::ppc_altivec_stvewx:
13362       VT = MVT::i32;
13363       break;
13364     case Intrinsic::ppc_vsx_stxvd2x:
13365       VT = MVT::v2f64;
13366       break;
13367     case Intrinsic::ppc_qpx_qvstfd:
13368       VT = MVT::v4f64;
13369       break;
13370     case Intrinsic::ppc_qpx_qvstfs:
13371       VT = MVT::v4f32;
13372       break;
13373     case Intrinsic::ppc_qpx_qvstfcd:
13374       VT = MVT::v2f64;
13375       break;
13376     case Intrinsic::ppc_qpx_qvstfcs:
13377       VT = MVT::v2f32;
13378       break;
13379     default:
13380       VT = MVT::v4i32;
13381       break;
13382     }
13383 
13384     Info.opc = ISD::INTRINSIC_VOID;
13385     Info.memVT = VT;
13386     Info.ptrVal = I.getArgOperand(1);
13387     Info.offset = -VT.getStoreSize()+1;
13388     Info.size = 2*VT.getStoreSize()-1;
13389     Info.align = 1;
13390     Info.vol = false;
13391     Info.readMem = false;
13392     Info.writeMem = true;
13393     return true;
13394   }
13395   case Intrinsic::ppc_qpx_qvstfda:
13396   case Intrinsic::ppc_qpx_qvstfsa:
13397   case Intrinsic::ppc_qpx_qvstfcda:
13398   case Intrinsic::ppc_qpx_qvstfcsa:
13399   case Intrinsic::ppc_qpx_qvstfiwa: {
13400     EVT VT;
13401     switch (Intrinsic) {
13402     case Intrinsic::ppc_qpx_qvstfda:
13403       VT = MVT::v4f64;
13404       break;
13405     case Intrinsic::ppc_qpx_qvstfsa:
13406       VT = MVT::v4f32;
13407       break;
13408     case Intrinsic::ppc_qpx_qvstfcda:
13409       VT = MVT::v2f64;
13410       break;
13411     case Intrinsic::ppc_qpx_qvstfcsa:
13412       VT = MVT::v2f32;
13413       break;
13414     default:
13415       VT = MVT::v4i32;
13416       break;
13417     }
13418 
13419     Info.opc = ISD::INTRINSIC_VOID;
13420     Info.memVT = VT;
13421     Info.ptrVal = I.getArgOperand(1);
13422     Info.offset = 0;
13423     Info.size = VT.getStoreSize();
13424     Info.align = 1;
13425     Info.vol = false;
13426     Info.readMem = false;
13427     Info.writeMem = true;
13428     return true;
13429   }
13430   default:
13431     break;
13432   }
13433 
13434   return false;
13435 }
13436 
13437 /// getOptimalMemOpType - Returns the target specific optimal type for load
13438 /// and store operations as a result of memset, memcpy, and memmove
13439 /// lowering. If DstAlign is zero that means it's safe to destination
13440 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13441 /// means there isn't a need to check it against alignment requirement,
13442 /// probably because the source does not need to be loaded. If 'IsMemset' is
13443 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13444 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13445 /// source is constant so it does not need to be loaded.
13446 /// It returns EVT::Other if the type should be determined using generic
13447 /// target-independent logic.
13448 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13449                                            unsigned DstAlign, unsigned SrcAlign,
13450                                            bool IsMemset, bool ZeroMemset,
13451                                            bool MemcpyStrSrc,
13452                                            MachineFunction &MF) const {
13453   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13454     const Function *F = MF.getFunction();
13455     // When expanding a memset, require at least two QPX instructions to cover
13456     // the cost of loading the value to be stored from the constant pool.
13457     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13458        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13459         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
13460       return MVT::v4f64;
13461     }
13462 
13463     // We should use Altivec/VSX loads and stores when available. For unaligned
13464     // addresses, unaligned VSX loads are only fast starting with the P8.
13465     if (Subtarget.hasAltivec() && Size >= 16 &&
13466         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13467          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13468       return MVT::v4i32;
13469   }
13470 
13471   if (Subtarget.isPPC64()) {
13472     return MVT::i64;
13473   }
13474 
13475   return MVT::i32;
13476 }
13477 
13478 /// \brief Returns true if it is beneficial to convert a load of a constant
13479 /// to just the constant itself.
13480 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13481                                                           Type *Ty) const {
13482   assert(Ty->isIntegerTy());
13483 
13484   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13485   return !(BitSize == 0 || BitSize > 64);
13486 }
13487 
13488 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13489   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13490     return false;
13491   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13492   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13493   return NumBits1 == 64 && NumBits2 == 32;
13494 }
13495 
13496 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13497   if (!VT1.isInteger() || !VT2.isInteger())
13498     return false;
13499   unsigned NumBits1 = VT1.getSizeInBits();
13500   unsigned NumBits2 = VT2.getSizeInBits();
13501   return NumBits1 == 64 && NumBits2 == 32;
13502 }
13503 
13504 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13505   // Generally speaking, zexts are not free, but they are free when they can be
13506   // folded with other operations.
13507   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13508     EVT MemVT = LD->getMemoryVT();
13509     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13510          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13511         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13512          LD->getExtensionType() == ISD::ZEXTLOAD))
13513       return true;
13514   }
13515 
13516   // FIXME: Add other cases...
13517   //  - 32-bit shifts with a zext to i64
13518   //  - zext after ctlz, bswap, etc.
13519   //  - zext after and by a constant mask
13520 
13521   return TargetLowering::isZExtFree(Val, VT2);
13522 }
13523 
13524 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13525   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13526          "invalid fpext types");
13527   return true;
13528 }
13529 
13530 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13531   return isInt<16>(Imm) || isUInt<16>(Imm);
13532 }
13533 
13534 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13535   return isInt<16>(Imm) || isUInt<16>(Imm);
13536 }
13537 
13538 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13539                                                        unsigned,
13540                                                        unsigned,
13541                                                        bool *Fast) const {
13542   if (DisablePPCUnaligned)
13543     return false;
13544 
13545   // PowerPC supports unaligned memory access for simple non-vector types.
13546   // Although accessing unaligned addresses is not as efficient as accessing
13547   // aligned addresses, it is generally more efficient than manual expansion,
13548   // and generally only traps for software emulation when crossing page
13549   // boundaries.
13550 
13551   if (!VT.isSimple())
13552     return false;
13553 
13554   if (VT.getSimpleVT().isVector()) {
13555     if (Subtarget.hasVSX()) {
13556       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13557           VT != MVT::v4f32 && VT != MVT::v4i32)
13558         return false;
13559     } else {
13560       return false;
13561     }
13562   }
13563 
13564   if (VT == MVT::ppcf128)
13565     return false;
13566 
13567   if (Fast)
13568     *Fast = true;
13569 
13570   return true;
13571 }
13572 
13573 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13574   VT = VT.getScalarType();
13575 
13576   if (!VT.isSimple())
13577     return false;
13578 
13579   switch (VT.getSimpleVT().SimpleTy) {
13580   case MVT::f32:
13581   case MVT::f64:
13582     return true;
13583   default:
13584     break;
13585   }
13586 
13587   return false;
13588 }
13589 
13590 const MCPhysReg *
13591 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13592   // LR is a callee-save register, but we must treat it as clobbered by any call
13593   // site. Hence we include LR in the scratch registers, which are in turn added
13594   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13595   // to CTR, which is used by any indirect call.
13596   static const MCPhysReg ScratchRegs[] = {
13597     PPC::X12, PPC::LR8, PPC::CTR8, 0
13598   };
13599 
13600   return ScratchRegs;
13601 }
13602 
13603 unsigned PPCTargetLowering::getExceptionPointerRegister(
13604     const Constant *PersonalityFn) const {
13605   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
13606 }
13607 
13608 unsigned PPCTargetLowering::getExceptionSelectorRegister(
13609     const Constant *PersonalityFn) const {
13610   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
13611 }
13612 
13613 bool
13614 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
13615                      EVT VT , unsigned DefinedValues) const {
13616   if (VT == MVT::v2i64)
13617     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
13618 
13619   if (Subtarget.hasVSX() || Subtarget.hasQPX())
13620     return true;
13621 
13622   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
13623 }
13624 
13625 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
13626   if (DisableILPPref || Subtarget.enableMachineScheduler())
13627     return TargetLowering::getSchedulingPreference(N);
13628 
13629   return Sched::ILP;
13630 }
13631 
13632 // Create a fast isel object.
13633 FastISel *
13634 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13635                                   const TargetLibraryInfo *LibInfo) const {
13636   return PPC::createFastISel(FuncInfo, LibInfo);
13637 }
13638 
13639 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13640   if (Subtarget.isDarwinABI()) return;
13641   if (!Subtarget.isPPC64()) return;
13642 
13643   // Update IsSplitCSR in PPCFunctionInfo
13644   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13645   PFI->setIsSplitCSR(true);
13646 }
13647 
13648 void PPCTargetLowering::insertCopiesSplitCSR(
13649   MachineBasicBlock *Entry,
13650   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13651   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13652   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13653   if (!IStart)
13654     return;
13655 
13656   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13657   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13658   MachineBasicBlock::iterator MBBI = Entry->begin();
13659   for (const MCPhysReg *I = IStart; *I; ++I) {
13660     const TargetRegisterClass *RC = nullptr;
13661     if (PPC::G8RCRegClass.contains(*I))
13662       RC = &PPC::G8RCRegClass;
13663     else if (PPC::F8RCRegClass.contains(*I))
13664       RC = &PPC::F8RCRegClass;
13665     else if (PPC::CRRCRegClass.contains(*I))
13666       RC = &PPC::CRRCRegClass;
13667     else if (PPC::VRRCRegClass.contains(*I))
13668       RC = &PPC::VRRCRegClass;
13669     else
13670       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13671 
13672     unsigned NewVR = MRI->createVirtualRegister(RC);
13673     // Create copy from CSR to a virtual register.
13674     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13675     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13676     // nounwind. If we want to generalize this later, we may need to emit
13677     // CFI pseudo-instructions.
13678     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13679              Attribute::NoUnwind) &&
13680            "Function should be nounwind in insertCopiesSplitCSR!");
13681     Entry->addLiveIn(*I);
13682     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13683       .addReg(*I);
13684 
13685     // Insert the copy-back instructions right before the terminator
13686     for (auto *Exit : Exits)
13687       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13688               TII->get(TargetOpcode::COPY), *I)
13689         .addReg(NewVR);
13690   }
13691 }
13692 
13693 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13694 bool PPCTargetLowering::useLoadStackGuardNode() const {
13695   if (!Subtarget.isTargetLinux())
13696     return TargetLowering::useLoadStackGuardNode();
13697   return true;
13698 }
13699 
13700 // Override to disable global variable loading on Linux.
13701 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13702   if (!Subtarget.isTargetLinux())
13703     return TargetLowering::insertSSPDeclarations(M);
13704 }
13705 
13706 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13707   if (!VT.isSimple() || !Subtarget.hasVSX())
13708     return false;
13709 
13710   switch(VT.getSimpleVT().SimpleTy) {
13711   default:
13712     // For FP types that are currently not supported by PPC backend, return
13713     // false. Examples: f16, f80.
13714     return false;
13715   case MVT::f32:
13716   case MVT::f64:
13717   case MVT::ppcf128:
13718     return Imm.isPosZero();
13719   }
13720 }
13721 
13722 // For vector shift operation op, fold
13723 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13724 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13725                                   SelectionDAG &DAG) {
13726   SDValue N0 = N->getOperand(0);
13727   SDValue N1 = N->getOperand(1);
13728   EVT VT = N0.getValueType();
13729   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13730   unsigned Opcode = N->getOpcode();
13731   unsigned TargetOpcode;
13732 
13733   switch (Opcode) {
13734   default:
13735     llvm_unreachable("Unexpected shift operation");
13736   case ISD::SHL:
13737     TargetOpcode = PPCISD::SHL;
13738     break;
13739   case ISD::SRL:
13740     TargetOpcode = PPCISD::SRL;
13741     break;
13742   case ISD::SRA:
13743     TargetOpcode = PPCISD::SRA;
13744     break;
13745   }
13746 
13747   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13748       N1->getOpcode() == ISD::AND)
13749     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13750       if (Mask->getZExtValue() == OpSizeInBits - 1)
13751         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13752 
13753   return SDValue();
13754 }
13755 
13756 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13757   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13758     return Value;
13759 
13760   return SDValue();
13761 }
13762 
13763 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13764   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13765     return Value;
13766 
13767   return SDValue();
13768 }
13769 
13770 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13771   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13772     return Value;
13773 
13774   return SDValue();
13775 }
13776