]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Merge ^/head r317216 through r317280.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / PowerPC / PPCISelLowering.cpp
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 "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCallingConv.h"
17 #include "PPCCCState.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCISelLowering.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/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.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/CallingConv.h"
56 #include "llvm/IR/CallSite.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/Instructions.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/IRBuilder.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/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Target/TargetInstrInfo.h"
85 #include "llvm/Target/TargetLowering.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include "llvm/Target/TargetRegisterInfo.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstdint>
92 #include <iterator>
93 #include <list>
94 #include <utility>
95 #include <vector>
96
97 using namespace llvm;
98
99 #define DEBUG_TYPE "ppc-lowering"
100
101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
103
104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
106
107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
109
110 static cl::opt<bool> DisableSCO("disable-ppc-sco",
111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
112
113 STATISTIC(NumTailCalls, "Number of tail calls");
114 STATISTIC(NumSiblingCalls, "Number of sibling calls");
115
116 // FIXME: Remove this once the bug has been fixed!
117 extern cl::opt<bool> ANDIGlueBug;
118
119 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
120                                      const PPCSubtarget &STI)
121     : TargetLowering(TM), Subtarget(STI) {
122   // Use _setjmp/_longjmp instead of setjmp/longjmp.
123   setUseUnderscoreSetJmp(true);
124   setUseUnderscoreLongJmp(true);
125
126   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
127   // arguments are at least 4/8 bytes aligned.
128   bool isPPC64 = Subtarget.isPPC64();
129   setMinStackArgumentAlignment(isPPC64 ? 8:4);
130
131   // Set up the register classes.
132   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
133   if (!useSoftFloat()) {
134     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
135     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
136   }
137
138   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
139   for (MVT VT : MVT::integer_valuetypes()) {
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
142   }
143
144   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
145
146   // PowerPC has pre-inc load and store's.
147   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
148   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
149   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
150   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
151   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
152   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
153   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
154   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
155   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
156   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
157   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
158   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
159   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
160   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
161
162   if (Subtarget.useCRBits()) {
163     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
164
165     if (isPPC64 || Subtarget.hasFPCVT()) {
166       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
167       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
168                          isPPC64 ? MVT::i64 : MVT::i32);
169       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
170       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
171                         isPPC64 ? MVT::i64 : MVT::i32);
172     } else {
173       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
174       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
175     }
176
177     // PowerPC does not support direct load / store of condition registers
178     setOperationAction(ISD::LOAD, MVT::i1, Custom);
179     setOperationAction(ISD::STORE, MVT::i1, Custom);
180
181     // FIXME: Remove this once the ANDI glue bug is fixed:
182     if (ANDIGlueBug)
183       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
184
185     for (MVT VT : MVT::integer_valuetypes()) {
186       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
187       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
188       setTruncStoreAction(VT, MVT::i1, Expand);
189     }
190
191     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
192   }
193
194   // This is used in the ppcf128->int sequence.  Note it has different semantics
195   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
196   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
197
198   // We do not currently implement these libm ops for PowerPC.
199   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
200   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
201   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
202   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
203   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
204   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
205
206   // PowerPC has no SREM/UREM instructions
207   setOperationAction(ISD::SREM, MVT::i32, Expand);
208   setOperationAction(ISD::UREM, MVT::i32, Expand);
209   setOperationAction(ISD::SREM, MVT::i64, Expand);
210   setOperationAction(ISD::UREM, MVT::i64, Expand);
211
212   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
213   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
214   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
215   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
216   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
217   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
218   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
219   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
220   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
221
222   // We don't support sin/cos/sqrt/fmod/pow
223   setOperationAction(ISD::FSIN , MVT::f64, Expand);
224   setOperationAction(ISD::FCOS , MVT::f64, Expand);
225   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
226   setOperationAction(ISD::FREM , MVT::f64, Expand);
227   setOperationAction(ISD::FPOW , MVT::f64, Expand);
228   setOperationAction(ISD::FMA  , MVT::f64, Legal);
229   setOperationAction(ISD::FSIN , MVT::f32, Expand);
230   setOperationAction(ISD::FCOS , MVT::f32, Expand);
231   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
232   setOperationAction(ISD::FREM , MVT::f32, Expand);
233   setOperationAction(ISD::FPOW , MVT::f32, Expand);
234   setOperationAction(ISD::FMA  , MVT::f32, Legal);
235
236   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
237
238   // If we're enabling GP optimizations, use hardware square root
239   if (!Subtarget.hasFSQRT() &&
240       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
241         Subtarget.hasFRE()))
242     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
243
244   if (!Subtarget.hasFSQRT() &&
245       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
246         Subtarget.hasFRES()))
247     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
248
249   if (Subtarget.hasFCPSGN()) {
250     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
251     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
252   } else {
253     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
254     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
255   }
256
257   if (Subtarget.hasFPRND()) {
258     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
259     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
260     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
261     setOperationAction(ISD::FROUND, MVT::f64, Legal);
262
263     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
264     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
265     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
266     setOperationAction(ISD::FROUND, MVT::f32, Legal);
267   }
268
269   // PowerPC does not have BSWAP
270   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
271   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
272   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
273   if (Subtarget.isISA3_0()) {
274     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
275     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
276   } else {
277     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
278     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
279   }
280
281   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
282     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
283     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
284   } else {
285     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
286     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
287   }
288
289   // PowerPC does not have ROTR
290   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
291   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
292
293   if (!Subtarget.useCRBits()) {
294     // PowerPC does not have Select
295     setOperationAction(ISD::SELECT, MVT::i32, Expand);
296     setOperationAction(ISD::SELECT, MVT::i64, Expand);
297     setOperationAction(ISD::SELECT, MVT::f32, Expand);
298     setOperationAction(ISD::SELECT, MVT::f64, Expand);
299   }
300
301   // PowerPC wants to turn select_cc of FP into fsel when possible.
302   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
303   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
304
305   // PowerPC wants to optimize integer setcc a bit
306   if (!Subtarget.useCRBits())
307     setOperationAction(ISD::SETCC, MVT::i32, Custom);
308
309   // PowerPC does not have BRCOND which requires SetCC
310   if (!Subtarget.useCRBits())
311     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
312
313   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
314
315   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
316   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
317
318   // PowerPC does not have [U|S]INT_TO_FP
319   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
320   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
321
322   if (Subtarget.hasDirectMove() && isPPC64) {
323     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
324     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
325     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
326     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
327   } else {
328     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
329     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
330     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
331     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
332   }
333
334   // We cannot sextinreg(i1).  Expand to shifts.
335   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
336
337   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
338   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
339   // support continuation, user-level threading, and etc.. As a result, no
340   // other SjLj exception interfaces are implemented and please don't build
341   // your own exception handling based on them.
342   // LLVM/Clang supports zero-cost DWARF exception handling.
343   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
344   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
345
346   // We want to legalize GlobalAddress and ConstantPool nodes into the
347   // appropriate instructions to materialize the address.
348   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
349   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
350   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
351   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
352   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
353   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
354   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
355   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
356   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
357   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
358
359   // TRAP is legal.
360   setOperationAction(ISD::TRAP, MVT::Other, Legal);
361
362   // TRAMPOLINE is custom lowered.
363   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
364   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
365
366   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
367   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
368
369   if (Subtarget.isSVR4ABI()) {
370     if (isPPC64) {
371       // VAARG always uses double-word chunks, so promote anything smaller.
372       setOperationAction(ISD::VAARG, MVT::i1, Promote);
373       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
374       setOperationAction(ISD::VAARG, MVT::i8, Promote);
375       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
376       setOperationAction(ISD::VAARG, MVT::i16, Promote);
377       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
378       setOperationAction(ISD::VAARG, MVT::i32, Promote);
379       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
380       setOperationAction(ISD::VAARG, MVT::Other, Expand);
381     } else {
382       // VAARG is custom lowered with the 32-bit SVR4 ABI.
383       setOperationAction(ISD::VAARG, MVT::Other, Custom);
384       setOperationAction(ISD::VAARG, MVT::i64, Custom);
385     }
386   } else
387     setOperationAction(ISD::VAARG, MVT::Other, Expand);
388
389   if (Subtarget.isSVR4ABI() && !isPPC64)
390     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
391     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
392   else
393     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
394
395   // Use the default implementation.
396   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
397   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
398   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
399   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
400   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
401   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
402   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
403   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
404   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
405
406   // We want to custom lower some of our intrinsics.
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408
409   // To handle counter-based loop conditions.
410   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
411
412   // Comparisons that require checking two conditions.
413   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
414   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
415   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
416   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
417   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
418   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
419   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
420   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
421   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
422   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
423   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
424   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
425
426   if (Subtarget.has64BitSupport()) {
427     // They also have instructions for converting between i64 and fp.
428     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
429     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
430     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
431     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
432     // This is just the low 32 bits of a (signed) fp->i64 conversion.
433     // We cannot do this with Promote because i64 is not a legal type.
434     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
435
436     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
437       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
438   } else {
439     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
440     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
441   }
442
443   // With the instructions enabled under FPCVT, we can do everything.
444   if (Subtarget.hasFPCVT()) {
445     if (Subtarget.has64BitSupport()) {
446       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
447       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
448       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
449       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
450     }
451
452     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
453     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
454     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
455     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
456   }
457
458   if (Subtarget.use64BitRegs()) {
459     // 64-bit PowerPC implementations can support i64 types directly
460     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
461     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
462     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
463     // 64-bit PowerPC wants to expand i128 shifts itself.
464     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
465     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
466     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
467   } else {
468     // 32-bit PowerPC wants to expand i64 shifts itself.
469     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
470     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
471     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
472   }
473
474   if (Subtarget.hasAltivec()) {
475     // First set operation action for all vector types to expand. Then we
476     // will selectively turn on ones that can be effectively codegen'd.
477     for (MVT VT : MVT::vector_valuetypes()) {
478       // add/sub are legal for all supported vector VT's.
479       setOperationAction(ISD::ADD, VT, Legal);
480       setOperationAction(ISD::SUB, VT, Legal);
481
482       // Vector instructions introduced in P8
483       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
484         setOperationAction(ISD::CTPOP, VT, Legal);
485         setOperationAction(ISD::CTLZ, VT, Legal);
486       }
487       else {
488         setOperationAction(ISD::CTPOP, VT, Expand);
489         setOperationAction(ISD::CTLZ, VT, Expand);
490       }
491
492       // Vector instructions introduced in P9
493       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
494         setOperationAction(ISD::CTTZ, VT, Legal);
495       else
496         setOperationAction(ISD::CTTZ, VT, Expand);
497
498       // We promote all shuffles to v16i8.
499       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
500       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
501
502       // We promote all non-typed operations to v4i32.
503       setOperationAction(ISD::AND   , VT, Promote);
504       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
505       setOperationAction(ISD::OR    , VT, Promote);
506       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
507       setOperationAction(ISD::XOR   , VT, Promote);
508       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
509       setOperationAction(ISD::LOAD  , VT, Promote);
510       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
511       setOperationAction(ISD::SELECT, VT, Promote);
512       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
513       setOperationAction(ISD::SELECT_CC, VT, Promote);
514       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
515       setOperationAction(ISD::STORE, VT, Promote);
516       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
517
518       // No other operations are legal.
519       setOperationAction(ISD::MUL , VT, Expand);
520       setOperationAction(ISD::SDIV, VT, Expand);
521       setOperationAction(ISD::SREM, VT, Expand);
522       setOperationAction(ISD::UDIV, VT, Expand);
523       setOperationAction(ISD::UREM, VT, Expand);
524       setOperationAction(ISD::FDIV, VT, Expand);
525       setOperationAction(ISD::FREM, VT, Expand);
526       setOperationAction(ISD::FNEG, VT, Expand);
527       setOperationAction(ISD::FSQRT, VT, Expand);
528       setOperationAction(ISD::FLOG, VT, Expand);
529       setOperationAction(ISD::FLOG10, VT, Expand);
530       setOperationAction(ISD::FLOG2, VT, Expand);
531       setOperationAction(ISD::FEXP, VT, Expand);
532       setOperationAction(ISD::FEXP2, VT, Expand);
533       setOperationAction(ISD::FSIN, VT, Expand);
534       setOperationAction(ISD::FCOS, VT, Expand);
535       setOperationAction(ISD::FABS, VT, Expand);
536       setOperationAction(ISD::FPOWI, VT, Expand);
537       setOperationAction(ISD::FFLOOR, VT, Expand);
538       setOperationAction(ISD::FCEIL,  VT, Expand);
539       setOperationAction(ISD::FTRUNC, VT, Expand);
540       setOperationAction(ISD::FRINT,  VT, Expand);
541       setOperationAction(ISD::FNEARBYINT, VT, Expand);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
543       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
544       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
545       setOperationAction(ISD::MULHU, VT, Expand);
546       setOperationAction(ISD::MULHS, VT, Expand);
547       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
548       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
549       setOperationAction(ISD::UDIVREM, VT, Expand);
550       setOperationAction(ISD::SDIVREM, VT, Expand);
551       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
552       setOperationAction(ISD::FPOW, VT, Expand);
553       setOperationAction(ISD::BSWAP, VT, Expand);
554       setOperationAction(ISD::VSELECT, VT, Expand);
555       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
556       setOperationAction(ISD::ROTL, VT, Expand);
557       setOperationAction(ISD::ROTR, VT, Expand);
558
559       for (MVT InnerVT : MVT::vector_valuetypes()) {
560         setTruncStoreAction(VT, InnerVT, Expand);
561         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
562         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
563         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
564       }
565     }
566
567     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
568     // with merges, splats, etc.
569     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
570
571     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
572     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
573     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
574     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
575     setOperationAction(ISD::SELECT, MVT::v4i32,
576                        Subtarget.useCRBits() ? Legal : Expand);
577     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
578     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
579     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
580     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
581     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
582     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
583     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
584     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
585     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
586
587     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
588     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
589     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
590     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
591
592     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
593     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
594
595     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
596       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
597       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
598     }
599
600     if (Subtarget.hasP8Altivec())
601       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
602     else
603       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
604
605     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
606     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
607
608     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
609     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
610
611     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
612     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
613     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
614     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
615
616     // Altivec does not contain unordered floating-point compare instructions
617     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
618     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
619     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
620     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
621
622     if (Subtarget.hasVSX()) {
623       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
624       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
625       if (Subtarget.hasP8Vector()) {
626         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
627         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
628       }
629       if (Subtarget.hasDirectMove() && isPPC64) {
630         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
631         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
632         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
633         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
634         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
635         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
636         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
637         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
638       }
639       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
640
641       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
642       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
643       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
644       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
645       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
646
647       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
648
649       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
650       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
651
652       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
653       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
654
655       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
656       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
657       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
658       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
659       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
660
661       // Share the Altivec comparison restrictions.
662       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
663       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
664       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
665       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
666
667       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
668       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
669
670       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
671
672       if (Subtarget.hasP8Vector())
673         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
674
675       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
676
677       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
678       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
679       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
680
681       if (Subtarget.hasP8Altivec()) {
682         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
683         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
684         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
685
686         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
687       }
688       else {
689         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
690         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
691         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
692
693         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
694
695         // VSX v2i64 only supports non-arithmetic operations.
696         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
697         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
698       }
699
700       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
701       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
702       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
703       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
704
705       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
706
707       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
708       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
709       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
710       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
711
712       // Vector operation legalization checks the result type of
713       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
714       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
715       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
716       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
717       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
718
719       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
720       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
721       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
722       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
723
724       if (Subtarget.hasDirectMove())
725         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
726       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
727
728       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
729     }
730
731     if (Subtarget.hasP8Altivec()) {
732       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
733       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
734     }
735
736     if (Subtarget.hasP9Vector()) {
737       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
738       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
739     }
740   }
741
742   if (Subtarget.hasQPX()) {
743     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
744     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
745     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
746     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
747
748     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
749     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
750
751     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
752     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
753
754     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
755     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
756
757     if (!Subtarget.useCRBits())
758       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
759     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
760
761     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
762     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
763     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
764     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
765     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
766     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
767     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
768
769     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
770     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
771
772     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
773     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
774     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
775
776     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
777     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
778     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
779     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
780     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
781     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
782     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
783     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
784     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
785     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
786     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
787
788     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
789     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
790
791     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
792     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
793
794     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
795
796     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
800
801     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
802     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
803
804     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
805     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
806
807     if (!Subtarget.useCRBits())
808       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
809     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
810
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
812     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
813     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
814     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
815     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
816     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
817     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
818
819     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
820     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
821
822     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
823     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
824     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
825     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
826     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
827     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
828     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
829     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
830     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
831     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
832     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
833
834     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
835     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
836
837     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
838     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
839
840     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
841
842     setOperationAction(ISD::AND , MVT::v4i1, Legal);
843     setOperationAction(ISD::OR , MVT::v4i1, Legal);
844     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
845
846     if (!Subtarget.useCRBits())
847       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
848     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
849
850     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
851     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
852
853     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
854     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
855     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
856     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
857     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
858     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
859     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
860
861     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
862     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
863
864     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
865
866     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
867     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
868     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
869     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
870
871     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
872     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
873     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
874     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
875
876     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
877     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
878
879     // These need to set FE_INEXACT, and so cannot be vectorized here.
880     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
881     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
882
883     if (TM.Options.UnsafeFPMath) {
884       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
885       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
886
887       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
888       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
889     } else {
890       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
891       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
892
893       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
894       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
895     }
896   }
897
898   if (Subtarget.has64BitSupport())
899     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
900
901   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
902
903   if (!isPPC64) {
904     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
905     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
906   }
907
908   setBooleanContents(ZeroOrOneBooleanContent);
909
910   if (Subtarget.hasAltivec()) {
911     // Altivec instructions set fields to all zeros or all ones.
912     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
913   }
914
915   if (!isPPC64) {
916     // These libcalls are not available in 32-bit.
917     setLibcallName(RTLIB::SHL_I128, nullptr);
918     setLibcallName(RTLIB::SRL_I128, nullptr);
919     setLibcallName(RTLIB::SRA_I128, nullptr);
920   }
921
922   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
923
924   // We have target-specific dag combine patterns for the following nodes:
925   setTargetDAGCombine(ISD::SINT_TO_FP);
926   setTargetDAGCombine(ISD::BUILD_VECTOR);
927   if (Subtarget.hasFPCVT())
928     setTargetDAGCombine(ISD::UINT_TO_FP);
929   setTargetDAGCombine(ISD::LOAD);
930   setTargetDAGCombine(ISD::STORE);
931   setTargetDAGCombine(ISD::BR_CC);
932   if (Subtarget.useCRBits())
933     setTargetDAGCombine(ISD::BRCOND);
934   setTargetDAGCombine(ISD::BSWAP);
935   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
936   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
937   setTargetDAGCombine(ISD::INTRINSIC_VOID);
938
939   setTargetDAGCombine(ISD::SIGN_EXTEND);
940   setTargetDAGCombine(ISD::ZERO_EXTEND);
941   setTargetDAGCombine(ISD::ANY_EXTEND);
942
943   if (Subtarget.useCRBits()) {
944     setTargetDAGCombine(ISD::TRUNCATE);
945     setTargetDAGCombine(ISD::SETCC);
946     setTargetDAGCombine(ISD::SELECT_CC);
947   }
948
949   // Use reciprocal estimates.
950   if (TM.Options.UnsafeFPMath) {
951     setTargetDAGCombine(ISD::FDIV);
952     setTargetDAGCombine(ISD::FSQRT);
953   }
954
955   // Darwin long double math library functions have $LDBL128 appended.
956   if (Subtarget.isDarwin()) {
957     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
958     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
959     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
960     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
961     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
962     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
963     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
964     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
965     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
966     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
967   }
968
969   // With 32 condition bits, we don't need to sink (and duplicate) compares
970   // aggressively in CodeGenPrep.
971   if (Subtarget.useCRBits()) {
972     setHasMultipleConditionRegisters();
973     setJumpIsExpensive();
974   }
975
976   setMinFunctionAlignment(2);
977   if (Subtarget.isDarwin())
978     setPrefFunctionAlignment(4);
979
980   switch (Subtarget.getDarwinDirective()) {
981   default: break;
982   case PPC::DIR_970:
983   case PPC::DIR_A2:
984   case PPC::DIR_E500mc:
985   case PPC::DIR_E5500:
986   case PPC::DIR_PWR4:
987   case PPC::DIR_PWR5:
988   case PPC::DIR_PWR5X:
989   case PPC::DIR_PWR6:
990   case PPC::DIR_PWR6X:
991   case PPC::DIR_PWR7:
992   case PPC::DIR_PWR8:
993   case PPC::DIR_PWR9:
994     setPrefFunctionAlignment(4);
995     setPrefLoopAlignment(4);
996     break;
997   }
998
999   if (Subtarget.enableMachineScheduler())
1000     setSchedulingPreference(Sched::Source);
1001   else
1002     setSchedulingPreference(Sched::Hybrid);
1003
1004   computeRegisterProperties(STI.getRegisterInfo());
1005
1006   // The Freescale cores do better with aggressive inlining of memcpy and
1007   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1008   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1009       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1010     MaxStoresPerMemset = 32;
1011     MaxStoresPerMemsetOptSize = 16;
1012     MaxStoresPerMemcpy = 32;
1013     MaxStoresPerMemcpyOptSize = 8;
1014     MaxStoresPerMemmove = 32;
1015     MaxStoresPerMemmoveOptSize = 8;
1016   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1017     // The A2 also benefits from (very) aggressive inlining of memcpy and
1018     // friends. The overhead of a the function call, even when warm, can be
1019     // over one hundred cycles.
1020     MaxStoresPerMemset = 128;
1021     MaxStoresPerMemcpy = 128;
1022     MaxStoresPerMemmove = 128;
1023   }
1024 }
1025
1026 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1027 /// the desired ByVal argument alignment.
1028 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1029                              unsigned MaxMaxAlign) {
1030   if (MaxAlign == MaxMaxAlign)
1031     return;
1032   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1033     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1034       MaxAlign = 32;
1035     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1036       MaxAlign = 16;
1037   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1038     unsigned EltAlign = 0;
1039     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1040     if (EltAlign > MaxAlign)
1041       MaxAlign = EltAlign;
1042   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1043     for (auto *EltTy : STy->elements()) {
1044       unsigned EltAlign = 0;
1045       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1046       if (EltAlign > MaxAlign)
1047         MaxAlign = EltAlign;
1048       if (MaxAlign == MaxMaxAlign)
1049         break;
1050     }
1051   }
1052 }
1053
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area.
1056 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1057                                                   const DataLayout &DL) const {
1058   // Darwin passes everything on 4 byte boundary.
1059   if (Subtarget.isDarwin())
1060     return 4;
1061
1062   // 16byte and wider vectors are passed on 16byte boundary.
1063   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1064   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1065   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1066     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1067   return Align;
1068 }
1069
1070 bool PPCTargetLowering::useSoftFloat() const {
1071   return Subtarget.useSoftFloat();
1072 }
1073
1074 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1075   switch ((PPCISD::NodeType)Opcode) {
1076   case PPCISD::FIRST_NUMBER:    break;
1077   case PPCISD::FSEL:            return "PPCISD::FSEL";
1078   case PPCISD::FCFID:           return "PPCISD::FCFID";
1079   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1080   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1081   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1082   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1083   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1084   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1085   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1086   case PPCISD::FRE:             return "PPCISD::FRE";
1087   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1088   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1089   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1090   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1091   case PPCISD::VPERM:           return "PPCISD::VPERM";
1092   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1093   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1094   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1095   case PPCISD::CMPB:            return "PPCISD::CMPB";
1096   case PPCISD::Hi:              return "PPCISD::Hi";
1097   case PPCISD::Lo:              return "PPCISD::Lo";
1098   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1099   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1100   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1101   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1102   case PPCISD::SRL:             return "PPCISD::SRL";
1103   case PPCISD::SRA:             return "PPCISD::SRA";
1104   case PPCISD::SHL:             return "PPCISD::SHL";
1105   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1106   case PPCISD::CALL:            return "PPCISD::CALL";
1107   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1108   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1109   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1110   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1111   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1112   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1113   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1114   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1115   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1116   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1117   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1118   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1119   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1120   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1121   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1122   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1123   case PPCISD::VCMP:            return "PPCISD::VCMP";
1124   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1125   case PPCISD::LBRX:            return "PPCISD::LBRX";
1126   case PPCISD::STBRX:           return "PPCISD::STBRX";
1127   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1128   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1129   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1130   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1131   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1132   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1133   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1134   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1135   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1136   case PPCISD::BDZ:             return "PPCISD::BDZ";
1137   case PPCISD::MFFS:            return "PPCISD::MFFS";
1138   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1139   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1140   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1141   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1142   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1143   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1144   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1145   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1146   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1147   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1148   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1149   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1150   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1151   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1152   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1153   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1154   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1155   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1156   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1157   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1158   case PPCISD::SC:              return "PPCISD::SC";
1159   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1160   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1161   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1162   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1163   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1164   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1165   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1166   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1167   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1168   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1169   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1170   }
1171   return nullptr;
1172 }
1173
1174 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1175                                           EVT VT) const {
1176   if (!VT.isVector())
1177     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1178
1179   if (Subtarget.hasQPX())
1180     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1181
1182   return VT.changeVectorElementTypeToInteger();
1183 }
1184
1185 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1186   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1187   return true;
1188 }
1189
1190 //===----------------------------------------------------------------------===//
1191 // Node matching predicates, for use by the tblgen matching code.
1192 //===----------------------------------------------------------------------===//
1193
1194 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1195 static bool isFloatingPointZero(SDValue Op) {
1196   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1197     return CFP->getValueAPF().isZero();
1198   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1199     // Maybe this has already been legalized into the constant pool?
1200     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1201       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1202         return CFP->getValueAPF().isZero();
1203   }
1204   return false;
1205 }
1206
1207 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1208 /// true if Op is undef or if it matches the specified value.
1209 static bool isConstantOrUndef(int Op, int Val) {
1210   return Op < 0 || Op == Val;
1211 }
1212
1213 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1214 /// VPKUHUM instruction.
1215 /// The ShuffleKind distinguishes between big-endian operations with
1216 /// two different inputs (0), either-endian operations with two identical
1217 /// inputs (1), and little-endian operations with two different inputs (2).
1218 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1220                                SelectionDAG &DAG) {
1221   bool IsLE = DAG.getDataLayout().isLittleEndian();
1222   if (ShuffleKind == 0) {
1223     if (IsLE)
1224       return false;
1225     for (unsigned i = 0; i != 16; ++i)
1226       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1227         return false;
1228   } else if (ShuffleKind == 2) {
1229     if (!IsLE)
1230       return false;
1231     for (unsigned i = 0; i != 16; ++i)
1232       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1233         return false;
1234   } else if (ShuffleKind == 1) {
1235     unsigned j = IsLE ? 0 : 1;
1236     for (unsigned i = 0; i != 8; ++i)
1237       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1238           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1239         return false;
1240   }
1241   return true;
1242 }
1243
1244 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1245 /// VPKUWUM instruction.
1246 /// The ShuffleKind distinguishes between big-endian operations with
1247 /// two different inputs (0), either-endian operations with two identical
1248 /// inputs (1), and little-endian operations with two different inputs (2).
1249 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1250 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1251                                SelectionDAG &DAG) {
1252   bool IsLE = DAG.getDataLayout().isLittleEndian();
1253   if (ShuffleKind == 0) {
1254     if (IsLE)
1255       return false;
1256     for (unsigned i = 0; i != 16; i += 2)
1257       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1258           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1259         return false;
1260   } else if (ShuffleKind == 2) {
1261     if (!IsLE)
1262       return false;
1263     for (unsigned i = 0; i != 16; i += 2)
1264       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1265           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1266         return false;
1267   } else if (ShuffleKind == 1) {
1268     unsigned j = IsLE ? 0 : 2;
1269     for (unsigned i = 0; i != 8; i += 2)
1270       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1271           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1272           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1273           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1274         return false;
1275   }
1276   return true;
1277 }
1278
1279 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1280 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1281 /// current subtarget.
1282 ///
1283 /// The ShuffleKind distinguishes between big-endian operations with
1284 /// two different inputs (0), either-endian operations with two identical
1285 /// inputs (1), and little-endian operations with two different inputs (2).
1286 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1287 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1288                                SelectionDAG &DAG) {
1289   const PPCSubtarget& Subtarget =
1290     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1291   if (!Subtarget.hasP8Vector())
1292     return false;
1293
1294   bool IsLE = DAG.getDataLayout().isLittleEndian();
1295   if (ShuffleKind == 0) {
1296     if (IsLE)
1297       return false;
1298     for (unsigned i = 0; i != 16; i += 4)
1299       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1300           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1301           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1302           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1303         return false;
1304   } else if (ShuffleKind == 2) {
1305     if (!IsLE)
1306       return false;
1307     for (unsigned i = 0; i != 16; i += 4)
1308       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1309           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1310           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1311           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1312         return false;
1313   } else if (ShuffleKind == 1) {
1314     unsigned j = IsLE ? 0 : 4;
1315     for (unsigned i = 0; i != 8; i += 4)
1316       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1317           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1318           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1319           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1320           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1321           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1322           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1323           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1324         return false;
1325   }
1326   return true;
1327 }
1328
1329 /// isVMerge - Common function, used to match vmrg* shuffles.
1330 ///
1331 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1332                      unsigned LHSStart, unsigned RHSStart) {
1333   if (N->getValueType(0) != MVT::v16i8)
1334     return false;
1335   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1336          "Unsupported merge size!");
1337
1338   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1339     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1340       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1341                              LHSStart+j+i*UnitSize) ||
1342           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1343                              RHSStart+j+i*UnitSize))
1344         return false;
1345     }
1346   return true;
1347 }
1348
1349 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1350 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1351 /// The ShuffleKind distinguishes between big-endian merges with two
1352 /// different inputs (0), either-endian merges with two identical inputs (1),
1353 /// and little-endian merges with two different inputs (2).  For the latter,
1354 /// the input operands are swapped (see PPCInstrAltivec.td).
1355 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1356                              unsigned ShuffleKind, SelectionDAG &DAG) {
1357   if (DAG.getDataLayout().isLittleEndian()) {
1358     if (ShuffleKind == 1) // unary
1359       return isVMerge(N, UnitSize, 0, 0);
1360     else if (ShuffleKind == 2) // swapped
1361       return isVMerge(N, UnitSize, 0, 16);
1362     else
1363       return false;
1364   } else {
1365     if (ShuffleKind == 1) // unary
1366       return isVMerge(N, UnitSize, 8, 8);
1367     else if (ShuffleKind == 0) // normal
1368       return isVMerge(N, UnitSize, 8, 24);
1369     else
1370       return false;
1371   }
1372 }
1373
1374 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1375 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1376 /// The ShuffleKind distinguishes between big-endian merges with two
1377 /// different inputs (0), either-endian merges with two identical inputs (1),
1378 /// and little-endian merges with two different inputs (2).  For the latter,
1379 /// the input operands are swapped (see PPCInstrAltivec.td).
1380 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1381                              unsigned ShuffleKind, SelectionDAG &DAG) {
1382   if (DAG.getDataLayout().isLittleEndian()) {
1383     if (ShuffleKind == 1) // unary
1384       return isVMerge(N, UnitSize, 8, 8);
1385     else if (ShuffleKind == 2) // swapped
1386       return isVMerge(N, UnitSize, 8, 24);
1387     else
1388       return false;
1389   } else {
1390     if (ShuffleKind == 1) // unary
1391       return isVMerge(N, UnitSize, 0, 0);
1392     else if (ShuffleKind == 0) // normal
1393       return isVMerge(N, UnitSize, 0, 16);
1394     else
1395       return false;
1396   }
1397 }
1398
1399 /**
1400  * \brief Common function used to match vmrgew and vmrgow shuffles
1401  *
1402  * The indexOffset determines whether to look for even or odd words in
1403  * the shuffle mask. This is based on the of the endianness of the target
1404  * machine.
1405  *   - Little Endian:
1406  *     - Use offset of 0 to check for odd elements
1407  *     - Use offset of 4 to check for even elements
1408  *   - Big Endian:
1409  *     - Use offset of 0 to check for even elements
1410  *     - Use offset of 4 to check for odd elements
1411  * A detailed description of the vector element ordering for little endian and
1412  * big endian can be found at
1413  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1414  * Targeting your applications - what little endian and big endian IBM XL C/C++
1415  * compiler differences mean to you
1416  *
1417  * The mask to the shuffle vector instruction specifies the indices of the
1418  * elements from the two input vectors to place in the result. The elements are
1419  * numbered in array-access order, starting with the first vector. These vectors
1420  * are always of type v16i8, thus each vector will contain 16 elements of size
1421  * 8. More info on the shuffle vector can be found in the
1422  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1423  * Language Reference.
1424  *
1425  * The RHSStartValue indicates whether the same input vectors are used (unary)
1426  * or two different input vectors are used, based on the following:
1427  *   - If the instruction uses the same vector for both inputs, the range of the
1428  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1429  *     be 0.
1430  *   - If the instruction has two different vectors then the range of the
1431  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1432  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1433  *     to 31 specify elements in the second vector).
1434  *
1435  * \param[in] N The shuffle vector SD Node to analyze
1436  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1437  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1438  * vector to the shuffle_vector instruction
1439  * \return true iff this shuffle vector represents an even or odd word merge
1440  */
1441 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1442                      unsigned RHSStartValue) {
1443   if (N->getValueType(0) != MVT::v16i8)
1444     return false;
1445
1446   for (unsigned i = 0; i < 2; ++i)
1447     for (unsigned j = 0; j < 4; ++j)
1448       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1449                              i*RHSStartValue+j+IndexOffset) ||
1450           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1451                              i*RHSStartValue+j+IndexOffset+8))
1452         return false;
1453   return true;
1454 }
1455
1456 /**
1457  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1458  * vmrgow instructions.
1459  *
1460  * \param[in] N The shuffle vector SD Node to analyze
1461  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1462  * \param[in] ShuffleKind Identify the type of merge:
1463  *   - 0 = big-endian merge with two different inputs;
1464  *   - 1 = either-endian merge with two identical inputs;
1465  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1466  *     little-endian merges).
1467  * \param[in] DAG The current SelectionDAG
1468  * \return true iff this shuffle mask
1469  */
1470 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1471                               unsigned ShuffleKind, SelectionDAG &DAG) {
1472   if (DAG.getDataLayout().isLittleEndian()) {
1473     unsigned indexOffset = CheckEven ? 4 : 0;
1474     if (ShuffleKind == 1) // Unary
1475       return isVMerge(N, indexOffset, 0);
1476     else if (ShuffleKind == 2) // swapped
1477       return isVMerge(N, indexOffset, 16);
1478     else
1479       return false;
1480   }
1481   else {
1482     unsigned indexOffset = CheckEven ? 0 : 4;
1483     if (ShuffleKind == 1) // Unary
1484       return isVMerge(N, indexOffset, 0);
1485     else if (ShuffleKind == 0) // Normal
1486       return isVMerge(N, indexOffset, 16);
1487     else
1488       return false;
1489   }
1490   return false;
1491 }
1492
1493 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1494 /// amount, otherwise return -1.
1495 /// The ShuffleKind distinguishes between big-endian operations with two
1496 /// different inputs (0), either-endian operations with two identical inputs
1497 /// (1), and little-endian operations with two different inputs (2).  For the
1498 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1499 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1500                              SelectionDAG &DAG) {
1501   if (N->getValueType(0) != MVT::v16i8)
1502     return -1;
1503
1504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1505
1506   // Find the first non-undef value in the shuffle mask.
1507   unsigned i;
1508   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1509     /*search*/;
1510
1511   if (i == 16) return -1;  // all undef.
1512
1513   // Otherwise, check to see if the rest of the elements are consecutively
1514   // numbered from this value.
1515   unsigned ShiftAmt = SVOp->getMaskElt(i);
1516   if (ShiftAmt < i) return -1;
1517
1518   ShiftAmt -= i;
1519   bool isLE = DAG.getDataLayout().isLittleEndian();
1520
1521   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1522     // Check the rest of the elements to see if they are consecutive.
1523     for (++i; i != 16; ++i)
1524       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1525         return -1;
1526   } else if (ShuffleKind == 1) {
1527     // Check the rest of the elements to see if they are consecutive.
1528     for (++i; i != 16; ++i)
1529       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1530         return -1;
1531   } else
1532     return -1;
1533
1534   if (isLE)
1535     ShiftAmt = 16 - ShiftAmt;
1536
1537   return ShiftAmt;
1538 }
1539
1540 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1541 /// specifies a splat of a single element that is suitable for input to
1542 /// VSPLTB/VSPLTH/VSPLTW.
1543 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1544   assert(N->getValueType(0) == MVT::v16i8 &&
1545          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1546
1547   // The consecutive indices need to specify an element, not part of two
1548   // different elements.  So abandon ship early if this isn't the case.
1549   if (N->getMaskElt(0) % EltSize != 0)
1550     return false;
1551
1552   // This is a splat operation if each element of the permute is the same, and
1553   // if the value doesn't reference the second vector.
1554   unsigned ElementBase = N->getMaskElt(0);
1555
1556   // FIXME: Handle UNDEF elements too!
1557   if (ElementBase >= 16)
1558     return false;
1559
1560   // Check that the indices are consecutive, in the case of a multi-byte element
1561   // splatted with a v16i8 mask.
1562   for (unsigned i = 1; i != EltSize; ++i)
1563     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1564       return false;
1565
1566   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1567     if (N->getMaskElt(i) < 0) continue;
1568     for (unsigned j = 0; j != EltSize; ++j)
1569       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1570         return false;
1571   }
1572   return true;
1573 }
1574
1575 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1576                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1577   // Check that the mask is shuffling words
1578   for (unsigned i = 0; i < 4; ++i) {
1579     unsigned B0 = N->getMaskElt(i*4);
1580     unsigned B1 = N->getMaskElt(i*4+1);
1581     unsigned B2 = N->getMaskElt(i*4+2);
1582     unsigned B3 = N->getMaskElt(i*4+3);
1583     if (B0 % 4)
1584       return false;
1585     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1586       return false;
1587   }
1588
1589   // Now we look at mask elements 0,4,8,12
1590   unsigned M0 = N->getMaskElt(0) / 4;
1591   unsigned M1 = N->getMaskElt(4) / 4;
1592   unsigned M2 = N->getMaskElt(8) / 4;
1593   unsigned M3 = N->getMaskElt(12) / 4;
1594   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1595   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1596
1597   // Below, let H and L be arbitrary elements of the shuffle mask
1598   // where H is in the range [4,7] and L is in the range [0,3].
1599   // H, 1, 2, 3 or L, 5, 6, 7
1600   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1601       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1602     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1603     InsertAtByte = IsLE ? 12 : 0;
1604     Swap = M0 < 4;
1605     return true;
1606   }
1607   // 0, H, 2, 3 or 4, L, 6, 7
1608   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1609       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1610     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1611     InsertAtByte = IsLE ? 8 : 4;
1612     Swap = M1 < 4;
1613     return true;
1614   }
1615   // 0, 1, H, 3 or 4, 5, L, 7
1616   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1617       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1618     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1619     InsertAtByte = IsLE ? 4 : 8;
1620     Swap = M2 < 4;
1621     return true;
1622   }
1623   // 0, 1, 2, H or 4, 5, 6, L
1624   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1625       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1626     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1627     InsertAtByte = IsLE ? 0 : 12;
1628     Swap = M3 < 4;
1629     return true;
1630   }
1631
1632   // If both vector operands for the shuffle are the same vector, the mask will
1633   // contain only elements from the first one and the second one will be undef.
1634   if (N->getOperand(1).isUndef()) {
1635     ShiftElts = 0;
1636     Swap = true;
1637     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1638     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1639       InsertAtByte = IsLE ? 12 : 0;
1640       return true;
1641     }
1642     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1643       InsertAtByte = IsLE ? 8 : 4;
1644       return true;
1645     }
1646     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1647       InsertAtByte = IsLE ? 4 : 8;
1648       return true;
1649     }
1650     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1651       InsertAtByte = IsLE ? 0 : 12;
1652       return true;
1653     }
1654   }
1655
1656   return false;
1657 }
1658
1659 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1660 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1661 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1662                                 SelectionDAG &DAG) {
1663   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1664   assert(isSplatShuffleMask(SVOp, EltSize));
1665   if (DAG.getDataLayout().isLittleEndian())
1666     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1667   else
1668     return SVOp->getMaskElt(0) / EltSize;
1669 }
1670
1671 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1672 /// by using a vspltis[bhw] instruction of the specified element size, return
1673 /// the constant being splatted.  The ByteSize field indicates the number of
1674 /// bytes of each element [124] -> [bhw].
1675 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1676   SDValue OpVal(nullptr, 0);
1677
1678   // If ByteSize of the splat is bigger than the element size of the
1679   // build_vector, then we have a case where we are checking for a splat where
1680   // multiple elements of the buildvector are folded together into a single
1681   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1682   unsigned EltSize = 16/N->getNumOperands();
1683   if (EltSize < ByteSize) {
1684     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1685     SDValue UniquedVals[4];
1686     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1687
1688     // See if all of the elements in the buildvector agree across.
1689     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1690       if (N->getOperand(i).isUndef()) continue;
1691       // If the element isn't a constant, bail fully out.
1692       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1693
1694       if (!UniquedVals[i&(Multiple-1)].getNode())
1695         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1696       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1697         return SDValue();  // no match.
1698     }
1699
1700     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1701     // either constant or undef values that are identical for each chunk.  See
1702     // if these chunks can form into a larger vspltis*.
1703
1704     // Check to see if all of the leading entries are either 0 or -1.  If
1705     // neither, then this won't fit into the immediate field.
1706     bool LeadingZero = true;
1707     bool LeadingOnes = true;
1708     for (unsigned i = 0; i != Multiple-1; ++i) {
1709       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1710
1711       LeadingZero &= isNullConstant(UniquedVals[i]);
1712       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1713     }
1714     // Finally, check the least significant entry.
1715     if (LeadingZero) {
1716       if (!UniquedVals[Multiple-1].getNode())
1717         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1718       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1719       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1720         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1721     }
1722     if (LeadingOnes) {
1723       if (!UniquedVals[Multiple-1].getNode())
1724         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1725       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1726       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1727         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1728     }
1729
1730     return SDValue();
1731   }
1732
1733   // Check to see if this buildvec has a single non-undef value in its elements.
1734   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1735     if (N->getOperand(i).isUndef()) continue;
1736     if (!OpVal.getNode())
1737       OpVal = N->getOperand(i);
1738     else if (OpVal != N->getOperand(i))
1739       return SDValue();
1740   }
1741
1742   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1743
1744   unsigned ValSizeInBytes = EltSize;
1745   uint64_t Value = 0;
1746   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1747     Value = CN->getZExtValue();
1748   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1749     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1750     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1751   }
1752
1753   // If the splat value is larger than the element value, then we can never do
1754   // this splat.  The only case that we could fit the replicated bits into our
1755   // immediate field for would be zero, and we prefer to use vxor for it.
1756   if (ValSizeInBytes < ByteSize) return SDValue();
1757
1758   // If the element value is larger than the splat value, check if it consists
1759   // of a repeated bit pattern of size ByteSize.
1760   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1761     return SDValue();
1762
1763   // Properly sign extend the value.
1764   int MaskVal = SignExtend32(Value, ByteSize * 8);
1765
1766   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1767   if (MaskVal == 0) return SDValue();
1768
1769   // Finally, if this value fits in a 5 bit sext field, return it
1770   if (SignExtend32<5>(MaskVal) == MaskVal)
1771     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1772   return SDValue();
1773 }
1774
1775 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1776 /// amount, otherwise return -1.
1777 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1778   EVT VT = N->getValueType(0);
1779   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1780     return -1;
1781
1782   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1783
1784   // Find the first non-undef value in the shuffle mask.
1785   unsigned i;
1786   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1787     /*search*/;
1788
1789   if (i == 4) return -1;  // all undef.
1790
1791   // Otherwise, check to see if the rest of the elements are consecutively
1792   // numbered from this value.
1793   unsigned ShiftAmt = SVOp->getMaskElt(i);
1794   if (ShiftAmt < i) return -1;
1795   ShiftAmt -= i;
1796
1797   // Check the rest of the elements to see if they are consecutive.
1798   for (++i; i != 4; ++i)
1799     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1800       return -1;
1801
1802   return ShiftAmt;
1803 }
1804
1805 //===----------------------------------------------------------------------===//
1806 //  Addressing Mode Selection
1807 //===----------------------------------------------------------------------===//
1808
1809 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1810 /// or 64-bit immediate, and if the value can be accurately represented as a
1811 /// sign extension from a 16-bit value.  If so, this returns true and the
1812 /// immediate.
1813 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1814   if (!isa<ConstantSDNode>(N))
1815     return false;
1816
1817   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1818   if (N->getValueType(0) == MVT::i32)
1819     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1820   else
1821     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1822 }
1823 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1824   return isIntS16Immediate(Op.getNode(), Imm);
1825 }
1826
1827 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1828 /// can be represented as an indexed [r+r] operation.  Returns false if it
1829 /// can be more efficiently represented with [r+imm].
1830 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1831                                             SDValue &Index,
1832                                             SelectionDAG &DAG) const {
1833   short imm = 0;
1834   if (N.getOpcode() == ISD::ADD) {
1835     if (isIntS16Immediate(N.getOperand(1), imm))
1836       return false;    // r+i
1837     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1838       return false;    // r+i
1839
1840     Base = N.getOperand(0);
1841     Index = N.getOperand(1);
1842     return true;
1843   } else if (N.getOpcode() == ISD::OR) {
1844     if (isIntS16Immediate(N.getOperand(1), imm))
1845       return false;    // r+i can fold it if we can.
1846
1847     // If this is an or of disjoint bitfields, we can codegen this as an add
1848     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1849     // disjoint.
1850     APInt LHSKnownZero, LHSKnownOne;
1851     APInt RHSKnownZero, RHSKnownOne;
1852     DAG.computeKnownBits(N.getOperand(0),
1853                          LHSKnownZero, LHSKnownOne);
1854
1855     if (LHSKnownZero.getBoolValue()) {
1856       DAG.computeKnownBits(N.getOperand(1),
1857                            RHSKnownZero, RHSKnownOne);
1858       // If all of the bits are known zero on the LHS or RHS, the add won't
1859       // carry.
1860       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1861         Base = N.getOperand(0);
1862         Index = N.getOperand(1);
1863         return true;
1864       }
1865     }
1866   }
1867
1868   return false;
1869 }
1870
1871 // If we happen to be doing an i64 load or store into a stack slot that has
1872 // less than a 4-byte alignment, then the frame-index elimination may need to
1873 // use an indexed load or store instruction (because the offset may not be a
1874 // multiple of 4). The extra register needed to hold the offset comes from the
1875 // register scavenger, and it is possible that the scavenger will need to use
1876 // an emergency spill slot. As a result, we need to make sure that a spill slot
1877 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1878 // stack slot.
1879 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1880   // FIXME: This does not handle the LWA case.
1881   if (VT != MVT::i64)
1882     return;
1883
1884   // NOTE: We'll exclude negative FIs here, which come from argument
1885   // lowering, because there are no known test cases triggering this problem
1886   // using packed structures (or similar). We can remove this exclusion if
1887   // we find such a test case. The reason why this is so test-case driven is
1888   // because this entire 'fixup' is only to prevent crashes (from the
1889   // register scavenger) on not-really-valid inputs. For example, if we have:
1890   //   %a = alloca i1
1891   //   %b = bitcast i1* %a to i64*
1892   //   store i64* a, i64 b
1893   // then the store should really be marked as 'align 1', but is not. If it
1894   // were marked as 'align 1' then the indexed form would have been
1895   // instruction-selected initially, and the problem this 'fixup' is preventing
1896   // won't happen regardless.
1897   if (FrameIdx < 0)
1898     return;
1899
1900   MachineFunction &MF = DAG.getMachineFunction();
1901   MachineFrameInfo &MFI = MF.getFrameInfo();
1902
1903   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1904   if (Align >= 4)
1905     return;
1906
1907   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1908   FuncInfo->setHasNonRISpills();
1909 }
1910
1911 /// Returns true if the address N can be represented by a base register plus
1912 /// a signed 16-bit displacement [r+imm], and if it is not better
1913 /// represented as reg+reg.  If Aligned is true, only accept displacements
1914 /// suitable for STD and friends, i.e. multiples of 4.
1915 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1916                                             SDValue &Base,
1917                                             SelectionDAG &DAG,
1918                                             bool Aligned) const {
1919   // FIXME dl should come from parent load or store, not from address
1920   SDLoc dl(N);
1921   // If this can be more profitably realized as r+r, fail.
1922   if (SelectAddressRegReg(N, Disp, Base, DAG))
1923     return false;
1924
1925   if (N.getOpcode() == ISD::ADD) {
1926     short imm = 0;
1927     if (isIntS16Immediate(N.getOperand(1), imm) &&
1928         (!Aligned || (imm & 3) == 0)) {
1929       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1930       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1931         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1932         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1933       } else {
1934         Base = N.getOperand(0);
1935       }
1936       return true; // [r+i]
1937     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1938       // Match LOAD (ADD (X, Lo(G))).
1939       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1940              && "Cannot handle constant offsets yet!");
1941       Disp = N.getOperand(1).getOperand(0);  // The global address.
1942       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1943              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1944              Disp.getOpcode() == ISD::TargetConstantPool ||
1945              Disp.getOpcode() == ISD::TargetJumpTable);
1946       Base = N.getOperand(0);
1947       return true;  // [&g+r]
1948     }
1949   } else if (N.getOpcode() == ISD::OR) {
1950     short imm = 0;
1951     if (isIntS16Immediate(N.getOperand(1), imm) &&
1952         (!Aligned || (imm & 3) == 0)) {
1953       // If this is an or of disjoint bitfields, we can codegen this as an add
1954       // (for better address arithmetic) if the LHS and RHS of the OR are
1955       // provably disjoint.
1956       APInt LHSKnownZero, LHSKnownOne;
1957       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1958
1959       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1960         // If all of the bits are known zero on the LHS or RHS, the add won't
1961         // carry.
1962         if (FrameIndexSDNode *FI =
1963               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1964           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1965           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1966         } else {
1967           Base = N.getOperand(0);
1968         }
1969         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1970         return true;
1971       }
1972     }
1973   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1974     // Loading from a constant address.
1975
1976     // If this address fits entirely in a 16-bit sext immediate field, codegen
1977     // this as "d, 0"
1978     short Imm;
1979     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1980       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1981       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1982                              CN->getValueType(0));
1983       return true;
1984     }
1985
1986     // Handle 32-bit sext immediates with LIS + addr mode.
1987     if ((CN->getValueType(0) == MVT::i32 ||
1988          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1989         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1990       int Addr = (int)CN->getZExtValue();
1991
1992       // Otherwise, break this down into an LIS + disp.
1993       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1994
1995       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1996                                    MVT::i32);
1997       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1998       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1999       return true;
2000     }
2001   }
2002
2003   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2004   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2005     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2006     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2007   } else
2008     Base = N;
2009   return true;      // [r+0]
2010 }
2011
2012 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2013 /// represented as an indexed [r+r] operation.
2014 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2015                                                 SDValue &Index,
2016                                                 SelectionDAG &DAG) const {
2017   // Check to see if we can easily represent this as an [r+r] address.  This
2018   // will fail if it thinks that the address is more profitably represented as
2019   // reg+imm, e.g. where imm = 0.
2020   if (SelectAddressRegReg(N, Base, Index, DAG))
2021     return true;
2022
2023   // If the operand is an addition, always emit this as [r+r], since this is
2024   // better (for code size, and execution, as the memop does the add for free)
2025   // than emitting an explicit add.
2026   if (N.getOpcode() == ISD::ADD) {
2027     Base = N.getOperand(0);
2028     Index = N.getOperand(1);
2029     return true;
2030   }
2031
2032   // Otherwise, do it the hard way, using R0 as the base register.
2033   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2034                          N.getValueType());
2035   Index = N;
2036   return true;
2037 }
2038
2039 /// getPreIndexedAddressParts - returns true by value, base pointer and
2040 /// offset pointer and addressing mode by reference if the node's address
2041 /// can be legally represented as pre-indexed load / store address.
2042 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2043                                                   SDValue &Offset,
2044                                                   ISD::MemIndexedMode &AM,
2045                                                   SelectionDAG &DAG) const {
2046   if (DisablePPCPreinc) return false;
2047
2048   bool isLoad = true;
2049   SDValue Ptr;
2050   EVT VT;
2051   unsigned Alignment;
2052   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2053     Ptr = LD->getBasePtr();
2054     VT = LD->getMemoryVT();
2055     Alignment = LD->getAlignment();
2056   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2057     Ptr = ST->getBasePtr();
2058     VT  = ST->getMemoryVT();
2059     Alignment = ST->getAlignment();
2060     isLoad = false;
2061   } else
2062     return false;
2063
2064   // PowerPC doesn't have preinc load/store instructions for vectors (except
2065   // for QPX, which does have preinc r+r forms).
2066   if (VT.isVector()) {
2067     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2068       return false;
2069     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2070       AM = ISD::PRE_INC;
2071       return true;
2072     }
2073   }
2074
2075   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2076     // Common code will reject creating a pre-inc form if the base pointer
2077     // is a frame index, or if N is a store and the base pointer is either
2078     // the same as or a predecessor of the value being stored.  Check for
2079     // those situations here, and try with swapped Base/Offset instead.
2080     bool Swap = false;
2081
2082     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2083       Swap = true;
2084     else if (!isLoad) {
2085       SDValue Val = cast<StoreSDNode>(N)->getValue();
2086       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2087         Swap = true;
2088     }
2089
2090     if (Swap)
2091       std::swap(Base, Offset);
2092
2093     AM = ISD::PRE_INC;
2094     return true;
2095   }
2096
2097   // LDU/STU can only handle immediates that are a multiple of 4.
2098   if (VT != MVT::i64) {
2099     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2100       return false;
2101   } else {
2102     // LDU/STU need an address with at least 4-byte alignment.
2103     if (Alignment < 4)
2104       return false;
2105
2106     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2107       return false;
2108   }
2109
2110   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2111     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2112     // sext i32 to i64 when addr mode is r+i.
2113     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2114         LD->getExtensionType() == ISD::SEXTLOAD &&
2115         isa<ConstantSDNode>(Offset))
2116       return false;
2117   }
2118
2119   AM = ISD::PRE_INC;
2120   return true;
2121 }
2122
2123 //===----------------------------------------------------------------------===//
2124 //  LowerOperation implementation
2125 //===----------------------------------------------------------------------===//
2126
2127 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2128 /// and LoOpFlags to the target MO flags.
2129 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2130                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2131                                const GlobalValue *GV = nullptr) {
2132   HiOpFlags = PPCII::MO_HA;
2133   LoOpFlags = PPCII::MO_LO;
2134
2135   // Don't use the pic base if not in PIC relocation model.
2136   if (IsPIC) {
2137     HiOpFlags |= PPCII::MO_PIC_FLAG;
2138     LoOpFlags |= PPCII::MO_PIC_FLAG;
2139   }
2140
2141   // If this is a reference to a global value that requires a non-lazy-ptr, make
2142   // sure that instruction lowering adds it.
2143   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2144     HiOpFlags |= PPCII::MO_NLP_FLAG;
2145     LoOpFlags |= PPCII::MO_NLP_FLAG;
2146
2147     if (GV->hasHiddenVisibility()) {
2148       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2149       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2150     }
2151   }
2152 }
2153
2154 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2155                              SelectionDAG &DAG) {
2156   SDLoc DL(HiPart);
2157   EVT PtrVT = HiPart.getValueType();
2158   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2159
2160   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2161   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2162
2163   // With PIC, the first instruction is actually "GR+hi(&G)".
2164   if (isPIC)
2165     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2166                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2167
2168   // Generate non-pic code that has direct accesses to the constant pool.
2169   // The address of the global is just (hi(&g)+lo(&g)).
2170   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2171 }
2172
2173 static void setUsesTOCBasePtr(MachineFunction &MF) {
2174   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2175   FuncInfo->setUsesTOCBasePtr();
2176 }
2177
2178 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2179   setUsesTOCBasePtr(DAG.getMachineFunction());
2180 }
2181
2182 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2183                            SDValue GA) {
2184   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2185   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2186                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2187
2188   SDValue Ops[] = { GA, Reg };
2189   return DAG.getMemIntrinsicNode(
2190       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2191       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2192       false, 0);
2193 }
2194
2195 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2196                                              SelectionDAG &DAG) const {
2197   EVT PtrVT = Op.getValueType();
2198   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2199   const Constant *C = CP->getConstVal();
2200
2201   // 64-bit SVR4 ABI code is always position-independent.
2202   // The actual address of the GlobalValue is stored in the TOC.
2203   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2204     setUsesTOCBasePtr(DAG);
2205     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2206     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2207   }
2208
2209   unsigned MOHiFlag, MOLoFlag;
2210   bool IsPIC = isPositionIndependent();
2211   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2212
2213   if (IsPIC && Subtarget.isSVR4ABI()) {
2214     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2215                                            PPCII::MO_PIC_FLAG);
2216     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2217   }
2218
2219   SDValue CPIHi =
2220     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2221   SDValue CPILo =
2222     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2223   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2224 }
2225
2226 // For 64-bit PowerPC, prefer the more compact relative encodings.
2227 // This trades 32 bits per jump table entry for one or two instructions
2228 // on the jump site.
2229 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2230   if (isJumpTableRelative())
2231     return MachineJumpTableInfo::EK_LabelDifference32;
2232
2233   return TargetLowering::getJumpTableEncoding();
2234 }
2235
2236 bool PPCTargetLowering::isJumpTableRelative() const {
2237   if (Subtarget.isPPC64())
2238     return true;
2239   return TargetLowering::isJumpTableRelative();
2240 }
2241
2242 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2243                                                     SelectionDAG &DAG) const {
2244   if (!Subtarget.isPPC64())
2245     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2246
2247   switch (getTargetMachine().getCodeModel()) {
2248   case CodeModel::Default:
2249   case CodeModel::Small:
2250   case CodeModel::Medium:
2251     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2252   default:
2253     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2254                        getPointerTy(DAG.getDataLayout()));
2255   }
2256 }
2257
2258 const MCExpr *
2259 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2260                                                 unsigned JTI,
2261                                                 MCContext &Ctx) const {
2262   if (!Subtarget.isPPC64())
2263     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2264
2265   switch (getTargetMachine().getCodeModel()) {
2266   case CodeModel::Default:
2267   case CodeModel::Small:
2268   case CodeModel::Medium:
2269     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2270   default:
2271     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2272   }
2273 }
2274
2275 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2276   EVT PtrVT = Op.getValueType();
2277   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2278
2279   // 64-bit SVR4 ABI code is always position-independent.
2280   // The actual address of the GlobalValue is stored in the TOC.
2281   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2282     setUsesTOCBasePtr(DAG);
2283     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2284     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2285   }
2286
2287   unsigned MOHiFlag, MOLoFlag;
2288   bool IsPIC = isPositionIndependent();
2289   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2290
2291   if (IsPIC && Subtarget.isSVR4ABI()) {
2292     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2293                                         PPCII::MO_PIC_FLAG);
2294     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2295   }
2296
2297   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2298   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2299   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2300 }
2301
2302 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2303                                              SelectionDAG &DAG) const {
2304   EVT PtrVT = Op.getValueType();
2305   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2306   const BlockAddress *BA = BASDN->getBlockAddress();
2307
2308   // 64-bit SVR4 ABI code is always position-independent.
2309   // The actual BlockAddress is stored in the TOC.
2310   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2311     setUsesTOCBasePtr(DAG);
2312     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2313     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2314   }
2315
2316   unsigned MOHiFlag, MOLoFlag;
2317   bool IsPIC = isPositionIndependent();
2318   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2319   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2320   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2321   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2322 }
2323
2324 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2325                                               SelectionDAG &DAG) const {
2326   // FIXME: TLS addresses currently use medium model code sequences,
2327   // which is the most useful form.  Eventually support for small and
2328   // large models could be added if users need it, at the cost of
2329   // additional complexity.
2330   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2331   if (DAG.getTarget().Options.EmulatedTLS)
2332     return LowerToTLSEmulatedModel(GA, DAG);
2333
2334   SDLoc dl(GA);
2335   const GlobalValue *GV = GA->getGlobal();
2336   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2337   bool is64bit = Subtarget.isPPC64();
2338   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2339   PICLevel::Level picLevel = M->getPICLevel();
2340
2341   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2342
2343   if (Model == TLSModel::LocalExec) {
2344     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2345                                                PPCII::MO_TPREL_HA);
2346     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2347                                                PPCII::MO_TPREL_LO);
2348     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2349                                      is64bit ? MVT::i64 : MVT::i32);
2350     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2351     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2352   }
2353
2354   if (Model == TLSModel::InitialExec) {
2355     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2356     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2357                                                 PPCII::MO_TLS);
2358     SDValue GOTPtr;
2359     if (is64bit) {
2360       setUsesTOCBasePtr(DAG);
2361       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2362       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2363                            PtrVT, GOTReg, TGA);
2364     } else
2365       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2366     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2367                                    PtrVT, TGA, GOTPtr);
2368     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2369   }
2370
2371   if (Model == TLSModel::GeneralDynamic) {
2372     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2373     SDValue GOTPtr;
2374     if (is64bit) {
2375       setUsesTOCBasePtr(DAG);
2376       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2377       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2378                                    GOTReg, TGA);
2379     } else {
2380       if (picLevel == PICLevel::SmallPIC)
2381         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2382       else
2383         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2384     }
2385     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2386                        GOTPtr, TGA, TGA);
2387   }
2388
2389   if (Model == TLSModel::LocalDynamic) {
2390     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2391     SDValue GOTPtr;
2392     if (is64bit) {
2393       setUsesTOCBasePtr(DAG);
2394       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2395       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2396                            GOTReg, TGA);
2397     } else {
2398       if (picLevel == PICLevel::SmallPIC)
2399         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2400       else
2401         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2402     }
2403     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2404                                   PtrVT, GOTPtr, TGA, TGA);
2405     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2406                                       PtrVT, TLSAddr, TGA);
2407     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2408   }
2409
2410   llvm_unreachable("Unknown TLS model!");
2411 }
2412
2413 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2414                                               SelectionDAG &DAG) const {
2415   EVT PtrVT = Op.getValueType();
2416   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2417   SDLoc DL(GSDN);
2418   const GlobalValue *GV = GSDN->getGlobal();
2419
2420   // 64-bit SVR4 ABI code is always position-independent.
2421   // The actual address of the GlobalValue is stored in the TOC.
2422   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2423     setUsesTOCBasePtr(DAG);
2424     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2425     return getTOCEntry(DAG, DL, true, GA);
2426   }
2427
2428   unsigned MOHiFlag, MOLoFlag;
2429   bool IsPIC = isPositionIndependent();
2430   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2431
2432   if (IsPIC && Subtarget.isSVR4ABI()) {
2433     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2434                                             GSDN->getOffset(),
2435                                             PPCII::MO_PIC_FLAG);
2436     return getTOCEntry(DAG, DL, false, GA);
2437   }
2438
2439   SDValue GAHi =
2440     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2441   SDValue GALo =
2442     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2443
2444   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2445
2446   // If the global reference is actually to a non-lazy-pointer, we have to do an
2447   // extra load to get the address of the global.
2448   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2449     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2450   return Ptr;
2451 }
2452
2453 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2454   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2455   SDLoc dl(Op);
2456
2457   if (Op.getValueType() == MVT::v2i64) {
2458     // When the operands themselves are v2i64 values, we need to do something
2459     // special because VSX has no underlying comparison operations for these.
2460     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2461       // Equality can be handled by casting to the legal type for Altivec
2462       // comparisons, everything else needs to be expanded.
2463       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2464         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2465                  DAG.getSetCC(dl, MVT::v4i32,
2466                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2467                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2468                    CC));
2469       }
2470
2471       return SDValue();
2472     }
2473
2474     // We handle most of these in the usual way.
2475     return Op;
2476   }
2477
2478   // If we're comparing for equality to zero, expose the fact that this is
2479   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2480   // fold the new nodes.
2481   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2482     return V;
2483
2484   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2485     // Leave comparisons against 0 and -1 alone for now, since they're usually
2486     // optimized.  FIXME: revisit this when we can custom lower all setcc
2487     // optimizations.
2488     if (C->isAllOnesValue() || C->isNullValue())
2489       return SDValue();
2490   }
2491
2492   // If we have an integer seteq/setne, turn it into a compare against zero
2493   // by xor'ing the rhs with the lhs, which is faster than setting a
2494   // condition register, reading it back out, and masking the correct bit.  The
2495   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2496   // the result to other bit-twiddling opportunities.
2497   EVT LHSVT = Op.getOperand(0).getValueType();
2498   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2499     EVT VT = Op.getValueType();
2500     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2501                                 Op.getOperand(1));
2502     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2503   }
2504   return SDValue();
2505 }
2506
2507 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2508   SDNode *Node = Op.getNode();
2509   EVT VT = Node->getValueType(0);
2510   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2511   SDValue InChain = Node->getOperand(0);
2512   SDValue VAListPtr = Node->getOperand(1);
2513   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2514   SDLoc dl(Node);
2515
2516   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2517
2518   // gpr_index
2519   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2520                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2521   InChain = GprIndex.getValue(1);
2522
2523   if (VT == MVT::i64) {
2524     // Check if GprIndex is even
2525     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2526                                  DAG.getConstant(1, dl, MVT::i32));
2527     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2528                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2529     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2530                                           DAG.getConstant(1, dl, MVT::i32));
2531     // Align GprIndex to be even if it isn't
2532     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2533                            GprIndex);
2534   }
2535
2536   // fpr index is 1 byte after gpr
2537   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2538                                DAG.getConstant(1, dl, MVT::i32));
2539
2540   // fpr
2541   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2542                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2543   InChain = FprIndex.getValue(1);
2544
2545   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2546                                        DAG.getConstant(8, dl, MVT::i32));
2547
2548   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2549                                         DAG.getConstant(4, dl, MVT::i32));
2550
2551   // areas
2552   SDValue OverflowArea =
2553       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2554   InChain = OverflowArea.getValue(1);
2555
2556   SDValue RegSaveArea =
2557       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2558   InChain = RegSaveArea.getValue(1);
2559
2560   // select overflow_area if index > 8
2561   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2562                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2563
2564   // adjustment constant gpr_index * 4/8
2565   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2566                                     VT.isInteger() ? GprIndex : FprIndex,
2567                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2568                                                     MVT::i32));
2569
2570   // OurReg = RegSaveArea + RegConstant
2571   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2572                                RegConstant);
2573
2574   // Floating types are 32 bytes into RegSaveArea
2575   if (VT.isFloatingPoint())
2576     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2577                          DAG.getConstant(32, dl, MVT::i32));
2578
2579   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2580   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2581                                    VT.isInteger() ? GprIndex : FprIndex,
2582                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2583                                                    MVT::i32));
2584
2585   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2586                               VT.isInteger() ? VAListPtr : FprPtr,
2587                               MachinePointerInfo(SV), MVT::i8);
2588
2589   // determine if we should load from reg_save_area or overflow_area
2590   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2591
2592   // increase overflow_area by 4/8 if gpr/fpr > 8
2593   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2594                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2595                                           dl, MVT::i32));
2596
2597   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2598                              OverflowAreaPlusN);
2599
2600   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2601                               MachinePointerInfo(), MVT::i32);
2602
2603   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2604 }
2605
2606 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2607   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2608
2609   // We have to copy the entire va_list struct:
2610   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2611   return DAG.getMemcpy(Op.getOperand(0), Op,
2612                        Op.getOperand(1), Op.getOperand(2),
2613                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2614                        false, MachinePointerInfo(), MachinePointerInfo());
2615 }
2616
2617 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2618                                                   SelectionDAG &DAG) const {
2619   return Op.getOperand(0);
2620 }
2621
2622 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2623                                                 SelectionDAG &DAG) const {
2624   SDValue Chain = Op.getOperand(0);
2625   SDValue Trmp = Op.getOperand(1); // trampoline
2626   SDValue FPtr = Op.getOperand(2); // nested function
2627   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2628   SDLoc dl(Op);
2629
2630   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2631   bool isPPC64 = (PtrVT == MVT::i64);
2632   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2633
2634   TargetLowering::ArgListTy Args;
2635   TargetLowering::ArgListEntry Entry;
2636
2637   Entry.Ty = IntPtrTy;
2638   Entry.Node = Trmp; Args.push_back(Entry);
2639
2640   // TrampSize == (isPPC64 ? 48 : 40);
2641   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2642                                isPPC64 ? MVT::i64 : MVT::i32);
2643   Args.push_back(Entry);
2644
2645   Entry.Node = FPtr; Args.push_back(Entry);
2646   Entry.Node = Nest; Args.push_back(Entry);
2647
2648   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2649   TargetLowering::CallLoweringInfo CLI(DAG);
2650   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2651       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2652       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2653
2654   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2655   return CallResult.second;
2656 }
2657
2658 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2659   MachineFunction &MF = DAG.getMachineFunction();
2660   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2661   EVT PtrVT = getPointerTy(MF.getDataLayout());
2662
2663   SDLoc dl(Op);
2664
2665   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2666     // vastart just stores the address of the VarArgsFrameIndex slot into the
2667     // memory location argument.
2668     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2669     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2670     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2671                         MachinePointerInfo(SV));
2672   }
2673
2674   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2675   // We suppose the given va_list is already allocated.
2676   //
2677   // typedef struct {
2678   //  char gpr;     /* index into the array of 8 GPRs
2679   //                 * stored in the register save area
2680   //                 * gpr=0 corresponds to r3,
2681   //                 * gpr=1 to r4, etc.
2682   //                 */
2683   //  char fpr;     /* index into the array of 8 FPRs
2684   //                 * stored in the register save area
2685   //                 * fpr=0 corresponds to f1,
2686   //                 * fpr=1 to f2, etc.
2687   //                 */
2688   //  char *overflow_arg_area;
2689   //                /* location on stack that holds
2690   //                 * the next overflow argument
2691   //                 */
2692   //  char *reg_save_area;
2693   //               /* where r3:r10 and f1:f8 (if saved)
2694   //                * are stored
2695   //                */
2696   // } va_list[1];
2697
2698   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2699   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2700   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2701                                             PtrVT);
2702   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2703                                  PtrVT);
2704
2705   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2706   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2707
2708   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2709   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2710
2711   uint64_t FPROffset = 1;
2712   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2713
2714   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2715
2716   // Store first byte : number of int regs
2717   SDValue firstStore =
2718       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2719                         MachinePointerInfo(SV), MVT::i8);
2720   uint64_t nextOffset = FPROffset;
2721   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2722                                   ConstFPROffset);
2723
2724   // Store second byte : number of float regs
2725   SDValue secondStore =
2726       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2727                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2728   nextOffset += StackOffset;
2729   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2730
2731   // Store second word : arguments given on stack
2732   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2733                                     MachinePointerInfo(SV, nextOffset));
2734   nextOffset += FrameOffset;
2735   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2736
2737   // Store third word : arguments given in registers
2738   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2739                       MachinePointerInfo(SV, nextOffset));
2740 }
2741
2742 #include "PPCGenCallingConv.inc"
2743
2744 // Function whose sole purpose is to kill compiler warnings
2745 // stemming from unused functions included from PPCGenCallingConv.inc.
2746 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2747   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2748 }
2749
2750 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2751                                       CCValAssign::LocInfo &LocInfo,
2752                                       ISD::ArgFlagsTy &ArgFlags,
2753                                       CCState &State) {
2754   return true;
2755 }
2756
2757 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2758                                              MVT &LocVT,
2759                                              CCValAssign::LocInfo &LocInfo,
2760                                              ISD::ArgFlagsTy &ArgFlags,
2761                                              CCState &State) {
2762   static const MCPhysReg ArgRegs[] = {
2763     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2764     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2765   };
2766   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2767
2768   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2769
2770   // Skip one register if the first unallocated register has an even register
2771   // number and there are still argument registers available which have not been
2772   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2773   // need to skip a register if RegNum is odd.
2774   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2775     State.AllocateReg(ArgRegs[RegNum]);
2776   }
2777
2778   // Always return false here, as this function only makes sure that the first
2779   // unallocated register has an odd register number and does not actually
2780   // allocate a register for the current argument.
2781   return false;
2782 }
2783
2784 bool
2785 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2786                                                   MVT &LocVT,
2787                                                   CCValAssign::LocInfo &LocInfo,
2788                                                   ISD::ArgFlagsTy &ArgFlags,
2789                                                   CCState &State) {
2790   static const MCPhysReg ArgRegs[] = {
2791     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2792     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2793   };
2794   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2795
2796   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2797   int RegsLeft = NumArgRegs - RegNum;
2798
2799   // Skip if there is not enough registers left for long double type (4 gpr regs
2800   // in soft float mode) and put long double argument on the stack.
2801   if (RegNum != NumArgRegs && RegsLeft < 4) {
2802     for (int i = 0; i < RegsLeft; i++) {
2803       State.AllocateReg(ArgRegs[RegNum + i]);
2804     }
2805   }
2806
2807   return false;
2808 }
2809
2810 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2811                                                MVT &LocVT,
2812                                                CCValAssign::LocInfo &LocInfo,
2813                                                ISD::ArgFlagsTy &ArgFlags,
2814                                                CCState &State) {
2815   static const MCPhysReg ArgRegs[] = {
2816     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2817     PPC::F8
2818   };
2819
2820   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2821
2822   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2823
2824   // If there is only one Floating-point register left we need to put both f64
2825   // values of a split ppc_fp128 value on the stack.
2826   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2827     State.AllocateReg(ArgRegs[RegNum]);
2828   }
2829
2830   // Always return false here, as this function only makes sure that the two f64
2831   // values a ppc_fp128 value is split into are both passed in registers or both
2832   // passed on the stack and does not actually allocate a register for the
2833   // current argument.
2834   return false;
2835 }
2836
2837 /// FPR - The set of FP registers that should be allocated for arguments,
2838 /// on Darwin.
2839 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2840                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2841                                 PPC::F11, PPC::F12, PPC::F13};
2842
2843 /// QFPR - The set of QPX registers that should be allocated for arguments.
2844 static const MCPhysReg QFPR[] = {
2845     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2846     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2847
2848 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2849 /// the stack.
2850 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2851                                        unsigned PtrByteSize) {
2852   unsigned ArgSize = ArgVT.getStoreSize();
2853   if (Flags.isByVal())
2854     ArgSize = Flags.getByValSize();
2855
2856   // Round up to multiples of the pointer size, except for array members,
2857   // which are always packed.
2858   if (!Flags.isInConsecutiveRegs())
2859     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2860
2861   return ArgSize;
2862 }
2863
2864 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2865 /// on the stack.
2866 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2867                                             ISD::ArgFlagsTy Flags,
2868                                             unsigned PtrByteSize) {
2869   unsigned Align = PtrByteSize;
2870
2871   // Altivec parameters are padded to a 16 byte boundary.
2872   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2873       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2874       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2875       ArgVT == MVT::v1i128)
2876     Align = 16;
2877   // QPX vector types stored in double-precision are padded to a 32 byte
2878   // boundary.
2879   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2880     Align = 32;
2881
2882   // ByVal parameters are aligned as requested.
2883   if (Flags.isByVal()) {
2884     unsigned BVAlign = Flags.getByValAlign();
2885     if (BVAlign > PtrByteSize) {
2886       if (BVAlign % PtrByteSize != 0)
2887           llvm_unreachable(
2888             "ByVal alignment is not a multiple of the pointer size");
2889
2890       Align = BVAlign;
2891     }
2892   }
2893
2894   // Array members are always packed to their original alignment.
2895   if (Flags.isInConsecutiveRegs()) {
2896     // If the array member was split into multiple registers, the first
2897     // needs to be aligned to the size of the full type.  (Except for
2898     // ppcf128, which is only aligned as its f64 components.)
2899     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2900       Align = OrigVT.getStoreSize();
2901     else
2902       Align = ArgVT.getStoreSize();
2903   }
2904
2905   return Align;
2906 }
2907
2908 /// CalculateStackSlotUsed - Return whether this argument will use its
2909 /// stack slot (instead of being passed in registers).  ArgOffset,
2910 /// AvailableFPRs, and AvailableVRs must hold the current argument
2911 /// position, and will be updated to account for this argument.
2912 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2913                                    ISD::ArgFlagsTy Flags,
2914                                    unsigned PtrByteSize,
2915                                    unsigned LinkageSize,
2916                                    unsigned ParamAreaSize,
2917                                    unsigned &ArgOffset,
2918                                    unsigned &AvailableFPRs,
2919                                    unsigned &AvailableVRs, bool HasQPX) {
2920   bool UseMemory = false;
2921
2922   // Respect alignment of argument on the stack.
2923   unsigned Align =
2924     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2925   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2926   // If there's no space left in the argument save area, we must
2927   // use memory (this check also catches zero-sized arguments).
2928   if (ArgOffset >= LinkageSize + ParamAreaSize)
2929     UseMemory = true;
2930
2931   // Allocate argument on the stack.
2932   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2933   if (Flags.isInConsecutiveRegsLast())
2934     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2935   // If we overran the argument save area, we must use memory
2936   // (this check catches arguments passed partially in memory)
2937   if (ArgOffset > LinkageSize + ParamAreaSize)
2938     UseMemory = true;
2939
2940   // However, if the argument is actually passed in an FPR or a VR,
2941   // we don't use memory after all.
2942   if (!Flags.isByVal()) {
2943     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2944         // QPX registers overlap with the scalar FP registers.
2945         (HasQPX && (ArgVT == MVT::v4f32 ||
2946                     ArgVT == MVT::v4f64 ||
2947                     ArgVT == MVT::v4i1)))
2948       if (AvailableFPRs > 0) {
2949         --AvailableFPRs;
2950         return false;
2951       }
2952     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2953         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2954         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2955         ArgVT == MVT::v1i128)
2956       if (AvailableVRs > 0) {
2957         --AvailableVRs;
2958         return false;
2959       }
2960   }
2961
2962   return UseMemory;
2963 }
2964
2965 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2966 /// ensure minimum alignment required for target.
2967 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2968                                      unsigned NumBytes) {
2969   unsigned TargetAlign = Lowering->getStackAlignment();
2970   unsigned AlignMask = TargetAlign - 1;
2971   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2972   return NumBytes;
2973 }
2974
2975 SDValue PPCTargetLowering::LowerFormalArguments(
2976     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2977     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2978     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2979   if (Subtarget.isSVR4ABI()) {
2980     if (Subtarget.isPPC64())
2981       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2982                                          dl, DAG, InVals);
2983     else
2984       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2985                                          dl, DAG, InVals);
2986   } else {
2987     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2988                                        dl, DAG, InVals);
2989   }
2990 }
2991
2992 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2993     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2994     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2995     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2996
2997   // 32-bit SVR4 ABI Stack Frame Layout:
2998   //              +-----------------------------------+
2999   //        +-->  |            Back chain             |
3000   //        |     +-----------------------------------+
3001   //        |     | Floating-point register save area |
3002   //        |     +-----------------------------------+
3003   //        |     |    General register save area     |
3004   //        |     +-----------------------------------+
3005   //        |     |          CR save word             |
3006   //        |     +-----------------------------------+
3007   //        |     |         VRSAVE save word          |
3008   //        |     +-----------------------------------+
3009   //        |     |         Alignment padding         |
3010   //        |     +-----------------------------------+
3011   //        |     |     Vector register save area     |
3012   //        |     +-----------------------------------+
3013   //        |     |       Local variable space        |
3014   //        |     +-----------------------------------+
3015   //        |     |        Parameter list area        |
3016   //        |     +-----------------------------------+
3017   //        |     |           LR save word            |
3018   //        |     +-----------------------------------+
3019   // SP-->  +---  |            Back chain             |
3020   //              +-----------------------------------+
3021   //
3022   // Specifications:
3023   //   System V Application Binary Interface PowerPC Processor Supplement
3024   //   AltiVec Technology Programming Interface Manual
3025
3026   MachineFunction &MF = DAG.getMachineFunction();
3027   MachineFrameInfo &MFI = MF.getFrameInfo();
3028   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3029
3030   EVT PtrVT = getPointerTy(MF.getDataLayout());
3031   // Potential tail calls could cause overwriting of argument stack slots.
3032   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3033                        (CallConv == CallingConv::Fast));
3034   unsigned PtrByteSize = 4;
3035
3036   // Assign locations to all of the incoming arguments.
3037   SmallVector<CCValAssign, 16> ArgLocs;
3038   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3039                  *DAG.getContext());
3040
3041   // Reserve space for the linkage area on the stack.
3042   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3043   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3044   if (useSoftFloat())
3045     CCInfo.PreAnalyzeFormalArguments(Ins);
3046
3047   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3048   CCInfo.clearWasPPCF128();
3049
3050   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051     CCValAssign &VA = ArgLocs[i];
3052
3053     // Arguments stored in registers.
3054     if (VA.isRegLoc()) {
3055       const TargetRegisterClass *RC;
3056       EVT ValVT = VA.getValVT();
3057
3058       switch (ValVT.getSimpleVT().SimpleTy) {
3059         default:
3060           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3061         case MVT::i1:
3062         case MVT::i32:
3063           RC = &PPC::GPRCRegClass;
3064           break;
3065         case MVT::f32:
3066           if (Subtarget.hasP8Vector())
3067             RC = &PPC::VSSRCRegClass;
3068           else
3069             RC = &PPC::F4RCRegClass;
3070           break;
3071         case MVT::f64:
3072           if (Subtarget.hasVSX())
3073             RC = &PPC::VSFRCRegClass;
3074           else
3075             RC = &PPC::F8RCRegClass;
3076           break;
3077         case MVT::v16i8:
3078         case MVT::v8i16:
3079         case MVT::v4i32:
3080           RC = &PPC::VRRCRegClass;
3081           break;
3082         case MVT::v4f32:
3083           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3084           break;
3085         case MVT::v2f64:
3086         case MVT::v2i64:
3087           RC = &PPC::VRRCRegClass;
3088           break;
3089         case MVT::v4f64:
3090           RC = &PPC::QFRCRegClass;
3091           break;
3092         case MVT::v4i1:
3093           RC = &PPC::QBRCRegClass;
3094           break;
3095       }
3096
3097       // Transform the arguments stored in physical registers into virtual ones.
3098       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3099       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3100                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3101
3102       if (ValVT == MVT::i1)
3103         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3104
3105       InVals.push_back(ArgValue);
3106     } else {
3107       // Argument stored in memory.
3108       assert(VA.isMemLoc());
3109
3110       unsigned ArgSize = VA.getLocVT().getStoreSize();
3111       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3112                                      isImmutable);
3113
3114       // Create load nodes to retrieve arguments from the stack.
3115       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3116       InVals.push_back(
3117           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3118     }
3119   }
3120
3121   // Assign locations to all of the incoming aggregate by value arguments.
3122   // Aggregates passed by value are stored in the local variable space of the
3123   // caller's stack frame, right above the parameter list area.
3124   SmallVector<CCValAssign, 16> ByValArgLocs;
3125   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3126                       ByValArgLocs, *DAG.getContext());
3127
3128   // Reserve stack space for the allocations in CCInfo.
3129   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3130
3131   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3132
3133   // Area that is at least reserved in the caller of this function.
3134   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3135   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3136
3137   // Set the size that is at least reserved in caller of this function.  Tail
3138   // call optimized function's reserved stack space needs to be aligned so that
3139   // taking the difference between two stack areas will result in an aligned
3140   // stack.
3141   MinReservedArea =
3142       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3143   FuncInfo->setMinReservedArea(MinReservedArea);
3144
3145   SmallVector<SDValue, 8> MemOps;
3146
3147   // If the function takes variable number of arguments, make a frame index for
3148   // the start of the first vararg value... for expansion of llvm.va_start.
3149   if (isVarArg) {
3150     static const MCPhysReg GPArgRegs[] = {
3151       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3152       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3153     };
3154     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3155
3156     static const MCPhysReg FPArgRegs[] = {
3157       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3158       PPC::F8
3159     };
3160     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3161
3162     if (useSoftFloat())
3163        NumFPArgRegs = 0;
3164
3165     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3166     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3167
3168     // Make room for NumGPArgRegs and NumFPArgRegs.
3169     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3170                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3171
3172     FuncInfo->setVarArgsStackOffset(
3173       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3174                             CCInfo.getNextStackOffset(), true));
3175
3176     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3177     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3178
3179     // The fixed integer arguments of a variadic function are stored to the
3180     // VarArgsFrameIndex on the stack so that they may be loaded by
3181     // dereferencing the result of va_next.
3182     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3183       // Get an existing live-in vreg, or add a new one.
3184       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3185       if (!VReg)
3186         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3187
3188       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3189       SDValue Store =
3190           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3191       MemOps.push_back(Store);
3192       // Increment the address by four for the next argument to store
3193       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3194       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3195     }
3196
3197     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3198     // is set.
3199     // The double arguments are stored to the VarArgsFrameIndex
3200     // on the stack.
3201     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3202       // Get an existing live-in vreg, or add a new one.
3203       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3204       if (!VReg)
3205         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3206
3207       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3208       SDValue Store =
3209           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3210       MemOps.push_back(Store);
3211       // Increment the address by eight for the next argument to store
3212       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3213                                          PtrVT);
3214       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3215     }
3216   }
3217
3218   if (!MemOps.empty())
3219     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3220
3221   return Chain;
3222 }
3223
3224 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3225 // value to MVT::i64 and then truncate to the correct register size.
3226 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3227                                              EVT ObjectVT, SelectionDAG &DAG,
3228                                              SDValue ArgVal,
3229                                              const SDLoc &dl) const {
3230   if (Flags.isSExt())
3231     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3232                          DAG.getValueType(ObjectVT));
3233   else if (Flags.isZExt())
3234     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3235                          DAG.getValueType(ObjectVT));
3236
3237   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3238 }
3239
3240 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3241     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3242     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3243     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3244   // TODO: add description of PPC stack frame format, or at least some docs.
3245   //
3246   bool isELFv2ABI = Subtarget.isELFv2ABI();
3247   bool isLittleEndian = Subtarget.isLittleEndian();
3248   MachineFunction &MF = DAG.getMachineFunction();
3249   MachineFrameInfo &MFI = MF.getFrameInfo();
3250   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3251
3252   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3253          "fastcc not supported on varargs functions");
3254
3255   EVT PtrVT = getPointerTy(MF.getDataLayout());
3256   // Potential tail calls could cause overwriting of argument stack slots.
3257   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3258                        (CallConv == CallingConv::Fast));
3259   unsigned PtrByteSize = 8;
3260   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3261
3262   static const MCPhysReg GPR[] = {
3263     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3264     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3265   };
3266   static const MCPhysReg VR[] = {
3267     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3268     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3269   };
3270
3271   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3272   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3273   const unsigned Num_VR_Regs  = array_lengthof(VR);
3274   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3275
3276   // Do a first pass over the arguments to determine whether the ABI
3277   // guarantees that our caller has allocated the parameter save area
3278   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3279   // in the ELFv2 ABI, it is true if this is a vararg function or if
3280   // any parameter is located in a stack slot.
3281
3282   bool HasParameterArea = !isELFv2ABI || isVarArg;
3283   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3284   unsigned NumBytes = LinkageSize;
3285   unsigned AvailableFPRs = Num_FPR_Regs;
3286   unsigned AvailableVRs = Num_VR_Regs;
3287   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3288     if (Ins[i].Flags.isNest())
3289       continue;
3290
3291     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3292                                PtrByteSize, LinkageSize, ParamAreaSize,
3293                                NumBytes, AvailableFPRs, AvailableVRs,
3294                                Subtarget.hasQPX()))
3295       HasParameterArea = true;
3296   }
3297
3298   // Add DAG nodes to load the arguments or copy them out of registers.  On
3299   // entry to a function on PPC, the arguments start after the linkage area,
3300   // although the first ones are often in registers.
3301
3302   unsigned ArgOffset = LinkageSize;
3303   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3304   unsigned &QFPR_idx = FPR_idx;
3305   SmallVector<SDValue, 8> MemOps;
3306   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3307   unsigned CurArgIdx = 0;
3308   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3309     SDValue ArgVal;
3310     bool needsLoad = false;
3311     EVT ObjectVT = Ins[ArgNo].VT;
3312     EVT OrigVT = Ins[ArgNo].ArgVT;
3313     unsigned ObjSize = ObjectVT.getStoreSize();
3314     unsigned ArgSize = ObjSize;
3315     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3316     if (Ins[ArgNo].isOrigArg()) {
3317       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3318       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3319     }
3320     // We re-align the argument offset for each argument, except when using the
3321     // fast calling convention, when we need to make sure we do that only when
3322     // we'll actually use a stack slot.
3323     unsigned CurArgOffset, Align;
3324     auto ComputeArgOffset = [&]() {
3325       /* Respect alignment of argument on the stack.  */
3326       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3327       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3328       CurArgOffset = ArgOffset;
3329     };
3330
3331     if (CallConv != CallingConv::Fast) {
3332       ComputeArgOffset();
3333
3334       /* Compute GPR index associated with argument offset.  */
3335       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3336       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3337     }
3338
3339     // FIXME the codegen can be much improved in some cases.
3340     // We do not have to keep everything in memory.
3341     if (Flags.isByVal()) {
3342       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3343
3344       if (CallConv == CallingConv::Fast)
3345         ComputeArgOffset();
3346
3347       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3348       ObjSize = Flags.getByValSize();
3349       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3350       // Empty aggregate parameters do not take up registers.  Examples:
3351       //   struct { } a;
3352       //   union  { } b;
3353       //   int c[0];
3354       // etc.  However, we have to provide a place-holder in InVals, so
3355       // pretend we have an 8-byte item at the current address for that
3356       // purpose.
3357       if (!ObjSize) {
3358         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3359         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3360         InVals.push_back(FIN);
3361         continue;
3362       }
3363
3364       // Create a stack object covering all stack doublewords occupied
3365       // by the argument.  If the argument is (fully or partially) on
3366       // the stack, or if the argument is fully in registers but the
3367       // caller has allocated the parameter save anyway, we can refer
3368       // directly to the caller's stack frame.  Otherwise, create a
3369       // local copy in our own frame.
3370       int FI;
3371       if (HasParameterArea ||
3372           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3373         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3374       else
3375         FI = MFI.CreateStackObject(ArgSize, Align, false);
3376       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3377
3378       // Handle aggregates smaller than 8 bytes.
3379       if (ObjSize < PtrByteSize) {
3380         // The value of the object is its address, which differs from the
3381         // address of the enclosing doubleword on big-endian systems.
3382         SDValue Arg = FIN;
3383         if (!isLittleEndian) {
3384           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3385           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3386         }
3387         InVals.push_back(Arg);
3388
3389         if (GPR_idx != Num_GPR_Regs) {
3390           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3391           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3392           SDValue Store;
3393
3394           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3395             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3396                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3397             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3398                                       MachinePointerInfo(&*FuncArg), ObjType);
3399           } else {
3400             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3401             // store the whole register as-is to the parameter save area
3402             // slot.
3403             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3404                                  MachinePointerInfo(&*FuncArg));
3405           }
3406
3407           MemOps.push_back(Store);
3408         }
3409         // Whether we copied from a register or not, advance the offset
3410         // into the parameter save area by a full doubleword.
3411         ArgOffset += PtrByteSize;
3412         continue;
3413       }
3414
3415       // The value of the object is its address, which is the address of
3416       // its first stack doubleword.
3417       InVals.push_back(FIN);
3418
3419       // Store whatever pieces of the object are in registers to memory.
3420       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3421         if (GPR_idx == Num_GPR_Regs)
3422           break;
3423
3424         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3425         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3426         SDValue Addr = FIN;
3427         if (j) {
3428           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3429           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3430         }
3431         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3432                                      MachinePointerInfo(&*FuncArg, j));
3433         MemOps.push_back(Store);
3434         ++GPR_idx;
3435       }
3436       ArgOffset += ArgSize;
3437       continue;
3438     }
3439
3440     switch (ObjectVT.getSimpleVT().SimpleTy) {
3441     default: llvm_unreachable("Unhandled argument type!");
3442     case MVT::i1:
3443     case MVT::i32:
3444     case MVT::i64:
3445       if (Flags.isNest()) {
3446         // The 'nest' parameter, if any, is passed in R11.
3447         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3448         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3449
3450         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3451           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3452
3453         break;
3454       }
3455
3456       // These can be scalar arguments or elements of an integer array type
3457       // passed directly.  Clang may use those instead of "byval" aggregate
3458       // types to avoid forcing arguments to memory unnecessarily.
3459       if (GPR_idx != Num_GPR_Regs) {
3460         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3461         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3462
3463         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3464           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3465           // value to MVT::i64 and then truncate to the correct register size.
3466           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3467       } else {
3468         if (CallConv == CallingConv::Fast)
3469           ComputeArgOffset();
3470
3471         needsLoad = true;
3472         ArgSize = PtrByteSize;
3473       }
3474       if (CallConv != CallingConv::Fast || needsLoad)
3475         ArgOffset += 8;
3476       break;
3477
3478     case MVT::f32:
3479     case MVT::f64:
3480       // These can be scalar arguments or elements of a float array type
3481       // passed directly.  The latter are used to implement ELFv2 homogenous
3482       // float aggregates.
3483       if (FPR_idx != Num_FPR_Regs) {
3484         unsigned VReg;
3485
3486         if (ObjectVT == MVT::f32)
3487           VReg = MF.addLiveIn(FPR[FPR_idx],
3488                               Subtarget.hasP8Vector()
3489                                   ? &PPC::VSSRCRegClass
3490                                   : &PPC::F4RCRegClass);
3491         else
3492           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3493                                                 ? &PPC::VSFRCRegClass
3494                                                 : &PPC::F8RCRegClass);
3495
3496         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3497         ++FPR_idx;
3498       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3499         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3500         // once we support fp <-> gpr moves.
3501
3502         // This can only ever happen in the presence of f32 array types,
3503         // since otherwise we never run out of FPRs before running out
3504         // of GPRs.
3505         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3506         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3507
3508         if (ObjectVT == MVT::f32) {
3509           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3510             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3511                                  DAG.getConstant(32, dl, MVT::i32));
3512           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3513         }
3514
3515         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3516       } else {
3517         if (CallConv == CallingConv::Fast)
3518           ComputeArgOffset();
3519
3520         needsLoad = true;
3521       }
3522
3523       // When passing an array of floats, the array occupies consecutive
3524       // space in the argument area; only round up to the next doubleword
3525       // at the end of the array.  Otherwise, each float takes 8 bytes.
3526       if (CallConv != CallingConv::Fast || needsLoad) {
3527         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3528         ArgOffset += ArgSize;
3529         if (Flags.isInConsecutiveRegsLast())
3530           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3531       }
3532       break;
3533     case MVT::v4f32:
3534     case MVT::v4i32:
3535     case MVT::v8i16:
3536     case MVT::v16i8:
3537     case MVT::v2f64:
3538     case MVT::v2i64:
3539     case MVT::v1i128:
3540       if (!Subtarget.hasQPX()) {
3541       // These can be scalar arguments or elements of a vector array type
3542       // passed directly.  The latter are used to implement ELFv2 homogenous
3543       // vector aggregates.
3544       if (VR_idx != Num_VR_Regs) {
3545         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3546         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3547         ++VR_idx;
3548       } else {
3549         if (CallConv == CallingConv::Fast)
3550           ComputeArgOffset();
3551
3552         needsLoad = true;
3553       }
3554       if (CallConv != CallingConv::Fast || needsLoad)
3555         ArgOffset += 16;
3556       break;
3557       } // not QPX
3558
3559       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3560              "Invalid QPX parameter type");
3561       /* fall through */
3562
3563     case MVT::v4f64:
3564     case MVT::v4i1:
3565       // QPX vectors are treated like their scalar floating-point subregisters
3566       // (except that they're larger).
3567       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3568       if (QFPR_idx != Num_QFPR_Regs) {
3569         const TargetRegisterClass *RC;
3570         switch (ObjectVT.getSimpleVT().SimpleTy) {
3571         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3572         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3573         default:         RC = &PPC::QBRCRegClass; break;
3574         }
3575
3576         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3577         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3578         ++QFPR_idx;
3579       } else {
3580         if (CallConv == CallingConv::Fast)
3581           ComputeArgOffset();
3582         needsLoad = true;
3583       }
3584       if (CallConv != CallingConv::Fast || needsLoad)
3585         ArgOffset += Sz;
3586       break;
3587     }
3588
3589     // We need to load the argument to a virtual register if we determined
3590     // above that we ran out of physical registers of the appropriate type.
3591     if (needsLoad) {
3592       if (ObjSize < ArgSize && !isLittleEndian)
3593         CurArgOffset += ArgSize - ObjSize;
3594       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3595       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3596       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3597     }
3598
3599     InVals.push_back(ArgVal);
3600   }
3601
3602   // Area that is at least reserved in the caller of this function.
3603   unsigned MinReservedArea;
3604   if (HasParameterArea)
3605     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3606   else
3607     MinReservedArea = LinkageSize;
3608
3609   // Set the size that is at least reserved in caller of this function.  Tail
3610   // call optimized functions' reserved stack space needs to be aligned so that
3611   // taking the difference between two stack areas will result in an aligned
3612   // stack.
3613   MinReservedArea =
3614       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3615   FuncInfo->setMinReservedArea(MinReservedArea);
3616
3617   // If the function takes variable number of arguments, make a frame index for
3618   // the start of the first vararg value... for expansion of llvm.va_start.
3619   if (isVarArg) {
3620     int Depth = ArgOffset;
3621
3622     FuncInfo->setVarArgsFrameIndex(
3623       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3624     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3625
3626     // If this function is vararg, store any remaining integer argument regs
3627     // to their spots on the stack so that they may be loaded by dereferencing
3628     // the result of va_next.
3629     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3630          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3631       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3632       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3633       SDValue Store =
3634           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3635       MemOps.push_back(Store);
3636       // Increment the address by four for the next argument to store
3637       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3638       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3639     }
3640   }
3641
3642   if (!MemOps.empty())
3643     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3644
3645   return Chain;
3646 }
3647
3648 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3649     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3650     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3651     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3652   // TODO: add description of PPC stack frame format, or at least some docs.
3653   //
3654   MachineFunction &MF = DAG.getMachineFunction();
3655   MachineFrameInfo &MFI = MF.getFrameInfo();
3656   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3657
3658   EVT PtrVT = getPointerTy(MF.getDataLayout());
3659   bool isPPC64 = PtrVT == MVT::i64;
3660   // Potential tail calls could cause overwriting of argument stack slots.
3661   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3662                        (CallConv == CallingConv::Fast));
3663   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3664   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3665   unsigned ArgOffset = LinkageSize;
3666   // Area that is at least reserved in caller of this function.
3667   unsigned MinReservedArea = ArgOffset;
3668
3669   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3670     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3671     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3672   };
3673   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3674     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3675     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3676   };
3677   static const MCPhysReg VR[] = {
3678     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3679     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3680   };
3681
3682   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3683   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3684   const unsigned Num_VR_Regs  = array_lengthof( VR);
3685
3686   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3687
3688   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3689
3690   // In 32-bit non-varargs functions, the stack space for vectors is after the
3691   // stack space for non-vectors.  We do not use this space unless we have
3692   // too many vectors to fit in registers, something that only occurs in
3693   // constructed examples:), but we have to walk the arglist to figure
3694   // that out...for the pathological case, compute VecArgOffset as the
3695   // start of the vector parameter area.  Computing VecArgOffset is the
3696   // entire point of the following loop.
3697   unsigned VecArgOffset = ArgOffset;
3698   if (!isVarArg && !isPPC64) {
3699     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3700          ++ArgNo) {
3701       EVT ObjectVT = Ins[ArgNo].VT;
3702       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3703
3704       if (Flags.isByVal()) {
3705         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3706         unsigned ObjSize = Flags.getByValSize();
3707         unsigned ArgSize =
3708                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3709         VecArgOffset += ArgSize;
3710         continue;
3711       }
3712
3713       switch(ObjectVT.getSimpleVT().SimpleTy) {
3714       default: llvm_unreachable("Unhandled argument type!");
3715       case MVT::i1:
3716       case MVT::i32:
3717       case MVT::f32:
3718         VecArgOffset += 4;
3719         break;
3720       case MVT::i64:  // PPC64
3721       case MVT::f64:
3722         // FIXME: We are guaranteed to be !isPPC64 at this point.
3723         // Does MVT::i64 apply?
3724         VecArgOffset += 8;
3725         break;
3726       case MVT::v4f32:
3727       case MVT::v4i32:
3728       case MVT::v8i16:
3729       case MVT::v16i8:
3730         // Nothing to do, we're only looking at Nonvector args here.
3731         break;
3732       }
3733     }
3734   }
3735   // We've found where the vector parameter area in memory is.  Skip the
3736   // first 12 parameters; these don't use that memory.
3737   VecArgOffset = ((VecArgOffset+15)/16)*16;
3738   VecArgOffset += 12*16;
3739
3740   // Add DAG nodes to load the arguments or copy them out of registers.  On
3741   // entry to a function on PPC, the arguments start after the linkage area,
3742   // although the first ones are often in registers.
3743
3744   SmallVector<SDValue, 8> MemOps;
3745   unsigned nAltivecParamsAtEnd = 0;
3746   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3747   unsigned CurArgIdx = 0;
3748   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3749     SDValue ArgVal;
3750     bool needsLoad = false;
3751     EVT ObjectVT = Ins[ArgNo].VT;
3752     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3753     unsigned ArgSize = ObjSize;
3754     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3755     if (Ins[ArgNo].isOrigArg()) {
3756       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3757       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3758     }
3759     unsigned CurArgOffset = ArgOffset;
3760
3761     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3762     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3763         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3764       if (isVarArg || isPPC64) {
3765         MinReservedArea = ((MinReservedArea+15)/16)*16;
3766         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3767                                                   Flags,
3768                                                   PtrByteSize);
3769       } else  nAltivecParamsAtEnd++;
3770     } else
3771       // Calculate min reserved area.
3772       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3773                                                 Flags,
3774                                                 PtrByteSize);
3775
3776     // FIXME the codegen can be much improved in some cases.
3777     // We do not have to keep everything in memory.
3778     if (Flags.isByVal()) {
3779       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3780
3781       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3782       ObjSize = Flags.getByValSize();
3783       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3784       // Objects of size 1 and 2 are right justified, everything else is
3785       // left justified.  This means the memory address is adjusted forwards.
3786       if (ObjSize==1 || ObjSize==2) {
3787         CurArgOffset = CurArgOffset + (4 - ObjSize);
3788       }
3789       // The value of the object is its address.
3790       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3791       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3792       InVals.push_back(FIN);
3793       if (ObjSize==1 || ObjSize==2) {
3794         if (GPR_idx != Num_GPR_Regs) {
3795           unsigned VReg;
3796           if (isPPC64)
3797             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3798           else
3799             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3800           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3801           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3802           SDValue Store =
3803               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3804                                 MachinePointerInfo(&*FuncArg), ObjType);
3805           MemOps.push_back(Store);
3806           ++GPR_idx;
3807         }
3808
3809         ArgOffset += PtrByteSize;
3810
3811         continue;
3812       }
3813       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3814         // Store whatever pieces of the object are in registers
3815         // to memory.  ArgOffset will be the address of the beginning
3816         // of the object.
3817         if (GPR_idx != Num_GPR_Regs) {
3818           unsigned VReg;
3819           if (isPPC64)
3820             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3821           else
3822             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3823           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3824           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3825           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3826           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3827                                        MachinePointerInfo(&*FuncArg, j));
3828           MemOps.push_back(Store);
3829           ++GPR_idx;
3830           ArgOffset += PtrByteSize;
3831         } else {
3832           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3833           break;
3834         }
3835       }
3836       continue;
3837     }
3838
3839     switch (ObjectVT.getSimpleVT().SimpleTy) {
3840     default: llvm_unreachable("Unhandled argument type!");
3841     case MVT::i1:
3842     case MVT::i32:
3843       if (!isPPC64) {
3844         if (GPR_idx != Num_GPR_Regs) {
3845           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3846           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3847
3848           if (ObjectVT == MVT::i1)
3849             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3850
3851           ++GPR_idx;
3852         } else {
3853           needsLoad = true;
3854           ArgSize = PtrByteSize;
3855         }
3856         // All int arguments reserve stack space in the Darwin ABI.
3857         ArgOffset += PtrByteSize;
3858         break;
3859       }
3860       LLVM_FALLTHROUGH;
3861     case MVT::i64:  // PPC64
3862       if (GPR_idx != Num_GPR_Regs) {
3863         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3864         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3865
3866         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3867           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3868           // value to MVT::i64 and then truncate to the correct register size.
3869           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3870
3871         ++GPR_idx;
3872       } else {
3873         needsLoad = true;
3874         ArgSize = PtrByteSize;
3875       }
3876       // All int arguments reserve stack space in the Darwin ABI.
3877       ArgOffset += 8;
3878       break;
3879
3880     case MVT::f32:
3881     case MVT::f64:
3882       // Every 4 bytes of argument space consumes one of the GPRs available for
3883       // argument passing.
3884       if (GPR_idx != Num_GPR_Regs) {
3885         ++GPR_idx;
3886         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3887           ++GPR_idx;
3888       }
3889       if (FPR_idx != Num_FPR_Regs) {
3890         unsigned VReg;
3891
3892         if (ObjectVT == MVT::f32)
3893           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3894         else
3895           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3896
3897         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3898         ++FPR_idx;
3899       } else {
3900         needsLoad = true;
3901       }
3902
3903       // All FP arguments reserve stack space in the Darwin ABI.
3904       ArgOffset += isPPC64 ? 8 : ObjSize;
3905       break;
3906     case MVT::v4f32:
3907     case MVT::v4i32:
3908     case MVT::v8i16:
3909     case MVT::v16i8:
3910       // Note that vector arguments in registers don't reserve stack space,
3911       // except in varargs functions.
3912       if (VR_idx != Num_VR_Regs) {
3913         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3914         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3915         if (isVarArg) {
3916           while ((ArgOffset % 16) != 0) {
3917             ArgOffset += PtrByteSize;
3918             if (GPR_idx != Num_GPR_Regs)
3919               GPR_idx++;
3920           }
3921           ArgOffset += 16;
3922           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3923         }
3924         ++VR_idx;
3925       } else {
3926         if (!isVarArg && !isPPC64) {
3927           // Vectors go after all the nonvectors.
3928           CurArgOffset = VecArgOffset;
3929           VecArgOffset += 16;
3930         } else {
3931           // Vectors are aligned.
3932           ArgOffset = ((ArgOffset+15)/16)*16;
3933           CurArgOffset = ArgOffset;
3934           ArgOffset += 16;
3935         }
3936         needsLoad = true;
3937       }
3938       break;
3939     }
3940
3941     // We need to load the argument to a virtual register if we determined above
3942     // that we ran out of physical registers of the appropriate type.
3943     if (needsLoad) {
3944       int FI = MFI.CreateFixedObject(ObjSize,
3945                                      CurArgOffset + (ArgSize - ObjSize),
3946                                      isImmutable);
3947       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3948       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3949     }
3950
3951     InVals.push_back(ArgVal);
3952   }
3953
3954   // Allow for Altivec parameters at the end, if needed.
3955   if (nAltivecParamsAtEnd) {
3956     MinReservedArea = ((MinReservedArea+15)/16)*16;
3957     MinReservedArea += 16*nAltivecParamsAtEnd;
3958   }
3959
3960   // Area that is at least reserved in the caller of this function.
3961   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3962
3963   // Set the size that is at least reserved in caller of this function.  Tail
3964   // call optimized functions' reserved stack space needs to be aligned so that
3965   // taking the difference between two stack areas will result in an aligned
3966   // stack.
3967   MinReservedArea =
3968       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3969   FuncInfo->setMinReservedArea(MinReservedArea);
3970
3971   // If the function takes variable number of arguments, make a frame index for
3972   // the start of the first vararg value... for expansion of llvm.va_start.
3973   if (isVarArg) {
3974     int Depth = ArgOffset;
3975
3976     FuncInfo->setVarArgsFrameIndex(
3977       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3978                             Depth, true));
3979     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3980
3981     // If this function is vararg, store any remaining integer argument regs
3982     // to their spots on the stack so that they may be loaded by dereferencing
3983     // the result of va_next.
3984     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3985       unsigned VReg;
3986
3987       if (isPPC64)
3988         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3989       else
3990         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3991
3992       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3993       SDValue Store =
3994           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3995       MemOps.push_back(Store);
3996       // Increment the address by four for the next argument to store
3997       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3998       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3999     }
4000   }
4001
4002   if (!MemOps.empty())
4003     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4004
4005   return Chain;
4006 }
4007
4008 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4009 /// adjusted to accommodate the arguments for the tailcall.
4010 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4011                                    unsigned ParamSize) {
4012
4013   if (!isTailCall) return 0;
4014
4015   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4016   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4017   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4018   // Remember only if the new adjustement is bigger.
4019   if (SPDiff < FI->getTailCallSPDelta())
4020     FI->setTailCallSPDelta(SPDiff);
4021
4022   return SPDiff;
4023 }
4024
4025 static bool isFunctionGlobalAddress(SDValue Callee);
4026
4027 static bool
4028 resideInSameSection(const Function *Caller, SDValue Callee,
4029                     const TargetMachine &TM) {
4030   // If !G, Callee can be an external symbol.
4031   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4032   if (!G)
4033     return false;
4034
4035   const GlobalValue *GV = G->getGlobal();
4036   if (!GV->isStrongDefinitionForLinker())
4037     return false;
4038
4039   // Any explicitly-specified sections and section prefixes must also match.
4040   // Also, if we're using -ffunction-sections, then each function is always in
4041   // a different section (the same is true for COMDAT functions).
4042   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4043       GV->getSection() != Caller->getSection())
4044     return false;
4045   if (const auto *F = dyn_cast<Function>(GV)) {
4046     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4047       return false;
4048   }
4049
4050   // If the callee might be interposed, then we can't assume the ultimate call
4051   // target will be in the same section. Even in cases where we can assume that
4052   // interposition won't happen, in any case where the linker might insert a
4053   // stub to allow for interposition, we must generate code as though
4054   // interposition might occur. To understand why this matters, consider a
4055   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4056   // in the same section, but a is in a different module (i.e. has a different
4057   // TOC base pointer). If the linker allows for interposition between b and c,
4058   // then it will generate a stub for the call edge between b and c which will
4059   // save the TOC pointer into the designated stack slot allocated by b. If we
4060   // return true here, and therefore allow a tail call between b and c, that
4061   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4062   // pointer into the stack slot allocated by a (where the a -> b stub saved
4063   // a's TOC base pointer). If we're not considering a tail call, but rather,
4064   // whether a nop is needed after the call instruction in b, because the linker
4065   // will insert a stub, it might complain about a missing nop if we omit it
4066   // (although many don't complain in this case).
4067   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4068     return false;
4069
4070   return true;
4071 }
4072
4073 static bool
4074 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4075                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4076   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4077
4078   const unsigned PtrByteSize = 8;
4079   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4080
4081   static const MCPhysReg GPR[] = {
4082     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4083     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4084   };
4085   static const MCPhysReg VR[] = {
4086     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4087     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4088   };
4089
4090   const unsigned NumGPRs = array_lengthof(GPR);
4091   const unsigned NumFPRs = 13;
4092   const unsigned NumVRs = array_lengthof(VR);
4093   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4094
4095   unsigned NumBytes = LinkageSize;
4096   unsigned AvailableFPRs = NumFPRs;
4097   unsigned AvailableVRs = NumVRs;
4098
4099   for (const ISD::OutputArg& Param : Outs) {
4100     if (Param.Flags.isNest()) continue;
4101
4102     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4103                                PtrByteSize, LinkageSize, ParamAreaSize,
4104                                NumBytes, AvailableFPRs, AvailableVRs,
4105                                Subtarget.hasQPX()))
4106       return true;
4107   }
4108   return false;
4109 }
4110
4111 static bool
4112 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4113   if (CS->arg_size() != CallerFn->arg_size())
4114     return false;
4115
4116   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4117   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4118   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4119
4120   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4121     const Value* CalleeArg = *CalleeArgIter;
4122     const Value* CallerArg = &(*CallerArgIter);
4123     if (CalleeArg == CallerArg)
4124       continue;
4125
4126     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4127     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4128     //      }
4129     // 1st argument of callee is undef and has the same type as caller.
4130     if (CalleeArg->getType() == CallerArg->getType() &&
4131         isa<UndefValue>(CalleeArg))
4132       continue;
4133
4134     return false;
4135   }
4136
4137   return true;
4138 }
4139
4140 bool
4141 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4142                                     SDValue Callee,
4143                                     CallingConv::ID CalleeCC,
4144                                     ImmutableCallSite *CS,
4145                                     bool isVarArg,
4146                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4147                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4148                                     SelectionDAG& DAG) const {
4149   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4150
4151   if (DisableSCO && !TailCallOpt) return false;
4152
4153   // Variadic argument functions are not supported.
4154   if (isVarArg) return false;
4155
4156   MachineFunction &MF = DAG.getMachineFunction();
4157   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4158
4159   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4160   // the same calling convention
4161   if (CallerCC != CalleeCC) return false;
4162
4163   // SCO support C calling convention
4164   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4165     return false;
4166
4167   // Caller contains any byval parameter is not supported.
4168   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4169     return false;
4170
4171   // Callee contains any byval parameter is not supported, too.
4172   // Note: This is a quick work around, because in some cases, e.g.
4173   // caller's stack size > callee's stack size, we are still able to apply
4174   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4175   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4176     return false;
4177
4178   // No TCO/SCO on indirect call because Caller have to restore its TOC
4179   if (!isFunctionGlobalAddress(Callee) &&
4180       !isa<ExternalSymbolSDNode>(Callee))
4181     return false;
4182
4183   // Check if Callee resides in the same section, because for now, PPC64 SVR4
4184   // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4185   // section.
4186   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4187   if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4188     return false;
4189
4190   // TCO allows altering callee ABI, so we don't have to check further.
4191   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4192     return true;
4193
4194   if (DisableSCO) return false;
4195
4196   // If callee use the same argument list that caller is using, then we can
4197   // apply SCO on this case. If it is not, then we need to check if callee needs
4198   // stack for passing arguments.
4199   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4200       needStackSlotPassParameters(Subtarget, Outs)) {
4201     return false;
4202   }
4203
4204   return true;
4205 }
4206
4207 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4208 /// for tail call optimization. Targets which want to do tail call
4209 /// optimization should implement this function.
4210 bool
4211 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4212                                                      CallingConv::ID CalleeCC,
4213                                                      bool isVarArg,
4214                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4215                                                      SelectionDAG& DAG) const {
4216   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4217     return false;
4218
4219   // Variable argument functions are not supported.
4220   if (isVarArg)
4221     return false;
4222
4223   MachineFunction &MF = DAG.getMachineFunction();
4224   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4225   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4226     // Functions containing by val parameters are not supported.
4227     for (unsigned i = 0; i != Ins.size(); i++) {
4228        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4229        if (Flags.isByVal()) return false;
4230     }
4231
4232     // Non-PIC/GOT tail calls are supported.
4233     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4234       return true;
4235
4236     // At the moment we can only do local tail calls (in same module, hidden
4237     // or protected) if we are generating PIC.
4238     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4239       return G->getGlobal()->hasHiddenVisibility()
4240           || G->getGlobal()->hasProtectedVisibility();
4241   }
4242
4243   return false;
4244 }
4245
4246 /// isCallCompatibleAddress - Return the immediate to use if the specified
4247 /// 32-bit value is representable in the immediate field of a BxA instruction.
4248 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4249   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4250   if (!C) return nullptr;
4251
4252   int Addr = C->getZExtValue();
4253   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4254       SignExtend32<26>(Addr) != Addr)
4255     return nullptr;  // Top 6 bits have to be sext of immediate.
4256
4257   return DAG
4258       .getConstant(
4259           (int)C->getZExtValue() >> 2, SDLoc(Op),
4260           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4261       .getNode();
4262 }
4263
4264 namespace {
4265
4266 struct TailCallArgumentInfo {
4267   SDValue Arg;
4268   SDValue FrameIdxOp;
4269   int FrameIdx = 0;
4270
4271   TailCallArgumentInfo() = default;
4272 };
4273
4274 } // end anonymous namespace
4275
4276 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4277 static void StoreTailCallArgumentsToStackSlot(
4278     SelectionDAG &DAG, SDValue Chain,
4279     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4280     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4281   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4282     SDValue Arg = TailCallArgs[i].Arg;
4283     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4284     int FI = TailCallArgs[i].FrameIdx;
4285     // Store relative to framepointer.
4286     MemOpChains.push_back(DAG.getStore(
4287         Chain, dl, Arg, FIN,
4288         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4289   }
4290 }
4291
4292 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4293 /// the appropriate stack slot for the tail call optimized function call.
4294 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4295                                              SDValue OldRetAddr, SDValue OldFP,
4296                                              int SPDiff, const SDLoc &dl) {
4297   if (SPDiff) {
4298     // Calculate the new stack slot for the return address.
4299     MachineFunction &MF = DAG.getMachineFunction();
4300     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4301     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4302     bool isPPC64 = Subtarget.isPPC64();
4303     int SlotSize = isPPC64 ? 8 : 4;
4304     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4305     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4306                                                          NewRetAddrLoc, true);
4307     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4308     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4309     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4310                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4311
4312     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4313     // slot as the FP is never overwritten.
4314     if (Subtarget.isDarwinABI()) {
4315       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4316       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4317                                                          true);
4318       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4319       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4320                            MachinePointerInfo::getFixedStack(
4321                                DAG.getMachineFunction(), NewFPIdx));
4322     }
4323   }
4324   return Chain;
4325 }
4326
4327 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4328 /// the position of the argument.
4329 static void
4330 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4331                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4332                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4333   int Offset = ArgOffset + SPDiff;
4334   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4335   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4336   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4337   SDValue FIN = DAG.getFrameIndex(FI, VT);
4338   TailCallArgumentInfo Info;
4339   Info.Arg = Arg;
4340   Info.FrameIdxOp = FIN;
4341   Info.FrameIdx = FI;
4342   TailCallArguments.push_back(Info);
4343 }
4344
4345 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4346 /// stack slot. Returns the chain as result and the loaded frame pointers in
4347 /// LROpOut/FPOpout. Used when tail calling.
4348 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4349     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4350     SDValue &FPOpOut, const SDLoc &dl) const {
4351   if (SPDiff) {
4352     // Load the LR and FP stack slot for later adjusting.
4353     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4354     LROpOut = getReturnAddrFrameIndex(DAG);
4355     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4356     Chain = SDValue(LROpOut.getNode(), 1);
4357
4358     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4359     // slot as the FP is never overwritten.
4360     if (Subtarget.isDarwinABI()) {
4361       FPOpOut = getFramePointerFrameIndex(DAG);
4362       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4363       Chain = SDValue(FPOpOut.getNode(), 1);
4364     }
4365   }
4366   return Chain;
4367 }
4368
4369 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4370 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4371 /// specified by the specific parameter attribute. The copy will be passed as
4372 /// a byval function parameter.
4373 /// Sometimes what we are copying is the end of a larger object, the part that
4374 /// does not fit in registers.
4375 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4376                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4377                                          SelectionDAG &DAG, const SDLoc &dl) {
4378   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4379   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4380                        false, false, false, MachinePointerInfo(),
4381                        MachinePointerInfo());
4382 }
4383
4384 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4385 /// tail calls.
4386 static void LowerMemOpCallTo(
4387     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4388     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4389     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4390     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4391   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4392   if (!isTailCall) {
4393     if (isVector) {
4394       SDValue StackPtr;
4395       if (isPPC64)
4396         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4397       else
4398         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4399       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4400                            DAG.getConstant(ArgOffset, dl, PtrVT));
4401     }
4402     MemOpChains.push_back(
4403         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4404     // Calculate and remember argument location.
4405   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4406                                   TailCallArguments);
4407 }
4408
4409 static void
4410 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4411                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4412                 SDValue FPOp,
4413                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4414   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4415   // might overwrite each other in case of tail call optimization.
4416   SmallVector<SDValue, 8> MemOpChains2;
4417   // Do not flag preceding copytoreg stuff together with the following stuff.
4418   InFlag = SDValue();
4419   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4420                                     MemOpChains2, dl);
4421   if (!MemOpChains2.empty())
4422     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4423
4424   // Store the return address to the appropriate stack slot.
4425   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4426
4427   // Emit callseq_end just before tailcall node.
4428   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4429                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4430   InFlag = Chain.getValue(1);
4431 }
4432
4433 // Is this global address that of a function that can be called by name? (as
4434 // opposed to something that must hold a descriptor for an indirect call).
4435 static bool isFunctionGlobalAddress(SDValue Callee) {
4436   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4437     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4438         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4439       return false;
4440
4441     return G->getGlobal()->getValueType()->isFunctionTy();
4442   }
4443
4444   return false;
4445 }
4446
4447 static unsigned
4448 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4449             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4450             bool isPatchPoint, bool hasNest,
4451             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4452             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4453             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4454   bool isPPC64 = Subtarget.isPPC64();
4455   bool isSVR4ABI = Subtarget.isSVR4ABI();
4456   bool isELFv2ABI = Subtarget.isELFv2ABI();
4457
4458   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4459   NodeTys.push_back(MVT::Other);   // Returns a chain
4460   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4461
4462   unsigned CallOpc = PPCISD::CALL;
4463
4464   bool needIndirectCall = true;
4465   if (!isSVR4ABI || !isPPC64)
4466     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4467       // If this is an absolute destination address, use the munged value.
4468       Callee = SDValue(Dest, 0);
4469       needIndirectCall = false;
4470     }
4471
4472   // PC-relative references to external symbols should go through $stub, unless
4473   // we're building with the leopard linker or later, which automatically
4474   // synthesizes these stubs.
4475   const TargetMachine &TM = DAG.getTarget();
4476   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4477   const GlobalValue *GV = nullptr;
4478   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4479     GV = G->getGlobal();
4480   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4481   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4482
4483   if (isFunctionGlobalAddress(Callee)) {
4484     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4485     // A call to a TLS address is actually an indirect call to a
4486     // thread-specific pointer.
4487     unsigned OpFlags = 0;
4488     if (UsePlt)
4489       OpFlags = PPCII::MO_PLT;
4490
4491     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4492     // every direct call is) turn it into a TargetGlobalAddress /
4493     // TargetExternalSymbol node so that legalize doesn't hack it.
4494     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4495                                         Callee.getValueType(), 0, OpFlags);
4496     needIndirectCall = false;
4497   }
4498
4499   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4500     unsigned char OpFlags = 0;
4501
4502     if (UsePlt)
4503       OpFlags = PPCII::MO_PLT;
4504
4505     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4506                                          OpFlags);
4507     needIndirectCall = false;
4508   }
4509
4510   if (isPatchPoint) {
4511     // We'll form an invalid direct call when lowering a patchpoint; the full
4512     // sequence for an indirect call is complicated, and many of the
4513     // instructions introduced might have side effects (and, thus, can't be
4514     // removed later). The call itself will be removed as soon as the
4515     // argument/return lowering is complete, so the fact that it has the wrong
4516     // kind of operands should not really matter.
4517     needIndirectCall = false;
4518   }
4519
4520   if (needIndirectCall) {
4521     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4522     // to do the call, we can't use PPCISD::CALL.
4523     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4524
4525     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4526       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4527       // entry point, but to the function descriptor (the function entry point
4528       // address is part of the function descriptor though).
4529       // The function descriptor is a three doubleword structure with the
4530       // following fields: function entry point, TOC base address and
4531       // environment pointer.
4532       // Thus for a call through a function pointer, the following actions need
4533       // to be performed:
4534       //   1. Save the TOC of the caller in the TOC save area of its stack
4535       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4536       //   2. Load the address of the function entry point from the function
4537       //      descriptor.
4538       //   3. Load the TOC of the callee from the function descriptor into r2.
4539       //   4. Load the environment pointer from the function descriptor into
4540       //      r11.
4541       //   5. Branch to the function entry point address.
4542       //   6. On return of the callee, the TOC of the caller needs to be
4543       //      restored (this is done in FinishCall()).
4544       //
4545       // The loads are scheduled at the beginning of the call sequence, and the
4546       // register copies are flagged together to ensure that no other
4547       // operations can be scheduled in between. E.g. without flagging the
4548       // copies together, a TOC access in the caller could be scheduled between
4549       // the assignment of the callee TOC and the branch to the callee, which
4550       // results in the TOC access going through the TOC of the callee instead
4551       // of going through the TOC of the caller, which leads to incorrect code.
4552
4553       // Load the address of the function entry point from the function
4554       // descriptor.
4555       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4556       if (LDChain.getValueType() == MVT::Glue)
4557         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4558
4559       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4560                           ? (MachineMemOperand::MODereferenceable |
4561                              MachineMemOperand::MOInvariant)
4562                           : MachineMemOperand::MONone;
4563
4564       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4565       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4566                                         /* Alignment = */ 8, MMOFlags);
4567
4568       // Load environment pointer into r11.
4569       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4570       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4571       SDValue LoadEnvPtr =
4572           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4573                       /* Alignment = */ 8, MMOFlags);
4574
4575       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4576       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4577       SDValue TOCPtr =
4578           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4579                       /* Alignment = */ 8, MMOFlags);
4580
4581       setUsesTOCBasePtr(DAG);
4582       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4583                                         InFlag);
4584       Chain = TOCVal.getValue(0);
4585       InFlag = TOCVal.getValue(1);
4586
4587       // If the function call has an explicit 'nest' parameter, it takes the
4588       // place of the environment pointer.
4589       if (!hasNest) {
4590         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4591                                           InFlag);
4592
4593         Chain = EnvVal.getValue(0);
4594         InFlag = EnvVal.getValue(1);
4595       }
4596
4597       MTCTROps[0] = Chain;
4598       MTCTROps[1] = LoadFuncPtr;
4599       MTCTROps[2] = InFlag;
4600     }
4601
4602     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4603                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4604     InFlag = Chain.getValue(1);
4605
4606     NodeTys.clear();
4607     NodeTys.push_back(MVT::Other);
4608     NodeTys.push_back(MVT::Glue);
4609     Ops.push_back(Chain);
4610     CallOpc = PPCISD::BCTRL;
4611     Callee.setNode(nullptr);
4612     // Add use of X11 (holding environment pointer)
4613     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4614       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4615     // Add CTR register as callee so a bctr can be emitted later.
4616     if (isTailCall)
4617       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4618   }
4619
4620   // If this is a direct call, pass the chain and the callee.
4621   if (Callee.getNode()) {
4622     Ops.push_back(Chain);
4623     Ops.push_back(Callee);
4624   }
4625   // If this is a tail call add stack pointer delta.
4626   if (isTailCall)
4627     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4628
4629   // Add argument registers to the end of the list so that they are known live
4630   // into the call.
4631   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4632     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4633                                   RegsToPass[i].second.getValueType()));
4634
4635   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4636   // into the call.
4637   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4638     setUsesTOCBasePtr(DAG);
4639     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4640   }
4641
4642   return CallOpc;
4643 }
4644
4645 SDValue PPCTargetLowering::LowerCallResult(
4646     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4647     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4648     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4649   SmallVector<CCValAssign, 16> RVLocs;
4650   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4651                     *DAG.getContext());
4652   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4653
4654   // Copy all of the result registers out of their specified physreg.
4655   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4656     CCValAssign &VA = RVLocs[i];
4657     assert(VA.isRegLoc() && "Can only return in registers!");
4658
4659     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4660                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4661     Chain = Val.getValue(1);
4662     InFlag = Val.getValue(2);
4663
4664     switch (VA.getLocInfo()) {
4665     default: llvm_unreachable("Unknown loc info!");
4666     case CCValAssign::Full: break;
4667     case CCValAssign::AExt:
4668       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4669       break;
4670     case CCValAssign::ZExt:
4671       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4672                         DAG.getValueType(VA.getValVT()));
4673       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4674       break;
4675     case CCValAssign::SExt:
4676       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4677                         DAG.getValueType(VA.getValVT()));
4678       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4679       break;
4680     }
4681
4682     InVals.push_back(Val);
4683   }
4684
4685   return Chain;
4686 }
4687
4688 SDValue PPCTargetLowering::FinishCall(
4689     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4690     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4691     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4692     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4693     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4694     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4695   std::vector<EVT> NodeTys;
4696   SmallVector<SDValue, 8> Ops;
4697   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4698                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4699                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4700
4701   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4702   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4703     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4704
4705   // When performing tail call optimization the callee pops its arguments off
4706   // the stack. Account for this here so these bytes can be pushed back on in
4707   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4708   int BytesCalleePops =
4709     (CallConv == CallingConv::Fast &&
4710      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4711
4712   // Add a register mask operand representing the call-preserved registers.
4713   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4714   const uint32_t *Mask =
4715       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4716   assert(Mask && "Missing call preserved mask for calling convention");
4717   Ops.push_back(DAG.getRegisterMask(Mask));
4718
4719   if (InFlag.getNode())
4720     Ops.push_back(InFlag);
4721
4722   // Emit tail call.
4723   if (isTailCall) {
4724     assert(((Callee.getOpcode() == ISD::Register &&
4725              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4726             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4727             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4728             isa<ConstantSDNode>(Callee)) &&
4729     "Expecting an global address, external symbol, absolute value or register");
4730
4731     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4732     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4733   }
4734
4735   // Add a NOP immediately after the branch instruction when using the 64-bit
4736   // SVR4 ABI. At link time, if caller and callee are in a different module and
4737   // thus have a different TOC, the call will be replaced with a call to a stub
4738   // function which saves the current TOC, loads the TOC of the callee and
4739   // branches to the callee. The NOP will be replaced with a load instruction
4740   // which restores the TOC of the caller from the TOC save slot of the current
4741   // stack frame. If caller and callee belong to the same module (and have the
4742   // same TOC), the NOP will remain unchanged.
4743
4744   MachineFunction &MF = DAG.getMachineFunction();
4745   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4746       !isPatchPoint) {
4747     if (CallOpc == PPCISD::BCTRL) {
4748       // This is a call through a function pointer.
4749       // Restore the caller TOC from the save area into R2.
4750       // See PrepareCall() for more information about calls through function
4751       // pointers in the 64-bit SVR4 ABI.
4752       // We are using a target-specific load with r2 hard coded, because the
4753       // result of a target-independent load would never go directly into r2,
4754       // since r2 is a reserved register (which prevents the register allocator
4755       // from allocating it), resulting in an additional register being
4756       // allocated and an unnecessary move instruction being generated.
4757       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4758
4759       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4760       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4761       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4762       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4763       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4764
4765       // The address needs to go after the chain input but before the flag (or
4766       // any other variadic arguments).
4767       Ops.insert(std::next(Ops.begin()), AddTOC);
4768     } else if (CallOpc == PPCISD::CALL &&
4769       !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4770       // Otherwise insert NOP for non-local calls.
4771       CallOpc = PPCISD::CALL_NOP;
4772     }
4773   }
4774
4775   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4776   InFlag = Chain.getValue(1);
4777
4778   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4779                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4780                              InFlag, dl);
4781   if (!Ins.empty())
4782     InFlag = Chain.getValue(1);
4783
4784   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4785                          Ins, dl, DAG, InVals);
4786 }
4787
4788 SDValue
4789 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4790                              SmallVectorImpl<SDValue> &InVals) const {
4791   SelectionDAG &DAG                     = CLI.DAG;
4792   SDLoc &dl                             = CLI.DL;
4793   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4794   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4795   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4796   SDValue Chain                         = CLI.Chain;
4797   SDValue Callee                        = CLI.Callee;
4798   bool &isTailCall                      = CLI.IsTailCall;
4799   CallingConv::ID CallConv              = CLI.CallConv;
4800   bool isVarArg                         = CLI.IsVarArg;
4801   bool isPatchPoint                     = CLI.IsPatchPoint;
4802   ImmutableCallSite *CS                 = CLI.CS;
4803
4804   if (isTailCall) {
4805     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4806       isTailCall = false;
4807     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4808       isTailCall =
4809         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4810                                                  isVarArg, Outs, Ins, DAG);
4811     else
4812       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4813                                                      Ins, DAG);
4814     if (isTailCall) {
4815       ++NumTailCalls;
4816       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4817         ++NumSiblingCalls;
4818
4819       assert(isa<GlobalAddressSDNode>(Callee) &&
4820              "Callee should be an llvm::Function object.");
4821       DEBUG(
4822         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4823         const unsigned Width = 80 - strlen("TCO caller: ")
4824                                   - strlen(", callee linkage: 0, 0");
4825         dbgs() << "TCO caller: "
4826                << left_justify(DAG.getMachineFunction().getName(), Width)
4827                << ", callee linkage: "
4828                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4829       );
4830     }
4831   }
4832
4833   if (!isTailCall && CS && CS->isMustTailCall())
4834     report_fatal_error("failed to perform tail call elimination on a call "
4835                        "site marked musttail");
4836
4837   // When long calls (i.e. indirect calls) are always used, calls are always
4838   // made via function pointer. If we have a function name, first translate it
4839   // into a pointer.
4840   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4841       !isTailCall)
4842     Callee = LowerGlobalAddress(Callee, DAG);
4843
4844   if (Subtarget.isSVR4ABI()) {
4845     if (Subtarget.isPPC64())
4846       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4847                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4848                               dl, DAG, InVals, CS);
4849     else
4850       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4851                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4852                               dl, DAG, InVals, CS);
4853   }
4854
4855   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4856                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4857                           dl, DAG, InVals, CS);
4858 }
4859
4860 SDValue PPCTargetLowering::LowerCall_32SVR4(
4861     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4862     bool isTailCall, bool isPatchPoint,
4863     const SmallVectorImpl<ISD::OutputArg> &Outs,
4864     const SmallVectorImpl<SDValue> &OutVals,
4865     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4866     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4867     ImmutableCallSite *CS) const {
4868   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4869   // of the 32-bit SVR4 ABI stack frame layout.
4870
4871   assert((CallConv == CallingConv::C ||
4872           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4873
4874   unsigned PtrByteSize = 4;
4875
4876   MachineFunction &MF = DAG.getMachineFunction();
4877
4878   // Mark this function as potentially containing a function that contains a
4879   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4880   // and restoring the callers stack pointer in this functions epilog. This is
4881   // done because by tail calling the called function might overwrite the value
4882   // in this function's (MF) stack pointer stack slot 0(SP).
4883   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4884       CallConv == CallingConv::Fast)
4885     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4886
4887   // Count how many bytes are to be pushed on the stack, including the linkage
4888   // area, parameter list area and the part of the local variable space which
4889   // contains copies of aggregates which are passed by value.
4890
4891   // Assign locations to all of the outgoing arguments.
4892   SmallVector<CCValAssign, 16> ArgLocs;
4893   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4894
4895   // Reserve space for the linkage area on the stack.
4896   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4897                        PtrByteSize);
4898   if (useSoftFloat())
4899     CCInfo.PreAnalyzeCallOperands(Outs);
4900
4901   if (isVarArg) {
4902     // Handle fixed and variable vector arguments differently.
4903     // Fixed vector arguments go into registers as long as registers are
4904     // available. Variable vector arguments always go into memory.
4905     unsigned NumArgs = Outs.size();
4906
4907     for (unsigned i = 0; i != NumArgs; ++i) {
4908       MVT ArgVT = Outs[i].VT;
4909       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4910       bool Result;
4911
4912       if (Outs[i].IsFixed) {
4913         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4914                                CCInfo);
4915       } else {
4916         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4917                                       ArgFlags, CCInfo);
4918       }
4919
4920       if (Result) {
4921 #ifndef NDEBUG
4922         errs() << "Call operand #" << i << " has unhandled type "
4923              << EVT(ArgVT).getEVTString() << "\n";
4924 #endif
4925         llvm_unreachable(nullptr);
4926       }
4927     }
4928   } else {
4929     // All arguments are treated the same.
4930     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4931   }
4932   CCInfo.clearWasPPCF128();
4933
4934   // Assign locations to all of the outgoing aggregate by value arguments.
4935   SmallVector<CCValAssign, 16> ByValArgLocs;
4936   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4937
4938   // Reserve stack space for the allocations in CCInfo.
4939   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4940
4941   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4942
4943   // Size of the linkage area, parameter list area and the part of the local
4944   // space variable where copies of aggregates which are passed by value are
4945   // stored.
4946   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4947
4948   // Calculate by how many bytes the stack has to be adjusted in case of tail
4949   // call optimization.
4950   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4951
4952   // Adjust the stack pointer for the new arguments...
4953   // These operations are automatically eliminated by the prolog/epilog pass
4954   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4955                                dl);
4956   SDValue CallSeqStart = Chain;
4957
4958   // Load the return address and frame pointer so it can be moved somewhere else
4959   // later.
4960   SDValue LROp, FPOp;
4961   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4962
4963   // Set up a copy of the stack pointer for use loading and storing any
4964   // arguments that may not fit in the registers available for argument
4965   // passing.
4966   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4967
4968   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4969   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4970   SmallVector<SDValue, 8> MemOpChains;
4971
4972   bool seenFloatArg = false;
4973   // Walk the register/memloc assignments, inserting copies/loads.
4974   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4975        i != e;
4976        ++i) {
4977     CCValAssign &VA = ArgLocs[i];
4978     SDValue Arg = OutVals[i];
4979     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4980
4981     if (Flags.isByVal()) {
4982       // Argument is an aggregate which is passed by value, thus we need to
4983       // create a copy of it in the local variable space of the current stack
4984       // frame (which is the stack frame of the caller) and pass the address of
4985       // this copy to the callee.
4986       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4987       CCValAssign &ByValVA = ByValArgLocs[j++];
4988       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4989
4990       // Memory reserved in the local variable space of the callers stack frame.
4991       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4992
4993       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4994       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4995                            StackPtr, PtrOff);
4996
4997       // Create a copy of the argument in the local area of the current
4998       // stack frame.
4999       SDValue MemcpyCall =
5000         CreateCopyOfByValArgument(Arg, PtrOff,
5001                                   CallSeqStart.getNode()->getOperand(0),
5002                                   Flags, DAG, dl);
5003
5004       // This must go outside the CALLSEQ_START..END.
5005       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5006                            CallSeqStart.getNode()->getOperand(1),
5007                            SDLoc(MemcpyCall));
5008       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5009                              NewCallSeqStart.getNode());
5010       Chain = CallSeqStart = NewCallSeqStart;
5011
5012       // Pass the address of the aggregate copy on the stack either in a
5013       // physical register or in the parameter list area of the current stack
5014       // frame to the callee.
5015       Arg = PtrOff;
5016     }
5017
5018     if (VA.isRegLoc()) {
5019       if (Arg.getValueType() == MVT::i1)
5020         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5021
5022       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5023       // Put argument in a physical register.
5024       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5025     } else {
5026       // Put argument in the parameter list area of the current stack frame.
5027       assert(VA.isMemLoc());
5028       unsigned LocMemOffset = VA.getLocMemOffset();
5029
5030       if (!isTailCall) {
5031         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5032         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5033                              StackPtr, PtrOff);
5034
5035         MemOpChains.push_back(
5036             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5037       } else {
5038         // Calculate and remember argument location.
5039         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5040                                  TailCallArguments);
5041       }
5042     }
5043   }
5044
5045   if (!MemOpChains.empty())
5046     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5047
5048   // Build a sequence of copy-to-reg nodes chained together with token chain
5049   // and flag operands which copy the outgoing args into the appropriate regs.
5050   SDValue InFlag;
5051   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5052     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5053                              RegsToPass[i].second, InFlag);
5054     InFlag = Chain.getValue(1);
5055   }
5056
5057   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5058   // registers.
5059   if (isVarArg) {
5060     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5061     SDValue Ops[] = { Chain, InFlag };
5062
5063     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5064                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5065
5066     InFlag = Chain.getValue(1);
5067   }
5068
5069   if (isTailCall)
5070     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5071                     TailCallArguments);
5072
5073   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5074                     /* unused except on PPC64 ELFv1 */ false, DAG,
5075                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5076                     NumBytes, Ins, InVals, CS);
5077 }
5078
5079 // Copy an argument into memory, being careful to do this outside the
5080 // call sequence for the call to which the argument belongs.
5081 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5082     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5083     SelectionDAG &DAG, const SDLoc &dl) const {
5084   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5085                         CallSeqStart.getNode()->getOperand(0),
5086                         Flags, DAG, dl);
5087   // The MEMCPY must go outside the CALLSEQ_START..END.
5088   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5089                              CallSeqStart.getNode()->getOperand(1),
5090                              SDLoc(MemcpyCall));
5091   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5092                          NewCallSeqStart.getNode());
5093   return NewCallSeqStart;
5094 }
5095
5096 SDValue PPCTargetLowering::LowerCall_64SVR4(
5097     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5098     bool isTailCall, bool isPatchPoint,
5099     const SmallVectorImpl<ISD::OutputArg> &Outs,
5100     const SmallVectorImpl<SDValue> &OutVals,
5101     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5102     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5103     ImmutableCallSite *CS) const {
5104   bool isELFv2ABI = Subtarget.isELFv2ABI();
5105   bool isLittleEndian = Subtarget.isLittleEndian();
5106   unsigned NumOps = Outs.size();
5107   bool hasNest = false;
5108   bool IsSibCall = false;
5109
5110   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5111   unsigned PtrByteSize = 8;
5112
5113   MachineFunction &MF = DAG.getMachineFunction();
5114
5115   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5116     IsSibCall = true;
5117
5118   // Mark this function as potentially containing a function that contains a
5119   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5120   // and restoring the callers stack pointer in this functions epilog. This is
5121   // done because by tail calling the called function might overwrite the value
5122   // in this function's (MF) stack pointer stack slot 0(SP).
5123   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5124       CallConv == CallingConv::Fast)
5125     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5126
5127   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5128          "fastcc not supported on varargs functions");
5129
5130   // Count how many bytes are to be pushed on the stack, including the linkage
5131   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5132   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5133   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5134   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5135   unsigned NumBytes = LinkageSize;
5136   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5137   unsigned &QFPR_idx = FPR_idx;
5138
5139   static const MCPhysReg GPR[] = {
5140     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5141     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5142   };
5143   static const MCPhysReg VR[] = {
5144     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5145     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5146   };
5147
5148   const unsigned NumGPRs = array_lengthof(GPR);
5149   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5150   const unsigned NumVRs  = array_lengthof(VR);
5151   const unsigned NumQFPRs = NumFPRs;
5152
5153   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5154   // can be passed to the callee in registers.
5155   // For the fast calling convention, there is another check below.
5156   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5157   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5158   if (!HasParameterArea) {
5159     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5160     unsigned AvailableFPRs = NumFPRs;
5161     unsigned AvailableVRs = NumVRs;
5162     unsigned NumBytesTmp = NumBytes;
5163     for (unsigned i = 0; i != NumOps; ++i) {
5164       if (Outs[i].Flags.isNest()) continue;
5165       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5166                                 PtrByteSize, LinkageSize, ParamAreaSize,
5167                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5168                                 Subtarget.hasQPX()))
5169         HasParameterArea = true;
5170     }
5171   }
5172
5173   // When using the fast calling convention, we don't provide backing for
5174   // arguments that will be in registers.
5175   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5176
5177   // Add up all the space actually used.
5178   for (unsigned i = 0; i != NumOps; ++i) {
5179     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5180     EVT ArgVT = Outs[i].VT;
5181     EVT OrigVT = Outs[i].ArgVT;
5182
5183     if (Flags.isNest())
5184       continue;
5185
5186     if (CallConv == CallingConv::Fast) {
5187       if (Flags.isByVal())
5188         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5189       else
5190         switch (ArgVT.getSimpleVT().SimpleTy) {
5191         default: llvm_unreachable("Unexpected ValueType for argument!");
5192         case MVT::i1:
5193         case MVT::i32:
5194         case MVT::i64:
5195           if (++NumGPRsUsed <= NumGPRs)
5196             continue;
5197           break;
5198         case MVT::v4i32:
5199         case MVT::v8i16:
5200         case MVT::v16i8:
5201         case MVT::v2f64:
5202         case MVT::v2i64:
5203         case MVT::v1i128:
5204           if (++NumVRsUsed <= NumVRs)
5205             continue;
5206           break;
5207         case MVT::v4f32:
5208           // When using QPX, this is handled like a FP register, otherwise, it
5209           // is an Altivec register.
5210           if (Subtarget.hasQPX()) {
5211             if (++NumFPRsUsed <= NumFPRs)
5212               continue;
5213           } else {
5214             if (++NumVRsUsed <= NumVRs)
5215               continue;
5216           }
5217           break;
5218         case MVT::f32:
5219         case MVT::f64:
5220         case MVT::v4f64: // QPX
5221         case MVT::v4i1:  // QPX
5222           if (++NumFPRsUsed <= NumFPRs)
5223             continue;
5224           break;
5225         }
5226     }
5227
5228     /* Respect alignment of argument on the stack.  */
5229     unsigned Align =
5230       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5231     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5232
5233     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5234     if (Flags.isInConsecutiveRegsLast())
5235       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5236   }
5237
5238   unsigned NumBytesActuallyUsed = NumBytes;
5239
5240   // In the old ELFv1 ABI,
5241   // the prolog code of the callee may store up to 8 GPR argument registers to
5242   // the stack, allowing va_start to index over them in memory if its varargs.
5243   // Because we cannot tell if this is needed on the caller side, we have to
5244   // conservatively assume that it is needed.  As such, make sure we have at
5245   // least enough stack space for the caller to store the 8 GPRs.
5246   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5247   // really requires memory operands, e.g. a vararg function.
5248   if (HasParameterArea)
5249     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5250   else
5251     NumBytes = LinkageSize;
5252
5253   // Tail call needs the stack to be aligned.
5254   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5255       CallConv == CallingConv::Fast)
5256     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5257
5258   int SPDiff = 0;
5259
5260   // Calculate by how many bytes the stack has to be adjusted in case of tail
5261   // call optimization.
5262   if (!IsSibCall)
5263     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5264
5265   // To protect arguments on the stack from being clobbered in a tail call,
5266   // force all the loads to happen before doing any other lowering.
5267   if (isTailCall)
5268     Chain = DAG.getStackArgumentTokenFactor(Chain);
5269
5270   // Adjust the stack pointer for the new arguments...
5271   // These operations are automatically eliminated by the prolog/epilog pass
5272   if (!IsSibCall)
5273     Chain = DAG.getCALLSEQ_START(Chain,
5274                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5275   SDValue CallSeqStart = Chain;
5276
5277   // Load the return address and frame pointer so it can be move somewhere else
5278   // later.
5279   SDValue LROp, FPOp;
5280   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5281
5282   // Set up a copy of the stack pointer for use loading and storing any
5283   // arguments that may not fit in the registers available for argument
5284   // passing.
5285   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5286
5287   // Figure out which arguments are going to go in registers, and which in
5288   // memory.  Also, if this is a vararg function, floating point operations
5289   // must be stored to our stack, and loaded into integer regs as well, if
5290   // any integer regs are available for argument passing.
5291   unsigned ArgOffset = LinkageSize;
5292
5293   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5294   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5295
5296   SmallVector<SDValue, 8> MemOpChains;
5297   for (unsigned i = 0; i != NumOps; ++i) {
5298     SDValue Arg = OutVals[i];
5299     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5300     EVT ArgVT = Outs[i].VT;
5301     EVT OrigVT = Outs[i].ArgVT;
5302
5303     // PtrOff will be used to store the current argument to the stack if a
5304     // register cannot be found for it.
5305     SDValue PtrOff;
5306
5307     // We re-align the argument offset for each argument, except when using the
5308     // fast calling convention, when we need to make sure we do that only when
5309     // we'll actually use a stack slot.
5310     auto ComputePtrOff = [&]() {
5311       /* Respect alignment of argument on the stack.  */
5312       unsigned Align =
5313         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5314       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5315
5316       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5317
5318       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5319     };
5320
5321     if (CallConv != CallingConv::Fast) {
5322       ComputePtrOff();
5323
5324       /* Compute GPR index associated with argument offset.  */
5325       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5326       GPR_idx = std::min(GPR_idx, NumGPRs);
5327     }
5328
5329     // Promote integers to 64-bit values.
5330     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5331       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5332       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5333       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5334     }
5335
5336     // FIXME memcpy is used way more than necessary.  Correctness first.
5337     // Note: "by value" is code for passing a structure by value, not
5338     // basic types.
5339     if (Flags.isByVal()) {
5340       // Note: Size includes alignment padding, so
5341       //   struct x { short a; char b; }
5342       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5343       // These are the proper values we need for right-justifying the
5344       // aggregate in a parameter register.
5345       unsigned Size = Flags.getByValSize();
5346
5347       // An empty aggregate parameter takes up no storage and no
5348       // registers.
5349       if (Size == 0)
5350         continue;
5351
5352       if (CallConv == CallingConv::Fast)
5353         ComputePtrOff();
5354
5355       // All aggregates smaller than 8 bytes must be passed right-justified.
5356       if (Size==1 || Size==2 || Size==4) {
5357         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5358         if (GPR_idx != NumGPRs) {
5359           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5360                                         MachinePointerInfo(), VT);
5361           MemOpChains.push_back(Load.getValue(1));
5362           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5363
5364           ArgOffset += PtrByteSize;
5365           continue;
5366         }
5367       }
5368
5369       if (GPR_idx == NumGPRs && Size < 8) {
5370         SDValue AddPtr = PtrOff;
5371         if (!isLittleEndian) {
5372           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5373                                           PtrOff.getValueType());
5374           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5375         }
5376         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5377                                                           CallSeqStart,
5378                                                           Flags, DAG, dl);
5379         ArgOffset += PtrByteSize;
5380         continue;
5381       }
5382       // Copy entire object into memory.  There are cases where gcc-generated
5383       // code assumes it is there, even if it could be put entirely into
5384       // registers.  (This is not what the doc says.)
5385
5386       // FIXME: The above statement is likely due to a misunderstanding of the
5387       // documents.  All arguments must be copied into the parameter area BY
5388       // THE CALLEE in the event that the callee takes the address of any
5389       // formal argument.  That has not yet been implemented.  However, it is
5390       // reasonable to use the stack area as a staging area for the register
5391       // load.
5392
5393       // Skip this for small aggregates, as we will use the same slot for a
5394       // right-justified copy, below.
5395       if (Size >= 8)
5396         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5397                                                           CallSeqStart,
5398                                                           Flags, DAG, dl);
5399
5400       // When a register is available, pass a small aggregate right-justified.
5401       if (Size < 8 && GPR_idx != NumGPRs) {
5402         // The easiest way to get this right-justified in a register
5403         // is to copy the structure into the rightmost portion of a
5404         // local variable slot, then load the whole slot into the
5405         // register.
5406         // FIXME: The memcpy seems to produce pretty awful code for
5407         // small aggregates, particularly for packed ones.
5408         // FIXME: It would be preferable to use the slot in the
5409         // parameter save area instead of a new local variable.
5410         SDValue AddPtr = PtrOff;
5411         if (!isLittleEndian) {
5412           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5413           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5414         }
5415         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5416                                                           CallSeqStart,
5417                                                           Flags, DAG, dl);
5418
5419         // Load the slot into the register.
5420         SDValue Load =
5421             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5422         MemOpChains.push_back(Load.getValue(1));
5423         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5424
5425         // Done with this argument.
5426         ArgOffset += PtrByteSize;
5427         continue;
5428       }
5429
5430       // For aggregates larger than PtrByteSize, copy the pieces of the
5431       // object that fit into registers from the parameter save area.
5432       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5433         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5434         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5435         if (GPR_idx != NumGPRs) {
5436           SDValue Load =
5437               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5438           MemOpChains.push_back(Load.getValue(1));
5439           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5440           ArgOffset += PtrByteSize;
5441         } else {
5442           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5443           break;
5444         }
5445       }
5446       continue;
5447     }
5448
5449     switch (Arg.getSimpleValueType().SimpleTy) {
5450     default: llvm_unreachable("Unexpected ValueType for argument!");
5451     case MVT::i1:
5452     case MVT::i32:
5453     case MVT::i64:
5454       if (Flags.isNest()) {
5455         // The 'nest' parameter, if any, is passed in R11.
5456         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5457         hasNest = true;
5458         break;
5459       }
5460
5461       // These can be scalar arguments or elements of an integer array type
5462       // passed directly.  Clang may use those instead of "byval" aggregate
5463       // types to avoid forcing arguments to memory unnecessarily.
5464       if (GPR_idx != NumGPRs) {
5465         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5466       } else {
5467         if (CallConv == CallingConv::Fast)
5468           ComputePtrOff();
5469
5470         assert(HasParameterArea &&
5471                "Parameter area must exist to pass an argument in memory.");
5472         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5473                          true, isTailCall, false, MemOpChains,
5474                          TailCallArguments, dl);
5475         if (CallConv == CallingConv::Fast)
5476           ArgOffset += PtrByteSize;
5477       }
5478       if (CallConv != CallingConv::Fast)
5479         ArgOffset += PtrByteSize;
5480       break;
5481     case MVT::f32:
5482     case MVT::f64: {
5483       // These can be scalar arguments or elements of a float array type
5484       // passed directly.  The latter are used to implement ELFv2 homogenous
5485       // float aggregates.
5486
5487       // Named arguments go into FPRs first, and once they overflow, the
5488       // remaining arguments go into GPRs and then the parameter save area.
5489       // Unnamed arguments for vararg functions always go to GPRs and
5490       // then the parameter save area.  For now, put all arguments to vararg
5491       // routines always in both locations (FPR *and* GPR or stack slot).
5492       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5493       bool NeededLoad = false;
5494
5495       // First load the argument into the next available FPR.
5496       if (FPR_idx != NumFPRs)
5497         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5498
5499       // Next, load the argument into GPR or stack slot if needed.
5500       if (!NeedGPROrStack)
5501         ;
5502       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5503         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5504         // once we support fp <-> gpr moves.
5505
5506         // In the non-vararg case, this can only ever happen in the
5507         // presence of f32 array types, since otherwise we never run
5508         // out of FPRs before running out of GPRs.
5509         SDValue ArgVal;
5510
5511         // Double values are always passed in a single GPR.
5512         if (Arg.getValueType() != MVT::f32) {
5513           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5514
5515         // Non-array float values are extended and passed in a GPR.
5516         } else if (!Flags.isInConsecutiveRegs()) {
5517           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5518           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5519
5520         // If we have an array of floats, we collect every odd element
5521         // together with its predecessor into one GPR.
5522         } else if (ArgOffset % PtrByteSize != 0) {
5523           SDValue Lo, Hi;
5524           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5525           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5526           if (!isLittleEndian)
5527             std::swap(Lo, Hi);
5528           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5529
5530         // The final element, if even, goes into the first half of a GPR.
5531         } else if (Flags.isInConsecutiveRegsLast()) {
5532           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5533           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5534           if (!isLittleEndian)
5535             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5536                                  DAG.getConstant(32, dl, MVT::i32));
5537
5538         // Non-final even elements are skipped; they will be handled
5539         // together the with subsequent argument on the next go-around.
5540         } else
5541           ArgVal = SDValue();
5542
5543         if (ArgVal.getNode())
5544           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5545       } else {
5546         if (CallConv == CallingConv::Fast)
5547           ComputePtrOff();
5548
5549         // Single-precision floating-point values are mapped to the
5550         // second (rightmost) word of the stack doubleword.
5551         if (Arg.getValueType() == MVT::f32 &&
5552             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5553           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5554           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5555         }
5556
5557         assert(HasParameterArea &&
5558                "Parameter area must exist to pass an argument in memory.");
5559         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5560                          true, isTailCall, false, MemOpChains,
5561                          TailCallArguments, dl);
5562
5563         NeededLoad = true;
5564       }
5565       // When passing an array of floats, the array occupies consecutive
5566       // space in the argument area; only round up to the next doubleword
5567       // at the end of the array.  Otherwise, each float takes 8 bytes.
5568       if (CallConv != CallingConv::Fast || NeededLoad) {
5569         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5570                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5571         if (Flags.isInConsecutiveRegsLast())
5572           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5573       }
5574       break;
5575     }
5576     case MVT::v4f32:
5577     case MVT::v4i32:
5578     case MVT::v8i16:
5579     case MVT::v16i8:
5580     case MVT::v2f64:
5581     case MVT::v2i64:
5582     case MVT::v1i128:
5583       if (!Subtarget.hasQPX()) {
5584       // These can be scalar arguments or elements of a vector array type
5585       // passed directly.  The latter are used to implement ELFv2 homogenous
5586       // vector aggregates.
5587
5588       // For a varargs call, named arguments go into VRs or on the stack as
5589       // usual; unnamed arguments always go to the stack or the corresponding
5590       // GPRs when within range.  For now, we always put the value in both
5591       // locations (or even all three).
5592       if (isVarArg) {
5593         assert(HasParameterArea &&
5594                "Parameter area must exist if we have a varargs call.");
5595         // We could elide this store in the case where the object fits
5596         // entirely in R registers.  Maybe later.
5597         SDValue Store =
5598             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5599         MemOpChains.push_back(Store);
5600         if (VR_idx != NumVRs) {
5601           SDValue Load =
5602               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5603           MemOpChains.push_back(Load.getValue(1));
5604           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5605         }
5606         ArgOffset += 16;
5607         for (unsigned i=0; i<16; i+=PtrByteSize) {
5608           if (GPR_idx == NumGPRs)
5609             break;
5610           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5611                                    DAG.getConstant(i, dl, PtrVT));
5612           SDValue Load =
5613               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5614           MemOpChains.push_back(Load.getValue(1));
5615           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5616         }
5617         break;
5618       }
5619
5620       // Non-varargs Altivec params go into VRs or on the stack.
5621       if (VR_idx != NumVRs) {
5622         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5623       } else {
5624         if (CallConv == CallingConv::Fast)
5625           ComputePtrOff();
5626
5627         assert(HasParameterArea &&
5628                "Parameter area must exist to pass an argument in memory.");
5629         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5630                          true, isTailCall, true, MemOpChains,
5631                          TailCallArguments, dl);
5632         if (CallConv == CallingConv::Fast)
5633           ArgOffset += 16;
5634       }
5635
5636       if (CallConv != CallingConv::Fast)
5637         ArgOffset += 16;
5638       break;
5639       } // not QPX
5640
5641       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5642              "Invalid QPX parameter type");
5643
5644       /* fall through */
5645     case MVT::v4f64:
5646     case MVT::v4i1: {
5647       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5648       if (isVarArg) {
5649         assert(HasParameterArea &&
5650                "Parameter area must exist if we have a varargs call.");
5651         // We could elide this store in the case where the object fits
5652         // entirely in R registers.  Maybe later.
5653         SDValue Store =
5654             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5655         MemOpChains.push_back(Store);
5656         if (QFPR_idx != NumQFPRs) {
5657           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5658                                      PtrOff, MachinePointerInfo());
5659           MemOpChains.push_back(Load.getValue(1));
5660           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5661         }
5662         ArgOffset += (IsF32 ? 16 : 32);
5663         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5664           if (GPR_idx == NumGPRs)
5665             break;
5666           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5667                                    DAG.getConstant(i, dl, PtrVT));
5668           SDValue Load =
5669               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5670           MemOpChains.push_back(Load.getValue(1));
5671           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5672         }
5673         break;
5674       }
5675
5676       // Non-varargs QPX params go into registers or on the stack.
5677       if (QFPR_idx != NumQFPRs) {
5678         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5679       } else {
5680         if (CallConv == CallingConv::Fast)
5681           ComputePtrOff();
5682
5683         assert(HasParameterArea &&
5684                "Parameter area must exist to pass an argument in memory.");
5685         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5686                          true, isTailCall, true, MemOpChains,
5687                          TailCallArguments, dl);
5688         if (CallConv == CallingConv::Fast)
5689           ArgOffset += (IsF32 ? 16 : 32);
5690       }
5691
5692       if (CallConv != CallingConv::Fast)
5693         ArgOffset += (IsF32 ? 16 : 32);
5694       break;
5695       }
5696     }
5697   }
5698
5699   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5700          "mismatch in size of parameter area");
5701   (void)NumBytesActuallyUsed;
5702
5703   if (!MemOpChains.empty())
5704     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5705
5706   // Check if this is an indirect call (MTCTR/BCTRL).
5707   // See PrepareCall() for more information about calls through function
5708   // pointers in the 64-bit SVR4 ABI.
5709   if (!isTailCall && !isPatchPoint &&
5710       !isFunctionGlobalAddress(Callee) &&
5711       !isa<ExternalSymbolSDNode>(Callee)) {
5712     // Load r2 into a virtual register and store it to the TOC save area.
5713     setUsesTOCBasePtr(DAG);
5714     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5715     // TOC save area offset.
5716     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5717     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5718     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5719     Chain = DAG.getStore(
5720         Val.getValue(1), dl, Val, AddPtr,
5721         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5722     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5723     // This does not mean the MTCTR instruction must use R12; it's easier
5724     // to model this as an extra parameter, so do that.
5725     if (isELFv2ABI && !isPatchPoint)
5726       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5727   }
5728
5729   // Build a sequence of copy-to-reg nodes chained together with token chain
5730   // and flag operands which copy the outgoing args into the appropriate regs.
5731   SDValue InFlag;
5732   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5733     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5734                              RegsToPass[i].second, InFlag);
5735     InFlag = Chain.getValue(1);
5736   }
5737
5738   if (isTailCall && !IsSibCall)
5739     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5740                     TailCallArguments);
5741
5742   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5743                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5744                     SPDiff, NumBytes, Ins, InVals, CS);
5745 }
5746
5747 SDValue PPCTargetLowering::LowerCall_Darwin(
5748     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5749     bool isTailCall, bool isPatchPoint,
5750     const SmallVectorImpl<ISD::OutputArg> &Outs,
5751     const SmallVectorImpl<SDValue> &OutVals,
5752     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5753     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5754     ImmutableCallSite *CS) const {
5755   unsigned NumOps = Outs.size();
5756
5757   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5758   bool isPPC64 = PtrVT == MVT::i64;
5759   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5760
5761   MachineFunction &MF = DAG.getMachineFunction();
5762
5763   // Mark this function as potentially containing a function that contains a
5764   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5765   // and restoring the callers stack pointer in this functions epilog. This is
5766   // done because by tail calling the called function might overwrite the value
5767   // in this function's (MF) stack pointer stack slot 0(SP).
5768   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5769       CallConv == CallingConv::Fast)
5770     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5771
5772   // Count how many bytes are to be pushed on the stack, including the linkage
5773   // area, and parameter passing area.  We start with 24/48 bytes, which is
5774   // prereserved space for [SP][CR][LR][3 x unused].
5775   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5776   unsigned NumBytes = LinkageSize;
5777
5778   // Add up all the space actually used.
5779   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5780   // they all go in registers, but we must reserve stack space for them for
5781   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5782   // assigned stack space in order, with padding so Altivec parameters are
5783   // 16-byte aligned.
5784   unsigned nAltivecParamsAtEnd = 0;
5785   for (unsigned i = 0; i != NumOps; ++i) {
5786     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5787     EVT ArgVT = Outs[i].VT;
5788     // Varargs Altivec parameters are padded to a 16 byte boundary.
5789     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5790         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5791         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5792       if (!isVarArg && !isPPC64) {
5793         // Non-varargs Altivec parameters go after all the non-Altivec
5794         // parameters; handle those later so we know how much padding we need.
5795         nAltivecParamsAtEnd++;
5796         continue;
5797       }
5798       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5799       NumBytes = ((NumBytes+15)/16)*16;
5800     }
5801     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5802   }
5803
5804   // Allow for Altivec parameters at the end, if needed.
5805   if (nAltivecParamsAtEnd) {
5806     NumBytes = ((NumBytes+15)/16)*16;
5807     NumBytes += 16*nAltivecParamsAtEnd;
5808   }
5809
5810   // The prolog code of the callee may store up to 8 GPR argument registers to
5811   // the stack, allowing va_start to index over them in memory if its varargs.
5812   // Because we cannot tell if this is needed on the caller side, we have to
5813   // conservatively assume that it is needed.  As such, make sure we have at
5814   // least enough stack space for the caller to store the 8 GPRs.
5815   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5816
5817   // Tail call needs the stack to be aligned.
5818   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5819       CallConv == CallingConv::Fast)
5820     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5821
5822   // Calculate by how many bytes the stack has to be adjusted in case of tail
5823   // call optimization.
5824   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5825
5826   // To protect arguments on the stack from being clobbered in a tail call,
5827   // force all the loads to happen before doing any other lowering.
5828   if (isTailCall)
5829     Chain = DAG.getStackArgumentTokenFactor(Chain);
5830
5831   // Adjust the stack pointer for the new arguments...
5832   // These operations are automatically eliminated by the prolog/epilog pass
5833   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5834                                dl);
5835   SDValue CallSeqStart = Chain;
5836
5837   // Load the return address and frame pointer so it can be move somewhere else
5838   // later.
5839   SDValue LROp, FPOp;
5840   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5841
5842   // Set up a copy of the stack pointer for use loading and storing any
5843   // arguments that may not fit in the registers available for argument
5844   // passing.
5845   SDValue StackPtr;
5846   if (isPPC64)
5847     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5848   else
5849     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5850
5851   // Figure out which arguments are going to go in registers, and which in
5852   // memory.  Also, if this is a vararg function, floating point operations
5853   // must be stored to our stack, and loaded into integer regs as well, if
5854   // any integer regs are available for argument passing.
5855   unsigned ArgOffset = LinkageSize;
5856   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5857
5858   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5859     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5860     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5861   };
5862   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5863     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5864     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5865   };
5866   static const MCPhysReg VR[] = {
5867     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5868     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5869   };
5870   const unsigned NumGPRs = array_lengthof(GPR_32);
5871   const unsigned NumFPRs = 13;
5872   const unsigned NumVRs  = array_lengthof(VR);
5873
5874   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5875
5876   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5877   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5878
5879   SmallVector<SDValue, 8> MemOpChains;
5880   for (unsigned i = 0; i != NumOps; ++i) {
5881     SDValue Arg = OutVals[i];
5882     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5883
5884     // PtrOff will be used to store the current argument to the stack if a
5885     // register cannot be found for it.
5886     SDValue PtrOff;
5887
5888     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5889
5890     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5891
5892     // On PPC64, promote integers to 64-bit values.
5893     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5894       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5895       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5896       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5897     }
5898
5899     // FIXME memcpy is used way more than necessary.  Correctness first.
5900     // Note: "by value" is code for passing a structure by value, not
5901     // basic types.
5902     if (Flags.isByVal()) {
5903       unsigned Size = Flags.getByValSize();
5904       // Very small objects are passed right-justified.  Everything else is
5905       // passed left-justified.
5906       if (Size==1 || Size==2) {
5907         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5908         if (GPR_idx != NumGPRs) {
5909           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5910                                         MachinePointerInfo(), VT);
5911           MemOpChains.push_back(Load.getValue(1));
5912           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5913
5914           ArgOffset += PtrByteSize;
5915         } else {
5916           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5917                                           PtrOff.getValueType());
5918           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5919           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5920                                                             CallSeqStart,
5921                                                             Flags, DAG, dl);
5922           ArgOffset += PtrByteSize;
5923         }
5924         continue;
5925       }
5926       // Copy entire object into memory.  There are cases where gcc-generated
5927       // code assumes it is there, even if it could be put entirely into
5928       // registers.  (This is not what the doc says.)
5929       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5930                                                         CallSeqStart,
5931                                                         Flags, DAG, dl);
5932
5933       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5934       // copy the pieces of the object that fit into registers from the
5935       // parameter save area.
5936       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5937         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5938         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5939         if (GPR_idx != NumGPRs) {
5940           SDValue Load =
5941               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5942           MemOpChains.push_back(Load.getValue(1));
5943           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5944           ArgOffset += PtrByteSize;
5945         } else {
5946           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5947           break;
5948         }
5949       }
5950       continue;
5951     }
5952
5953     switch (Arg.getSimpleValueType().SimpleTy) {
5954     default: llvm_unreachable("Unexpected ValueType for argument!");
5955     case MVT::i1:
5956     case MVT::i32:
5957     case MVT::i64:
5958       if (GPR_idx != NumGPRs) {
5959         if (Arg.getValueType() == MVT::i1)
5960           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5961
5962         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5963       } else {
5964         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5965                          isPPC64, isTailCall, false, MemOpChains,
5966                          TailCallArguments, dl);
5967       }
5968       ArgOffset += PtrByteSize;
5969       break;
5970     case MVT::f32:
5971     case MVT::f64:
5972       if (FPR_idx != NumFPRs) {
5973         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5974
5975         if (isVarArg) {
5976           SDValue Store =
5977               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5978           MemOpChains.push_back(Store);
5979
5980           // Float varargs are always shadowed in available integer registers
5981           if (GPR_idx != NumGPRs) {
5982             SDValue Load =
5983                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5984             MemOpChains.push_back(Load.getValue(1));
5985             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5986           }
5987           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5988             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5989             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5990             SDValue Load =
5991                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5992             MemOpChains.push_back(Load.getValue(1));
5993             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5994           }
5995         } else {
5996           // If we have any FPRs remaining, we may also have GPRs remaining.
5997           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5998           // GPRs.
5999           if (GPR_idx != NumGPRs)
6000             ++GPR_idx;
6001           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6002               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6003             ++GPR_idx;
6004         }
6005       } else
6006         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6007                          isPPC64, isTailCall, false, MemOpChains,
6008                          TailCallArguments, dl);
6009       if (isPPC64)
6010         ArgOffset += 8;
6011       else
6012         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6013       break;
6014     case MVT::v4f32:
6015     case MVT::v4i32:
6016     case MVT::v8i16:
6017     case MVT::v16i8:
6018       if (isVarArg) {
6019         // These go aligned on the stack, or in the corresponding R registers
6020         // when within range.  The Darwin PPC ABI doc claims they also go in
6021         // V registers; in fact gcc does this only for arguments that are
6022         // prototyped, not for those that match the ...  We do it for all
6023         // arguments, seems to work.
6024         while (ArgOffset % 16 !=0) {
6025           ArgOffset += PtrByteSize;
6026           if (GPR_idx != NumGPRs)
6027             GPR_idx++;
6028         }
6029         // We could elide this store in the case where the object fits
6030         // entirely in R registers.  Maybe later.
6031         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6032                              DAG.getConstant(ArgOffset, dl, PtrVT));
6033         SDValue Store =
6034             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6035         MemOpChains.push_back(Store);
6036         if (VR_idx != NumVRs) {
6037           SDValue Load =
6038               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6039           MemOpChains.push_back(Load.getValue(1));
6040           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6041         }
6042         ArgOffset += 16;
6043         for (unsigned i=0; i<16; i+=PtrByteSize) {
6044           if (GPR_idx == NumGPRs)
6045             break;
6046           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6047                                    DAG.getConstant(i, dl, PtrVT));
6048           SDValue Load =
6049               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6050           MemOpChains.push_back(Load.getValue(1));
6051           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6052         }
6053         break;
6054       }
6055
6056       // Non-varargs Altivec params generally go in registers, but have
6057       // stack space allocated at the end.
6058       if (VR_idx != NumVRs) {
6059         // Doesn't have GPR space allocated.
6060         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6061       } else if (nAltivecParamsAtEnd==0) {
6062         // We are emitting Altivec params in order.
6063         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6064                          isPPC64, isTailCall, true, MemOpChains,
6065                          TailCallArguments, dl);
6066         ArgOffset += 16;
6067       }
6068       break;
6069     }
6070   }
6071   // If all Altivec parameters fit in registers, as they usually do,
6072   // they get stack space following the non-Altivec parameters.  We
6073   // don't track this here because nobody below needs it.
6074   // If there are more Altivec parameters than fit in registers emit
6075   // the stores here.
6076   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6077     unsigned j = 0;
6078     // Offset is aligned; skip 1st 12 params which go in V registers.
6079     ArgOffset = ((ArgOffset+15)/16)*16;
6080     ArgOffset += 12*16;
6081     for (unsigned i = 0; i != NumOps; ++i) {
6082       SDValue Arg = OutVals[i];
6083       EVT ArgType = Outs[i].VT;
6084       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6085           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6086         if (++j > NumVRs) {
6087           SDValue PtrOff;
6088           // We are emitting Altivec params in order.
6089           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6090                            isPPC64, isTailCall, true, MemOpChains,
6091                            TailCallArguments, dl);
6092           ArgOffset += 16;
6093         }
6094       }
6095     }
6096   }
6097
6098   if (!MemOpChains.empty())
6099     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6100
6101   // On Darwin, R12 must contain the address of an indirect callee.  This does
6102   // not mean the MTCTR instruction must use R12; it's easier to model this as
6103   // an extra parameter, so do that.
6104   if (!isTailCall &&
6105       !isFunctionGlobalAddress(Callee) &&
6106       !isa<ExternalSymbolSDNode>(Callee) &&
6107       !isBLACompatibleAddress(Callee, DAG))
6108     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6109                                                    PPC::R12), Callee));
6110
6111   // Build a sequence of copy-to-reg nodes chained together with token chain
6112   // and flag operands which copy the outgoing args into the appropriate regs.
6113   SDValue InFlag;
6114   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6115     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6116                              RegsToPass[i].second, InFlag);
6117     InFlag = Chain.getValue(1);
6118   }
6119
6120   if (isTailCall)
6121     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6122                     TailCallArguments);
6123
6124   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6125                     /* unused except on PPC64 ELFv1 */ false, DAG,
6126                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6127                     NumBytes, Ins, InVals, CS);
6128 }
6129
6130 bool
6131 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6132                                   MachineFunction &MF, bool isVarArg,
6133                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6134                                   LLVMContext &Context) const {
6135   SmallVector<CCValAssign, 16> RVLocs;
6136   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6137   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6138 }
6139
6140 SDValue
6141 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6142                                bool isVarArg,
6143                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6144                                const SmallVectorImpl<SDValue> &OutVals,
6145                                const SDLoc &dl, SelectionDAG &DAG) const {
6146   SmallVector<CCValAssign, 16> RVLocs;
6147   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6148                  *DAG.getContext());
6149   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6150
6151   SDValue Flag;
6152   SmallVector<SDValue, 4> RetOps(1, Chain);
6153
6154   // Copy the result values into the output registers.
6155   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6156     CCValAssign &VA = RVLocs[i];
6157     assert(VA.isRegLoc() && "Can only return in registers!");
6158
6159     SDValue Arg = OutVals[i];
6160
6161     switch (VA.getLocInfo()) {
6162     default: llvm_unreachable("Unknown loc info!");
6163     case CCValAssign::Full: break;
6164     case CCValAssign::AExt:
6165       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6166       break;
6167     case CCValAssign::ZExt:
6168       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6169       break;
6170     case CCValAssign::SExt:
6171       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6172       break;
6173     }
6174
6175     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6176     Flag = Chain.getValue(1);
6177     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6178   }
6179
6180   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6181   const MCPhysReg *I =
6182     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6183   if (I) {
6184     for (; *I; ++I) {
6185
6186       if (PPC::G8RCRegClass.contains(*I))
6187         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6188       else if (PPC::F8RCRegClass.contains(*I))
6189         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6190       else if (PPC::CRRCRegClass.contains(*I))
6191         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6192       else if (PPC::VRRCRegClass.contains(*I))
6193         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6194       else
6195         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6196     }
6197   }
6198
6199   RetOps[0] = Chain;  // Update chain.
6200
6201   // Add the flag if we have it.
6202   if (Flag.getNode())
6203     RetOps.push_back(Flag);
6204
6205   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6206 }
6207
6208 SDValue
6209 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6210                                                 SelectionDAG &DAG) const {
6211   SDLoc dl(Op);
6212
6213   // Get the corect type for integers.
6214   EVT IntVT = Op.getValueType();
6215
6216   // Get the inputs.
6217   SDValue Chain = Op.getOperand(0);
6218   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6219   // Build a DYNAREAOFFSET node.
6220   SDValue Ops[2] = {Chain, FPSIdx};
6221   SDVTList VTs = DAG.getVTList(IntVT);
6222   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6223 }
6224
6225 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6226                                              SelectionDAG &DAG) const {
6227   // When we pop the dynamic allocation we need to restore the SP link.
6228   SDLoc dl(Op);
6229
6230   // Get the corect type for pointers.
6231   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6232
6233   // Construct the stack pointer operand.
6234   bool isPPC64 = Subtarget.isPPC64();
6235   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6236   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6237
6238   // Get the operands for the STACKRESTORE.
6239   SDValue Chain = Op.getOperand(0);
6240   SDValue SaveSP = Op.getOperand(1);
6241
6242   // Load the old link SP.
6243   SDValue LoadLinkSP =
6244       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6245
6246   // Restore the stack pointer.
6247   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6248
6249   // Store the old link SP.
6250   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6251 }
6252
6253 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6254   MachineFunction &MF = DAG.getMachineFunction();
6255   bool isPPC64 = Subtarget.isPPC64();
6256   EVT PtrVT = getPointerTy(MF.getDataLayout());
6257
6258   // Get current frame pointer save index.  The users of this index will be
6259   // primarily DYNALLOC instructions.
6260   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6261   int RASI = FI->getReturnAddrSaveIndex();
6262
6263   // If the frame pointer save index hasn't been defined yet.
6264   if (!RASI) {
6265     // Find out what the fix offset of the frame pointer save area.
6266     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6267     // Allocate the frame index for frame pointer save area.
6268     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6269     // Save the result.
6270     FI->setReturnAddrSaveIndex(RASI);
6271   }
6272   return DAG.getFrameIndex(RASI, PtrVT);
6273 }
6274
6275 SDValue
6276 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6277   MachineFunction &MF = DAG.getMachineFunction();
6278   bool isPPC64 = Subtarget.isPPC64();
6279   EVT PtrVT = getPointerTy(MF.getDataLayout());
6280
6281   // Get current frame pointer save index.  The users of this index will be
6282   // primarily DYNALLOC instructions.
6283   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6284   int FPSI = FI->getFramePointerSaveIndex();
6285
6286   // If the frame pointer save index hasn't been defined yet.
6287   if (!FPSI) {
6288     // Find out what the fix offset of the frame pointer save area.
6289     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6290     // Allocate the frame index for frame pointer save area.
6291     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6292     // Save the result.
6293     FI->setFramePointerSaveIndex(FPSI);
6294   }
6295   return DAG.getFrameIndex(FPSI, PtrVT);
6296 }
6297
6298 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6299                                                    SelectionDAG &DAG) const {
6300   // Get the inputs.
6301   SDValue Chain = Op.getOperand(0);
6302   SDValue Size  = Op.getOperand(1);
6303   SDLoc dl(Op);
6304
6305   // Get the corect type for pointers.
6306   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6307   // Negate the size.
6308   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6309                                 DAG.getConstant(0, dl, PtrVT), Size);
6310   // Construct a node for the frame pointer save index.
6311   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6312   // Build a DYNALLOC node.
6313   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6314   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6315   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6316 }
6317
6318 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6319                                                      SelectionDAG &DAG) const {
6320   MachineFunction &MF = DAG.getMachineFunction();
6321
6322   bool isPPC64 = Subtarget.isPPC64();
6323   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6324
6325   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6326   return DAG.getFrameIndex(FI, PtrVT);
6327 }
6328
6329 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6330                                                SelectionDAG &DAG) const {
6331   SDLoc DL(Op);
6332   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6333                      DAG.getVTList(MVT::i32, MVT::Other),
6334                      Op.getOperand(0), Op.getOperand(1));
6335 }
6336
6337 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6338                                                 SelectionDAG &DAG) const {
6339   SDLoc DL(Op);
6340   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6341                      Op.getOperand(0), Op.getOperand(1));
6342 }
6343
6344 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6345   if (Op.getValueType().isVector())
6346     return LowerVectorLoad(Op, DAG);
6347
6348   assert(Op.getValueType() == MVT::i1 &&
6349          "Custom lowering only for i1 loads");
6350
6351   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6352
6353   SDLoc dl(Op);
6354   LoadSDNode *LD = cast<LoadSDNode>(Op);
6355
6356   SDValue Chain = LD->getChain();
6357   SDValue BasePtr = LD->getBasePtr();
6358   MachineMemOperand *MMO = LD->getMemOperand();
6359
6360   SDValue NewLD =
6361       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6362                      BasePtr, MVT::i8, MMO);
6363   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6364
6365   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6366   return DAG.getMergeValues(Ops, dl);
6367 }
6368
6369 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6370   if (Op.getOperand(1).getValueType().isVector())
6371     return LowerVectorStore(Op, DAG);
6372
6373   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6374          "Custom lowering only for i1 stores");
6375
6376   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6377
6378   SDLoc dl(Op);
6379   StoreSDNode *ST = cast<StoreSDNode>(Op);
6380
6381   SDValue Chain = ST->getChain();
6382   SDValue BasePtr = ST->getBasePtr();
6383   SDValue Value = ST->getValue();
6384   MachineMemOperand *MMO = ST->getMemOperand();
6385
6386   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6387                       Value);
6388   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6389 }
6390
6391 // FIXME: Remove this once the ANDI glue bug is fixed:
6392 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6393   assert(Op.getValueType() == MVT::i1 &&
6394          "Custom lowering only for i1 results");
6395
6396   SDLoc DL(Op);
6397   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6398                      Op.getOperand(0));
6399 }
6400
6401 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6402 /// possible.
6403 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6404   // Not FP? Not a fsel.
6405   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6406       !Op.getOperand(2).getValueType().isFloatingPoint())
6407     return Op;
6408
6409   // We might be able to do better than this under some circumstances, but in
6410   // general, fsel-based lowering of select is a finite-math-only optimization.
6411   // For more information, see section F.3 of the 2.06 ISA specification.
6412   if (!DAG.getTarget().Options.NoInfsFPMath ||
6413       !DAG.getTarget().Options.NoNaNsFPMath)
6414     return Op;
6415   // TODO: Propagate flags from the select rather than global settings.
6416   SDNodeFlags Flags;
6417   Flags.setNoInfs(true);
6418   Flags.setNoNaNs(true);
6419
6420   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6421
6422   EVT ResVT = Op.getValueType();
6423   EVT CmpVT = Op.getOperand(0).getValueType();
6424   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6425   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6426   SDLoc dl(Op);
6427
6428   // If the RHS of the comparison is a 0.0, we don't need to do the
6429   // subtraction at all.
6430   SDValue Sel1;
6431   if (isFloatingPointZero(RHS))
6432     switch (CC) {
6433     default: break;       // SETUO etc aren't handled by fsel.
6434     case ISD::SETNE:
6435       std::swap(TV, FV);
6436     case ISD::SETEQ:
6437       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6438         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6439       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6440       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6441         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6442       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6443                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6444     case ISD::SETULT:
6445     case ISD::SETLT:
6446       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6447     case ISD::SETOGE:
6448     case ISD::SETGE:
6449       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6450         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6451       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6452     case ISD::SETUGT:
6453     case ISD::SETGT:
6454       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6455     case ISD::SETOLE:
6456     case ISD::SETLE:
6457       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6458         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6459       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6460                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6461     }
6462
6463   SDValue Cmp;
6464   switch (CC) {
6465   default: break;       // SETUO etc aren't handled by fsel.
6466   case ISD::SETNE:
6467     std::swap(TV, FV);
6468   case ISD::SETEQ:
6469     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6470     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6471       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6472     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6473     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6474       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6475     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6476                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6477   case ISD::SETULT:
6478   case ISD::SETLT:
6479     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6480     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6481       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6482     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6483   case ISD::SETOGE:
6484   case ISD::SETGE:
6485     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6486     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6487       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6488     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6489   case ISD::SETUGT:
6490   case ISD::SETGT:
6491     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6492     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6493       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6494     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6495   case ISD::SETOLE:
6496   case ISD::SETLE:
6497     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6498     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6499       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6500     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6501   }
6502   return Op;
6503 }
6504
6505 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6506                                                SelectionDAG &DAG,
6507                                                const SDLoc &dl) const {
6508   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6509   SDValue Src = Op.getOperand(0);
6510   if (Src.getValueType() == MVT::f32)
6511     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6512
6513   SDValue Tmp;
6514   switch (Op.getSimpleValueType().SimpleTy) {
6515   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6516   case MVT::i32:
6517     Tmp = DAG.getNode(
6518         Op.getOpcode() == ISD::FP_TO_SINT
6519             ? PPCISD::FCTIWZ
6520             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6521         dl, MVT::f64, Src);
6522     break;
6523   case MVT::i64:
6524     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6525            "i64 FP_TO_UINT is supported only with FPCVT");
6526     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6527                                                         PPCISD::FCTIDUZ,
6528                       dl, MVT::f64, Src);
6529     break;
6530   }
6531
6532   // Convert the FP value to an int value through memory.
6533   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6534     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6535   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6536   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6537   MachinePointerInfo MPI =
6538       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6539
6540   // Emit a store to the stack slot.
6541   SDValue Chain;
6542   if (i32Stack) {
6543     MachineFunction &MF = DAG.getMachineFunction();
6544     MachineMemOperand *MMO =
6545       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6546     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6547     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6548               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6549   } else
6550     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6551
6552   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6553   // add in a bias on big endian.
6554   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6555     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6556                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6557     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6558   }
6559
6560   RLI.Chain = Chain;
6561   RLI.Ptr = FIPtr;
6562   RLI.MPI = MPI;
6563 }
6564
6565 /// \brief Custom lowers floating point to integer conversions to use
6566 /// the direct move instructions available in ISA 2.07 to avoid the
6567 /// need for load/store combinations.
6568 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6569                                                     SelectionDAG &DAG,
6570                                                     const SDLoc &dl) const {
6571   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6572   SDValue Src = Op.getOperand(0);
6573
6574   if (Src.getValueType() == MVT::f32)
6575     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6576
6577   SDValue Tmp;
6578   switch (Op.getSimpleValueType().SimpleTy) {
6579   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6580   case MVT::i32:
6581     Tmp = DAG.getNode(
6582         Op.getOpcode() == ISD::FP_TO_SINT
6583             ? PPCISD::FCTIWZ
6584             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6585         dl, MVT::f64, Src);
6586     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6587     break;
6588   case MVT::i64:
6589     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6590            "i64 FP_TO_UINT is supported only with FPCVT");
6591     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6592                                                         PPCISD::FCTIDUZ,
6593                       dl, MVT::f64, Src);
6594     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6595     break;
6596   }
6597   return Tmp;
6598 }
6599
6600 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6601                                           const SDLoc &dl) const {
6602   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6603     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6604
6605   ReuseLoadInfo RLI;
6606   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6607
6608   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6609                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6610 }
6611
6612 // We're trying to insert a regular store, S, and then a load, L. If the
6613 // incoming value, O, is a load, we might just be able to have our load use the
6614 // address used by O. However, we don't know if anything else will store to
6615 // that address before we can load from it. To prevent this situation, we need
6616 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6617 // the same chain operand as O, we create a token factor from the chain results
6618 // of O and L, and we replace all uses of O's chain result with that token
6619 // factor (see spliceIntoChain below for this last part).
6620 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6621                                             ReuseLoadInfo &RLI,
6622                                             SelectionDAG &DAG,
6623                                             ISD::LoadExtType ET) const {
6624   SDLoc dl(Op);
6625   if (ET == ISD::NON_EXTLOAD &&
6626       (Op.getOpcode() == ISD::FP_TO_UINT ||
6627        Op.getOpcode() == ISD::FP_TO_SINT) &&
6628       isOperationLegalOrCustom(Op.getOpcode(),
6629                                Op.getOperand(0).getValueType())) {
6630
6631     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6632     return true;
6633   }
6634
6635   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6636   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6637       LD->isNonTemporal())
6638     return false;
6639   if (LD->getMemoryVT() != MemVT)
6640     return false;
6641
6642   RLI.Ptr = LD->getBasePtr();
6643   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6644     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6645            "Non-pre-inc AM on PPC?");
6646     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6647                           LD->getOffset());
6648   }
6649
6650   RLI.Chain = LD->getChain();
6651   RLI.MPI = LD->getPointerInfo();
6652   RLI.IsDereferenceable = LD->isDereferenceable();
6653   RLI.IsInvariant = LD->isInvariant();
6654   RLI.Alignment = LD->getAlignment();
6655   RLI.AAInfo = LD->getAAInfo();
6656   RLI.Ranges = LD->getRanges();
6657
6658   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6659   return true;
6660 }
6661
6662 // Given the head of the old chain, ResChain, insert a token factor containing
6663 // it and NewResChain, and make users of ResChain now be users of that token
6664 // factor.
6665 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6666                                         SDValue NewResChain,
6667                                         SelectionDAG &DAG) const {
6668   if (!ResChain)
6669     return;
6670
6671   SDLoc dl(NewResChain);
6672
6673   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6674                            NewResChain, DAG.getUNDEF(MVT::Other));
6675   assert(TF.getNode() != NewResChain.getNode() &&
6676          "A new TF really is required here");
6677
6678   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6679   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6680 }
6681
6682 /// \brief Analyze profitability of direct move
6683 /// prefer float load to int load plus direct move
6684 /// when there is no integer use of int load
6685 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6686   SDNode *Origin = Op.getOperand(0).getNode();
6687   if (Origin->getOpcode() != ISD::LOAD)
6688     return true;
6689
6690   // If there is no LXSIBZX/LXSIHZX, like Power8,
6691   // prefer direct move if the memory size is 1 or 2 bytes.
6692   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6693   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6694     return true;
6695
6696   for (SDNode::use_iterator UI = Origin->use_begin(),
6697                             UE = Origin->use_end();
6698        UI != UE; ++UI) {
6699
6700     // Only look at the users of the loaded value.
6701     if (UI.getUse().get().getResNo() != 0)
6702       continue;
6703
6704     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6705         UI->getOpcode() != ISD::UINT_TO_FP)
6706       return true;
6707   }
6708
6709   return false;
6710 }
6711
6712 /// \brief Custom lowers integer to floating point conversions to use
6713 /// the direct move instructions available in ISA 2.07 to avoid the
6714 /// need for load/store combinations.
6715 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6716                                                     SelectionDAG &DAG,
6717                                                     const SDLoc &dl) const {
6718   assert((Op.getValueType() == MVT::f32 ||
6719           Op.getValueType() == MVT::f64) &&
6720          "Invalid floating point type as target of conversion");
6721   assert(Subtarget.hasFPCVT() &&
6722          "Int to FP conversions with direct moves require FPCVT");
6723   SDValue FP;
6724   SDValue Src = Op.getOperand(0);
6725   bool SinglePrec = Op.getValueType() == MVT::f32;
6726   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6727   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6728   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6729                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6730
6731   if (WordInt) {
6732     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6733                      dl, MVT::f64, Src);
6734     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6735   }
6736   else {
6737     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6738     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6739   }
6740
6741   return FP;
6742 }
6743
6744 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6745                                           SelectionDAG &DAG) const {
6746   SDLoc dl(Op);
6747
6748   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6749     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6750       return SDValue();
6751
6752     SDValue Value = Op.getOperand(0);
6753     // The values are now known to be -1 (false) or 1 (true). To convert this
6754     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6755     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6756     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6757
6758     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6759
6760     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6761
6762     if (Op.getValueType() != MVT::v4f64)
6763       Value = DAG.getNode(ISD::FP_ROUND, dl,
6764                           Op.getValueType(), Value,
6765                           DAG.getIntPtrConstant(1, dl));
6766     return Value;
6767   }
6768
6769   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6770   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6771     return SDValue();
6772
6773   if (Op.getOperand(0).getValueType() == MVT::i1)
6774     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6775                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6776                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6777
6778   // If we have direct moves, we can do all the conversion, skip the store/load
6779   // however, without FPCVT we can't do most conversions.
6780   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6781       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6782     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6783
6784   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6785          "UINT_TO_FP is supported only with FPCVT");
6786
6787   // If we have FCFIDS, then use it when converting to single-precision.
6788   // Otherwise, convert to double-precision and then round.
6789   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6790                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6791                                                             : PPCISD::FCFIDS)
6792                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6793                                                             : PPCISD::FCFID);
6794   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6795                   ? MVT::f32
6796                   : MVT::f64;
6797
6798   if (Op.getOperand(0).getValueType() == MVT::i64) {
6799     SDValue SINT = Op.getOperand(0);
6800     // When converting to single-precision, we actually need to convert
6801     // to double-precision first and then round to single-precision.
6802     // To avoid double-rounding effects during that operation, we have
6803     // to prepare the input operand.  Bits that might be truncated when
6804     // converting to double-precision are replaced by a bit that won't
6805     // be lost at this stage, but is below the single-precision rounding
6806     // position.
6807     //
6808     // However, if -enable-unsafe-fp-math is in effect, accept double
6809     // rounding to avoid the extra overhead.
6810     if (Op.getValueType() == MVT::f32 &&
6811         !Subtarget.hasFPCVT() &&
6812         !DAG.getTarget().Options.UnsafeFPMath) {
6813
6814       // Twiddle input to make sure the low 11 bits are zero.  (If this
6815       // is the case, we are guaranteed the value will fit into the 53 bit
6816       // mantissa of an IEEE double-precision value without rounding.)
6817       // If any of those low 11 bits were not zero originally, make sure
6818       // bit 12 (value 2048) is set instead, so that the final rounding
6819       // to single-precision gets the correct result.
6820       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6821                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6822       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6823                           Round, DAG.getConstant(2047, dl, MVT::i64));
6824       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6825       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6826                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6827
6828       // However, we cannot use that value unconditionally: if the magnitude
6829       // of the input value is small, the bit-twiddling we did above might
6830       // end up visibly changing the output.  Fortunately, in that case, we
6831       // don't need to twiddle bits since the original input will convert
6832       // exactly to double-precision floating-point already.  Therefore,
6833       // construct a conditional to use the original value if the top 11
6834       // bits are all sign-bit copies, and use the rounded value computed
6835       // above otherwise.
6836       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6837                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6838       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6839                          Cond, DAG.getConstant(1, dl, MVT::i64));
6840       Cond = DAG.getSetCC(dl, MVT::i32,
6841                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6842
6843       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6844     }
6845
6846     ReuseLoadInfo RLI;
6847     SDValue Bits;
6848
6849     MachineFunction &MF = DAG.getMachineFunction();
6850     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6851       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6852                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6853       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6854     } else if (Subtarget.hasLFIWAX() &&
6855                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6856       MachineMemOperand *MMO =
6857         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6858                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6859       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6860       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6861                                      DAG.getVTList(MVT::f64, MVT::Other),
6862                                      Ops, MVT::i32, MMO);
6863       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6864     } else if (Subtarget.hasFPCVT() &&
6865                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6866       MachineMemOperand *MMO =
6867         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6868                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6869       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6870       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6871                                      DAG.getVTList(MVT::f64, MVT::Other),
6872                                      Ops, MVT::i32, MMO);
6873       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6874     } else if (((Subtarget.hasLFIWAX() &&
6875                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6876                 (Subtarget.hasFPCVT() &&
6877                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6878                SINT.getOperand(0).getValueType() == MVT::i32) {
6879       MachineFrameInfo &MFI = MF.getFrameInfo();
6880       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6881
6882       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6883       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6884
6885       SDValue Store =
6886           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6887                        MachinePointerInfo::getFixedStack(
6888                            DAG.getMachineFunction(), FrameIdx));
6889
6890       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6891              "Expected an i32 store");
6892
6893       RLI.Ptr = FIdx;
6894       RLI.Chain = Store;
6895       RLI.MPI =
6896           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6897       RLI.Alignment = 4;
6898
6899       MachineMemOperand *MMO =
6900         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6901                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6902       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6903       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6904                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6905                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6906                                      Ops, MVT::i32, MMO);
6907     } else
6908       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6909
6910     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6911
6912     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6913       FP = DAG.getNode(ISD::FP_ROUND, dl,
6914                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6915     return FP;
6916   }
6917
6918   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6919          "Unhandled INT_TO_FP type in custom expander!");
6920   // Since we only generate this in 64-bit mode, we can take advantage of
6921   // 64-bit registers.  In particular, sign extend the input value into the
6922   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6923   // then lfd it and fcfid it.
6924   MachineFunction &MF = DAG.getMachineFunction();
6925   MachineFrameInfo &MFI = MF.getFrameInfo();
6926   EVT PtrVT = getPointerTy(MF.getDataLayout());
6927
6928   SDValue Ld;
6929   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6930     ReuseLoadInfo RLI;
6931     bool ReusingLoad;
6932     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6933                                             DAG))) {
6934       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6935       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6936
6937       SDValue Store =
6938           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6939                        MachinePointerInfo::getFixedStack(
6940                            DAG.getMachineFunction(), FrameIdx));
6941
6942       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6943              "Expected an i32 store");
6944
6945       RLI.Ptr = FIdx;
6946       RLI.Chain = Store;
6947       RLI.MPI =
6948           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6949       RLI.Alignment = 4;
6950     }
6951
6952     MachineMemOperand *MMO =
6953       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6954                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6955     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6956     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6957                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6958                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6959                                  Ops, MVT::i32, MMO);
6960     if (ReusingLoad)
6961       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6962   } else {
6963     assert(Subtarget.isPPC64() &&
6964            "i32->FP without LFIWAX supported only on PPC64");
6965
6966     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6967     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6968
6969     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6970                                 Op.getOperand(0));
6971
6972     // STD the extended value into the stack slot.
6973     SDValue Store = DAG.getStore(
6974         DAG.getEntryNode(), dl, Ext64, FIdx,
6975         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6976
6977     // Load the value as a double.
6978     Ld = DAG.getLoad(
6979         MVT::f64, dl, Store, FIdx,
6980         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6981   }
6982
6983   // FCFID it and return it.
6984   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6985   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6986     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6987                      DAG.getIntPtrConstant(0, dl));
6988   return FP;
6989 }
6990
6991 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6992                                             SelectionDAG &DAG) const {
6993   SDLoc dl(Op);
6994   /*
6995    The rounding mode is in bits 30:31 of FPSR, and has the following
6996    settings:
6997      00 Round to nearest
6998      01 Round to 0
6999      10 Round to +inf
7000      11 Round to -inf
7001
7002   FLT_ROUNDS, on the other hand, expects the following:
7003     -1 Undefined
7004      0 Round to 0
7005      1 Round to nearest
7006      2 Round to +inf
7007      3 Round to -inf
7008
7009   To perform the conversion, we do:
7010     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7011   */
7012
7013   MachineFunction &MF = DAG.getMachineFunction();
7014   EVT VT = Op.getValueType();
7015   EVT PtrVT = getPointerTy(MF.getDataLayout());
7016
7017   // Save FP Control Word to register
7018   EVT NodeTys[] = {
7019     MVT::f64,    // return register
7020     MVT::Glue    // unused in this context
7021   };
7022   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7023
7024   // Save FP register to stack slot
7025   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7026   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7027   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7028                                MachinePointerInfo());
7029
7030   // Load FP Control Word from low 32 bits of stack slot.
7031   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7032   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7033   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7034
7035   // Transform as necessary
7036   SDValue CWD1 =
7037     DAG.getNode(ISD::AND, dl, MVT::i32,
7038                 CWD, DAG.getConstant(3, dl, MVT::i32));
7039   SDValue CWD2 =
7040     DAG.getNode(ISD::SRL, dl, MVT::i32,
7041                 DAG.getNode(ISD::AND, dl, MVT::i32,
7042                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7043                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7044                             DAG.getConstant(3, dl, MVT::i32)),
7045                 DAG.getConstant(1, dl, MVT::i32));
7046
7047   SDValue RetVal =
7048     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7049
7050   return DAG.getNode((VT.getSizeInBits() < 16 ?
7051                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7052 }
7053
7054 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7055   EVT VT = Op.getValueType();
7056   unsigned BitWidth = VT.getSizeInBits();
7057   SDLoc dl(Op);
7058   assert(Op.getNumOperands() == 3 &&
7059          VT == Op.getOperand(1).getValueType() &&
7060          "Unexpected SHL!");
7061
7062   // Expand into a bunch of logical ops.  Note that these ops
7063   // depend on the PPC behavior for oversized shift amounts.
7064   SDValue Lo = Op.getOperand(0);
7065   SDValue Hi = Op.getOperand(1);
7066   SDValue Amt = Op.getOperand(2);
7067   EVT AmtVT = Amt.getValueType();
7068
7069   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7070                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7071   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7072   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7073   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7074   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7075                              DAG.getConstant(-BitWidth, dl, AmtVT));
7076   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7077   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7078   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7079   SDValue OutOps[] = { OutLo, OutHi };
7080   return DAG.getMergeValues(OutOps, dl);
7081 }
7082
7083 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7084   EVT VT = Op.getValueType();
7085   SDLoc dl(Op);
7086   unsigned BitWidth = VT.getSizeInBits();
7087   assert(Op.getNumOperands() == 3 &&
7088          VT == Op.getOperand(1).getValueType() &&
7089          "Unexpected SRL!");
7090
7091   // Expand into a bunch of logical ops.  Note that these ops
7092   // depend on the PPC behavior for oversized shift amounts.
7093   SDValue Lo = Op.getOperand(0);
7094   SDValue Hi = Op.getOperand(1);
7095   SDValue Amt = Op.getOperand(2);
7096   EVT AmtVT = Amt.getValueType();
7097
7098   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7099                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7100   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7101   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7102   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7103   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7104                              DAG.getConstant(-BitWidth, dl, AmtVT));
7105   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7106   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7107   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7108   SDValue OutOps[] = { OutLo, OutHi };
7109   return DAG.getMergeValues(OutOps, dl);
7110 }
7111
7112 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7113   SDLoc dl(Op);
7114   EVT VT = Op.getValueType();
7115   unsigned BitWidth = VT.getSizeInBits();
7116   assert(Op.getNumOperands() == 3 &&
7117          VT == Op.getOperand(1).getValueType() &&
7118          "Unexpected SRA!");
7119
7120   // Expand into a bunch of logical ops, followed by a select_cc.
7121   SDValue Lo = Op.getOperand(0);
7122   SDValue Hi = Op.getOperand(1);
7123   SDValue Amt = Op.getOperand(2);
7124   EVT AmtVT = Amt.getValueType();
7125
7126   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7127                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7128   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7129   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7130   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7131   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7132                              DAG.getConstant(-BitWidth, dl, AmtVT));
7133   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7134   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7135   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7136                                   Tmp4, Tmp6, ISD::SETLE);
7137   SDValue OutOps[] = { OutLo, OutHi };
7138   return DAG.getMergeValues(OutOps, dl);
7139 }
7140
7141 //===----------------------------------------------------------------------===//
7142 // Vector related lowering.
7143 //
7144
7145 /// BuildSplatI - Build a canonical splati of Val with an element size of
7146 /// SplatSize.  Cast the result to VT.
7147 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7148                            SelectionDAG &DAG, const SDLoc &dl) {
7149   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7150
7151   static const MVT VTys[] = { // canonical VT to use for each size.
7152     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7153   };
7154
7155   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7156
7157   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7158   if (Val == -1)
7159     SplatSize = 1;
7160
7161   EVT CanonicalVT = VTys[SplatSize-1];
7162
7163   // Build a canonical splat for this value.
7164   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7165 }
7166
7167 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7168 /// specified intrinsic ID.
7169 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7170                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7171   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7172   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7173                      DAG.getConstant(IID, dl, MVT::i32), Op);
7174 }
7175
7176 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7177 /// specified intrinsic ID.
7178 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7179                                 SelectionDAG &DAG, const SDLoc &dl,
7180                                 EVT DestVT = MVT::Other) {
7181   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7182   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7183                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7184 }
7185
7186 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7187 /// specified intrinsic ID.
7188 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7189                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7190                                 EVT DestVT = MVT::Other) {
7191   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7192   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7193                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7194 }
7195
7196 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7197 /// amount.  The result has the specified value type.
7198 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7199                            SelectionDAG &DAG, const SDLoc &dl) {
7200   // Force LHS/RHS to be the right type.
7201   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7202   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7203
7204   int Ops[16];
7205   for (unsigned i = 0; i != 16; ++i)
7206     Ops[i] = i + Amt;
7207   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7208   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7209 }
7210
7211 /// Do we have an efficient pattern in a .td file for this node?
7212 ///
7213 /// \param V - pointer to the BuildVectorSDNode being matched
7214 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7215 ///
7216 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7217 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7218 /// the opposite is true (expansion is beneficial) are:
7219 /// - The node builds a vector out of integers that are not 32 or 64-bits
7220 /// - The node builds a vector out of constants
7221 /// - The node is a "load-and-splat"
7222 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7223 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7224                                             bool HasDirectMove) {
7225   EVT VecVT = V->getValueType(0);
7226   bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7227     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7228   if (!RightType)
7229     return false;
7230
7231   bool IsSplat = true;
7232   bool IsLoad = false;
7233   SDValue Op0 = V->getOperand(0);
7234
7235   // This function is called in a block that confirms the node is not a constant
7236   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7237   // different constants.
7238   if (V->isConstant())
7239     return false;
7240   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7241     if (V->getOperand(i).isUndef())
7242       return false;
7243     // We want to expand nodes that represent load-and-splat even if the
7244     // loaded value is a floating point truncation or conversion to int.
7245     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7246         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7247          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7248         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7249          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7250         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7251          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7252       IsLoad = true;
7253     // If the operands are different or the input is not a load and has more
7254     // uses than just this BV node, then it isn't a splat.
7255     if (V->getOperand(i) != Op0 ||
7256         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7257       IsSplat = false;
7258   }
7259   return !(IsSplat && IsLoad);
7260 }
7261
7262 // If this is a case we can't handle, return null and let the default
7263 // expansion code take care of it.  If we CAN select this case, and if it
7264 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7265 // this case more efficiently than a constant pool load, lower it to the
7266 // sequence of ops that should be used.
7267 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7268                                              SelectionDAG &DAG) const {
7269   SDLoc dl(Op);
7270   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7271   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7272
7273   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7274     // We first build an i32 vector, load it into a QPX register,
7275     // then convert it to a floating-point vector and compare it
7276     // to a zero vector to get the boolean result.
7277     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7278     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7279     MachinePointerInfo PtrInfo =
7280         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7281     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7282     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7283
7284     assert(BVN->getNumOperands() == 4 &&
7285       "BUILD_VECTOR for v4i1 does not have 4 operands");
7286
7287     bool IsConst = true;
7288     for (unsigned i = 0; i < 4; ++i) {
7289       if (BVN->getOperand(i).isUndef()) continue;
7290       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7291         IsConst = false;
7292         break;
7293       }
7294     }
7295
7296     if (IsConst) {
7297       Constant *One =
7298         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7299       Constant *NegOne =
7300         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7301
7302       Constant *CV[4];
7303       for (unsigned i = 0; i < 4; ++i) {
7304         if (BVN->getOperand(i).isUndef())
7305           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7306         else if (isNullConstant(BVN->getOperand(i)))
7307           CV[i] = NegOne;
7308         else
7309           CV[i] = One;
7310       }
7311
7312       Constant *CP = ConstantVector::get(CV);
7313       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7314                                           16 /* alignment */);
7315
7316       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7317       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7318       return DAG.getMemIntrinsicNode(
7319           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7320           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7321     }
7322
7323     SmallVector<SDValue, 4> Stores;
7324     for (unsigned i = 0; i < 4; ++i) {
7325       if (BVN->getOperand(i).isUndef()) continue;
7326
7327       unsigned Offset = 4*i;
7328       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7329       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7330
7331       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7332       if (StoreSize > 4) {
7333         Stores.push_back(
7334             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7335                               PtrInfo.getWithOffset(Offset), MVT::i32));
7336       } else {
7337         SDValue StoreValue = BVN->getOperand(i);
7338         if (StoreSize < 4)
7339           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7340
7341         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7342                                       PtrInfo.getWithOffset(Offset)));
7343       }
7344     }
7345
7346     SDValue StoreChain;
7347     if (!Stores.empty())
7348       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7349     else
7350       StoreChain = DAG.getEntryNode();
7351
7352     // Now load from v4i32 into the QPX register; this will extend it to
7353     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7354     // is typed as v4f64 because the QPX register integer states are not
7355     // explicitly represented.
7356
7357     SDValue Ops[] = {StoreChain,
7358                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7359                      FIdx};
7360     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7361
7362     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7363       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7364     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7365       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7366       LoadedVect);
7367
7368     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7369
7370     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7371   }
7372
7373   // All other QPX vectors are handled by generic code.
7374   if (Subtarget.hasQPX())
7375     return SDValue();
7376
7377   // Check if this is a splat of a constant value.
7378   APInt APSplatBits, APSplatUndef;
7379   unsigned SplatBitSize;
7380   bool HasAnyUndefs;
7381   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7382                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7383       SplatBitSize > 32) {
7384     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7385     // lowered to VSX instructions under certain conditions.
7386     // Without VSX, there is no pattern more efficient than expanding the node.
7387     if (Subtarget.hasVSX() &&
7388         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7389       return Op;
7390     return SDValue();
7391   }
7392
7393   unsigned SplatBits = APSplatBits.getZExtValue();
7394   unsigned SplatUndef = APSplatUndef.getZExtValue();
7395   unsigned SplatSize = SplatBitSize / 8;
7396
7397   // First, handle single instruction cases.
7398
7399   // All zeros?
7400   if (SplatBits == 0) {
7401     // Canonicalize all zero vectors to be v4i32.
7402     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7403       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7404       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7405     }
7406     return Op;
7407   }
7408
7409   // We have XXSPLTIB for constant splats one byte wide
7410   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7411     // This is a splat of 1-byte elements with some elements potentially undef.
7412     // Rather than trying to match undef in the SDAG patterns, ensure that all
7413     // elements are the same constant.
7414     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7415       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7416                                                        dl, MVT::i32));
7417       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7418       if (Op.getValueType() != MVT::v16i8)
7419         return DAG.getBitcast(Op.getValueType(), NewBV);
7420       return NewBV;
7421     }
7422     return Op;
7423   }
7424
7425   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7426   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7427                     (32-SplatBitSize));
7428   if (SextVal >= -16 && SextVal <= 15)
7429     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7430
7431   // Two instruction sequences.
7432
7433   // If this value is in the range [-32,30] and is even, use:
7434   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7435   // If this value is in the range [17,31] and is odd, use:
7436   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7437   // If this value is in the range [-31,-17] and is odd, use:
7438   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7439   // Note the last two are three-instruction sequences.
7440   if (SextVal >= -32 && SextVal <= 31) {
7441     // To avoid having these optimizations undone by constant folding,
7442     // we convert to a pseudo that will be expanded later into one of
7443     // the above forms.
7444     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7445     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7446               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7447     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7448     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7449     if (VT == Op.getValueType())
7450       return RetVal;
7451     else
7452       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7453   }
7454
7455   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7456   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7457   // for fneg/fabs.
7458   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7459     // Make -1 and vspltisw -1:
7460     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7461
7462     // Make the VSLW intrinsic, computing 0x8000_0000.
7463     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7464                                    OnesV, DAG, dl);
7465
7466     // xor by OnesV to invert it.
7467     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7468     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7469   }
7470
7471   // Check to see if this is a wide variety of vsplti*, binop self cases.
7472   static const signed char SplatCsts[] = {
7473     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7474     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7475   };
7476
7477   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7478     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7479     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7480     int i = SplatCsts[idx];
7481
7482     // Figure out what shift amount will be used by altivec if shifted by i in
7483     // this splat size.
7484     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7485
7486     // vsplti + shl self.
7487     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7488       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7489       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7490         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7491         Intrinsic::ppc_altivec_vslw
7492       };
7493       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7494       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7495     }
7496
7497     // vsplti + srl self.
7498     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7499       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7500       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7501         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7502         Intrinsic::ppc_altivec_vsrw
7503       };
7504       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7505       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7506     }
7507
7508     // vsplti + sra self.
7509     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7510       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7511       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7512         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7513         Intrinsic::ppc_altivec_vsraw
7514       };
7515       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7516       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7517     }
7518
7519     // vsplti + rol self.
7520     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7521                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7522       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7523       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7524         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7525         Intrinsic::ppc_altivec_vrlw
7526       };
7527       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7528       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7529     }
7530
7531     // t = vsplti c, result = vsldoi t, t, 1
7532     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7533       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7534       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7535       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7536     }
7537     // t = vsplti c, result = vsldoi t, t, 2
7538     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7539       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7540       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7541       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7542     }
7543     // t = vsplti c, result = vsldoi t, t, 3
7544     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7545       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7546       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7547       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7548     }
7549   }
7550
7551   return SDValue();
7552 }
7553
7554 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7555 /// the specified operations to build the shuffle.
7556 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7557                                       SDValue RHS, SelectionDAG &DAG,
7558                                       const SDLoc &dl) {
7559   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7560   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7561   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7562
7563   enum {
7564     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7565     OP_VMRGHW,
7566     OP_VMRGLW,
7567     OP_VSPLTISW0,
7568     OP_VSPLTISW1,
7569     OP_VSPLTISW2,
7570     OP_VSPLTISW3,
7571     OP_VSLDOI4,
7572     OP_VSLDOI8,
7573     OP_VSLDOI12
7574   };
7575
7576   if (OpNum == OP_COPY) {
7577     if (LHSID == (1*9+2)*9+3) return LHS;
7578     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7579     return RHS;
7580   }
7581
7582   SDValue OpLHS, OpRHS;
7583   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7584   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7585
7586   int ShufIdxs[16];
7587   switch (OpNum) {
7588   default: llvm_unreachable("Unknown i32 permute!");
7589   case OP_VMRGHW:
7590     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7591     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7592     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7593     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7594     break;
7595   case OP_VMRGLW:
7596     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7597     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7598     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7599     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7600     break;
7601   case OP_VSPLTISW0:
7602     for (unsigned i = 0; i != 16; ++i)
7603       ShufIdxs[i] = (i&3)+0;
7604     break;
7605   case OP_VSPLTISW1:
7606     for (unsigned i = 0; i != 16; ++i)
7607       ShufIdxs[i] = (i&3)+4;
7608     break;
7609   case OP_VSPLTISW2:
7610     for (unsigned i = 0; i != 16; ++i)
7611       ShufIdxs[i] = (i&3)+8;
7612     break;
7613   case OP_VSPLTISW3:
7614     for (unsigned i = 0; i != 16; ++i)
7615       ShufIdxs[i] = (i&3)+12;
7616     break;
7617   case OP_VSLDOI4:
7618     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7619   case OP_VSLDOI8:
7620     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7621   case OP_VSLDOI12:
7622     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7623   }
7624   EVT VT = OpLHS.getValueType();
7625   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7626   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7627   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7628   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7629 }
7630
7631 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7632 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7633 /// return the code it can be lowered into.  Worst case, it can always be
7634 /// lowered into a vperm.
7635 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7636                                                SelectionDAG &DAG) const {
7637   SDLoc dl(Op);
7638   SDValue V1 = Op.getOperand(0);
7639   SDValue V2 = Op.getOperand(1);
7640   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7641   EVT VT = Op.getValueType();
7642   bool isLittleEndian = Subtarget.isLittleEndian();
7643
7644   unsigned ShiftElts, InsertAtByte;
7645   bool Swap;
7646   if (Subtarget.hasP9Vector() &&
7647       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7648                            isLittleEndian)) {
7649     if (Swap)
7650       std::swap(V1, V2);
7651     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7652     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7653     if (ShiftElts) {
7654       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7655                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7656       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7657                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7658       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7659     }
7660     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7661                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7662     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7663   }
7664
7665   if (Subtarget.hasVSX()) {
7666     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7667       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7668
7669       // If the source for the shuffle is a scalar_to_vector that came from a
7670       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7671       if (Subtarget.hasP9Vector() &&
7672           ((isLittleEndian && SplatIdx == 3) ||
7673            (!isLittleEndian && SplatIdx == 0))) {
7674         SDValue Src = V1.getOperand(0);
7675         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7676             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7677             Src.getOperand(0).hasOneUse())
7678           return V1;
7679       }
7680       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7681       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7682                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7683       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7684     }
7685
7686     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7687     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7688       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7689       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7690       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7691     }
7692   }
7693
7694   if (Subtarget.hasQPX()) {
7695     if (VT.getVectorNumElements() != 4)
7696       return SDValue();
7697
7698     if (V2.isUndef()) V2 = V1;
7699
7700     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7701     if (AlignIdx != -1) {
7702       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7703                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7704     } else if (SVOp->isSplat()) {
7705       int SplatIdx = SVOp->getSplatIndex();
7706       if (SplatIdx >= 4) {
7707         std::swap(V1, V2);
7708         SplatIdx -= 4;
7709       }
7710
7711       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7712                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7713     }
7714
7715     // Lower this into a qvgpci/qvfperm pair.
7716
7717     // Compute the qvgpci literal
7718     unsigned idx = 0;
7719     for (unsigned i = 0; i < 4; ++i) {
7720       int m = SVOp->getMaskElt(i);
7721       unsigned mm = m >= 0 ? (unsigned) m : i;
7722       idx |= mm << (3-i)*3;
7723     }
7724
7725     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7726                              DAG.getConstant(idx, dl, MVT::i32));
7727     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7728   }
7729
7730   // Cases that are handled by instructions that take permute immediates
7731   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7732   // selected by the instruction selector.
7733   if (V2.isUndef()) {
7734     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7735         PPC::isSplatShuffleMask(SVOp, 2) ||
7736         PPC::isSplatShuffleMask(SVOp, 4) ||
7737         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7738         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7739         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7740         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7741         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7742         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7743         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7744         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7745         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7746         (Subtarget.hasP8Altivec() && (
7747          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7748          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7749          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7750       return Op;
7751     }
7752   }
7753
7754   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7755   // and produce a fixed permutation.  If any of these match, do not lower to
7756   // VPERM.
7757   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7758   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7759       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7760       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7761       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7762       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7763       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7764       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7765       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7766       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7767       (Subtarget.hasP8Altivec() && (
7768        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7769        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7770        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7771     return Op;
7772
7773   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7774   // perfect shuffle table to emit an optimal matching sequence.
7775   ArrayRef<int> PermMask = SVOp->getMask();
7776
7777   unsigned PFIndexes[4];
7778   bool isFourElementShuffle = true;
7779   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7780     unsigned EltNo = 8;   // Start out undef.
7781     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7782       if (PermMask[i*4+j] < 0)
7783         continue;   // Undef, ignore it.
7784
7785       unsigned ByteSource = PermMask[i*4+j];
7786       if ((ByteSource & 3) != j) {
7787         isFourElementShuffle = false;
7788         break;
7789       }
7790
7791       if (EltNo == 8) {
7792         EltNo = ByteSource/4;
7793       } else if (EltNo != ByteSource/4) {
7794         isFourElementShuffle = false;
7795         break;
7796       }
7797     }
7798     PFIndexes[i] = EltNo;
7799   }
7800
7801   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7802   // perfect shuffle vector to determine if it is cost effective to do this as
7803   // discrete instructions, or whether we should use a vperm.
7804   // For now, we skip this for little endian until such time as we have a
7805   // little-endian perfect shuffle table.
7806   if (isFourElementShuffle && !isLittleEndian) {
7807     // Compute the index in the perfect shuffle table.
7808     unsigned PFTableIndex =
7809       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7810
7811     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7812     unsigned Cost  = (PFEntry >> 30);
7813
7814     // Determining when to avoid vperm is tricky.  Many things affect the cost
7815     // of vperm, particularly how many times the perm mask needs to be computed.
7816     // For example, if the perm mask can be hoisted out of a loop or is already
7817     // used (perhaps because there are multiple permutes with the same shuffle
7818     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7819     // the loop requires an extra register.
7820     //
7821     // As a compromise, we only emit discrete instructions if the shuffle can be
7822     // generated in 3 or fewer operations.  When we have loop information
7823     // available, if this block is within a loop, we should avoid using vperm
7824     // for 3-operation perms and use a constant pool load instead.
7825     if (Cost < 3)
7826       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7827   }
7828
7829   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7830   // vector that will get spilled to the constant pool.
7831   if (V2.isUndef()) V2 = V1;
7832
7833   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7834   // that it is in input element units, not in bytes.  Convert now.
7835
7836   // For little endian, the order of the input vectors is reversed, and
7837   // the permutation mask is complemented with respect to 31.  This is
7838   // necessary to produce proper semantics with the big-endian-biased vperm
7839   // instruction.
7840   EVT EltVT = V1.getValueType().getVectorElementType();
7841   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7842
7843   SmallVector<SDValue, 16> ResultMask;
7844   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7845     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7846
7847     for (unsigned j = 0; j != BytesPerElement; ++j)
7848       if (isLittleEndian)
7849         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7850                                              dl, MVT::i32));
7851       else
7852         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7853                                              MVT::i32));
7854   }
7855
7856   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7857   if (isLittleEndian)
7858     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7859                        V2, V1, VPermMask);
7860   else
7861     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7862                        V1, V2, VPermMask);
7863 }
7864
7865 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7866 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7867 /// information about the intrinsic.
7868 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7869                                  bool &isDot, const PPCSubtarget &Subtarget) {
7870   unsigned IntrinsicID =
7871       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7872   CompareOpc = -1;
7873   isDot = false;
7874   switch (IntrinsicID) {
7875   default:
7876     return false;
7877   // Comparison predicates.
7878   case Intrinsic::ppc_altivec_vcmpbfp_p:
7879     CompareOpc = 966;
7880     isDot = true;
7881     break;
7882   case Intrinsic::ppc_altivec_vcmpeqfp_p:
7883     CompareOpc = 198;
7884     isDot = true;
7885     break;
7886   case Intrinsic::ppc_altivec_vcmpequb_p:
7887     CompareOpc = 6;
7888     isDot = true;
7889     break;
7890   case Intrinsic::ppc_altivec_vcmpequh_p:
7891     CompareOpc = 70;
7892     isDot = true;
7893     break;
7894   case Intrinsic::ppc_altivec_vcmpequw_p:
7895     CompareOpc = 134;
7896     isDot = true;
7897     break;
7898   case Intrinsic::ppc_altivec_vcmpequd_p:
7899     if (Subtarget.hasP8Altivec()) {
7900       CompareOpc = 199;
7901       isDot = true;
7902     } else
7903       return false;
7904     break;
7905   case Intrinsic::ppc_altivec_vcmpneb_p:
7906   case Intrinsic::ppc_altivec_vcmpneh_p:
7907   case Intrinsic::ppc_altivec_vcmpnew_p:
7908   case Intrinsic::ppc_altivec_vcmpnezb_p:
7909   case Intrinsic::ppc_altivec_vcmpnezh_p:
7910   case Intrinsic::ppc_altivec_vcmpnezw_p:
7911     if (Subtarget.hasP9Altivec()) {
7912       switch (IntrinsicID) {
7913       default:
7914         llvm_unreachable("Unknown comparison intrinsic.");
7915       case Intrinsic::ppc_altivec_vcmpneb_p:
7916         CompareOpc = 7;
7917         break;
7918       case Intrinsic::ppc_altivec_vcmpneh_p:
7919         CompareOpc = 71;
7920         break;
7921       case Intrinsic::ppc_altivec_vcmpnew_p:
7922         CompareOpc = 135;
7923         break;
7924       case Intrinsic::ppc_altivec_vcmpnezb_p:
7925         CompareOpc = 263;
7926         break;
7927       case Intrinsic::ppc_altivec_vcmpnezh_p:
7928         CompareOpc = 327;
7929         break;
7930       case Intrinsic::ppc_altivec_vcmpnezw_p:
7931         CompareOpc = 391;
7932         break;
7933       }
7934       isDot = true;
7935     } else
7936       return false;
7937     break;
7938   case Intrinsic::ppc_altivec_vcmpgefp_p:
7939     CompareOpc = 454;
7940     isDot = true;
7941     break;
7942   case Intrinsic::ppc_altivec_vcmpgtfp_p:
7943     CompareOpc = 710;
7944     isDot = true;
7945     break;
7946   case Intrinsic::ppc_altivec_vcmpgtsb_p:
7947     CompareOpc = 774;
7948     isDot = true;
7949     break;
7950   case Intrinsic::ppc_altivec_vcmpgtsh_p:
7951     CompareOpc = 838;
7952     isDot = true;
7953     break;
7954   case Intrinsic::ppc_altivec_vcmpgtsw_p:
7955     CompareOpc = 902;
7956     isDot = true;
7957     break;
7958   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7959     if (Subtarget.hasP8Altivec()) {
7960       CompareOpc = 967;
7961       isDot = true;
7962     } else
7963       return false;
7964     break;
7965   case Intrinsic::ppc_altivec_vcmpgtub_p:
7966     CompareOpc = 518;
7967     isDot = true;
7968     break;
7969   case Intrinsic::ppc_altivec_vcmpgtuh_p:
7970     CompareOpc = 582;
7971     isDot = true;
7972     break;
7973   case Intrinsic::ppc_altivec_vcmpgtuw_p:
7974     CompareOpc = 646;
7975     isDot = true;
7976     break;
7977   case Intrinsic::ppc_altivec_vcmpgtud_p:
7978     if (Subtarget.hasP8Altivec()) {
7979       CompareOpc = 711;
7980       isDot = true;
7981     } else
7982       return false;
7983     break;
7984
7985   // VSX predicate comparisons use the same infrastructure
7986   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7987   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7988   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7989   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7990   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7991   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7992     if (Subtarget.hasVSX()) {
7993       switch (IntrinsicID) {
7994       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7995         CompareOpc = 99;
7996         break;
7997       case Intrinsic::ppc_vsx_xvcmpgedp_p:
7998         CompareOpc = 115;
7999         break;
8000       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8001         CompareOpc = 107;
8002         break;
8003       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8004         CompareOpc = 67;
8005         break;
8006       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8007         CompareOpc = 83;
8008         break;
8009       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8010         CompareOpc = 75;
8011         break;
8012       }
8013       isDot = true;
8014     } else
8015       return false;
8016     break;
8017
8018   // Normal Comparisons.
8019   case Intrinsic::ppc_altivec_vcmpbfp:
8020     CompareOpc = 966;
8021     break;
8022   case Intrinsic::ppc_altivec_vcmpeqfp:
8023     CompareOpc = 198;
8024     break;
8025   case Intrinsic::ppc_altivec_vcmpequb:
8026     CompareOpc = 6;
8027     break;
8028   case Intrinsic::ppc_altivec_vcmpequh:
8029     CompareOpc = 70;
8030     break;
8031   case Intrinsic::ppc_altivec_vcmpequw:
8032     CompareOpc = 134;
8033     break;
8034   case Intrinsic::ppc_altivec_vcmpequd:
8035     if (Subtarget.hasP8Altivec())
8036       CompareOpc = 199;
8037     else
8038       return false;
8039     break;
8040   case Intrinsic::ppc_altivec_vcmpneb:
8041   case Intrinsic::ppc_altivec_vcmpneh:
8042   case Intrinsic::ppc_altivec_vcmpnew:
8043   case Intrinsic::ppc_altivec_vcmpnezb:
8044   case Intrinsic::ppc_altivec_vcmpnezh:
8045   case Intrinsic::ppc_altivec_vcmpnezw:
8046     if (Subtarget.hasP9Altivec())
8047       switch (IntrinsicID) {
8048       default:
8049         llvm_unreachable("Unknown comparison intrinsic.");
8050       case Intrinsic::ppc_altivec_vcmpneb:
8051         CompareOpc = 7;
8052         break;
8053       case Intrinsic::ppc_altivec_vcmpneh:
8054         CompareOpc = 71;
8055         break;
8056       case Intrinsic::ppc_altivec_vcmpnew:
8057         CompareOpc = 135;
8058         break;
8059       case Intrinsic::ppc_altivec_vcmpnezb:
8060         CompareOpc = 263;
8061         break;
8062       case Intrinsic::ppc_altivec_vcmpnezh:
8063         CompareOpc = 327;
8064         break;
8065       case Intrinsic::ppc_altivec_vcmpnezw:
8066         CompareOpc = 391;
8067         break;
8068       }
8069     else
8070       return false;
8071     break;
8072   case Intrinsic::ppc_altivec_vcmpgefp:
8073     CompareOpc = 454;
8074     break;
8075   case Intrinsic::ppc_altivec_vcmpgtfp:
8076     CompareOpc = 710;
8077     break;
8078   case Intrinsic::ppc_altivec_vcmpgtsb:
8079     CompareOpc = 774;
8080     break;
8081   case Intrinsic::ppc_altivec_vcmpgtsh:
8082     CompareOpc = 838;
8083     break;
8084   case Intrinsic::ppc_altivec_vcmpgtsw:
8085     CompareOpc = 902;
8086     break;
8087   case Intrinsic::ppc_altivec_vcmpgtsd:
8088     if (Subtarget.hasP8Altivec())
8089       CompareOpc = 967;
8090     else
8091       return false;
8092     break;
8093   case Intrinsic::ppc_altivec_vcmpgtub:
8094     CompareOpc = 518;
8095     break;
8096   case Intrinsic::ppc_altivec_vcmpgtuh:
8097     CompareOpc = 582;
8098     break;
8099   case Intrinsic::ppc_altivec_vcmpgtuw:
8100     CompareOpc = 646;
8101     break;
8102   case Intrinsic::ppc_altivec_vcmpgtud:
8103     if (Subtarget.hasP8Altivec())
8104       CompareOpc = 711;
8105     else
8106       return false;
8107     break;
8108   }
8109   return true;
8110 }
8111
8112 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8113 /// lower, do it, otherwise return null.
8114 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8115                                                    SelectionDAG &DAG) const {
8116   unsigned IntrinsicID =
8117     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8118
8119   if (IntrinsicID == Intrinsic::thread_pointer) {
8120     // Reads the thread pointer register, used for __builtin_thread_pointer.
8121     bool is64bit = Subtarget.isPPC64();
8122     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8123                            is64bit ? MVT::i64 : MVT::i32);
8124   }
8125
8126   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8127   // opcode number of the comparison.
8128   SDLoc dl(Op);
8129   int CompareOpc;
8130   bool isDot;
8131   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8132     return SDValue();    // Don't custom lower most intrinsics.
8133
8134   // If this is a non-dot comparison, make the VCMP node and we are done.
8135   if (!isDot) {
8136     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8137                               Op.getOperand(1), Op.getOperand(2),
8138                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8139     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8140   }
8141
8142   // Create the PPCISD altivec 'dot' comparison node.
8143   SDValue Ops[] = {
8144     Op.getOperand(2),  // LHS
8145     Op.getOperand(3),  // RHS
8146     DAG.getConstant(CompareOpc, dl, MVT::i32)
8147   };
8148   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8149   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8150
8151   // Now that we have the comparison, emit a copy from the CR to a GPR.
8152   // This is flagged to the above dot comparison.
8153   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8154                                 DAG.getRegister(PPC::CR6, MVT::i32),
8155                                 CompNode.getValue(1));
8156
8157   // Unpack the result based on how the target uses it.
8158   unsigned BitNo;   // Bit # of CR6.
8159   bool InvertBit;   // Invert result?
8160   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8161   default:  // Can't happen, don't crash on invalid number though.
8162   case 0:   // Return the value of the EQ bit of CR6.
8163     BitNo = 0; InvertBit = false;
8164     break;
8165   case 1:   // Return the inverted value of the EQ bit of CR6.
8166     BitNo = 0; InvertBit = true;
8167     break;
8168   case 2:   // Return the value of the LT bit of CR6.
8169     BitNo = 2; InvertBit = false;
8170     break;
8171   case 3:   // Return the inverted value of the LT bit of CR6.
8172     BitNo = 2; InvertBit = true;
8173     break;
8174   }
8175
8176   // Shift the bit into the low position.
8177   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8178                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8179   // Isolate the bit.
8180   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8181                       DAG.getConstant(1, dl, MVT::i32));
8182
8183   // If we are supposed to, toggle the bit.
8184   if (InvertBit)
8185     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8186                         DAG.getConstant(1, dl, MVT::i32));
8187   return Flags;
8188 }
8189
8190 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8191                                                   SelectionDAG &DAG) const {
8192   SDLoc dl(Op);
8193   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8194   // instructions), but for smaller types, we need to first extend up to v2i32
8195   // before doing going farther.
8196   if (Op.getValueType() == MVT::v2i64) {
8197     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8198     if (ExtVT != MVT::v2i32) {
8199       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8200       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8201                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8202                                         ExtVT.getVectorElementType(), 4)));
8203       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8204       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8205                        DAG.getValueType(MVT::v2i32));
8206     }
8207
8208     return Op;
8209   }
8210
8211   return SDValue();
8212 }
8213
8214 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8215                                                  SelectionDAG &DAG) const {
8216   SDLoc dl(Op);
8217   // Create a stack slot that is 16-byte aligned.
8218   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8219   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8220   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8221   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8222
8223   // Store the input value into Value#0 of the stack slot.
8224   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8225                                MachinePointerInfo());
8226   // Load it out.
8227   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8228 }
8229
8230 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8231                                                   SelectionDAG &DAG) const {
8232   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8233          "Should only be called for ISD::INSERT_VECTOR_ELT");
8234   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8235   // We have legal lowering for constant indices but not for variable ones.
8236   if (C)
8237     return Op;
8238   return SDValue();
8239 }
8240
8241 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8242                                                    SelectionDAG &DAG) const {
8243   SDLoc dl(Op);
8244   SDNode *N = Op.getNode();
8245
8246   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8247          "Unknown extract_vector_elt type");
8248
8249   SDValue Value = N->getOperand(0);
8250
8251   // The first part of this is like the store lowering except that we don't
8252   // need to track the chain.
8253
8254   // The values are now known to be -1 (false) or 1 (true). To convert this
8255   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8256   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8257   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8258
8259   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8260   // understand how to form the extending load.
8261   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8262
8263   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8264
8265   // Now convert to an integer and store.
8266   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8267     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8268     Value);
8269
8270   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8271   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8272   MachinePointerInfo PtrInfo =
8273       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8274   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8275   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8276
8277   SDValue StoreChain = DAG.getEntryNode();
8278   SDValue Ops[] = {StoreChain,
8279                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8280                    Value, FIdx};
8281   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8282
8283   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8284     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8285
8286   // Extract the value requested.
8287   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8288   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8289   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8290
8291   SDValue IntVal =
8292       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8293
8294   if (!Subtarget.useCRBits())
8295     return IntVal;
8296
8297   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8298 }
8299
8300 /// Lowering for QPX v4i1 loads
8301 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8302                                            SelectionDAG &DAG) const {
8303   SDLoc dl(Op);
8304   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8305   SDValue LoadChain = LN->getChain();
8306   SDValue BasePtr = LN->getBasePtr();
8307
8308   if (Op.getValueType() == MVT::v4f64 ||
8309       Op.getValueType() == MVT::v4f32) {
8310     EVT MemVT = LN->getMemoryVT();
8311     unsigned Alignment = LN->getAlignment();
8312
8313     // If this load is properly aligned, then it is legal.
8314     if (Alignment >= MemVT.getStoreSize())
8315       return Op;
8316
8317     EVT ScalarVT = Op.getValueType().getScalarType(),
8318         ScalarMemVT = MemVT.getScalarType();
8319     unsigned Stride = ScalarMemVT.getStoreSize();
8320
8321     SDValue Vals[4], LoadChains[4];
8322     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8323       SDValue Load;
8324       if (ScalarVT != ScalarMemVT)
8325         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8326                               BasePtr,
8327                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8328                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8329                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8330       else
8331         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8332                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8333                            MinAlign(Alignment, Idx * Stride),
8334                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8335
8336       if (Idx == 0 && LN->isIndexed()) {
8337         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8338                "Unknown addressing mode on vector load");
8339         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8340                                   LN->getAddressingMode());
8341       }
8342
8343       Vals[Idx] = Load;
8344       LoadChains[Idx] = Load.getValue(1);
8345
8346       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8347                             DAG.getConstant(Stride, dl,
8348                                             BasePtr.getValueType()));
8349     }
8350
8351     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8352     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8353
8354     if (LN->isIndexed()) {
8355       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8356       return DAG.getMergeValues(RetOps, dl);
8357     }
8358
8359     SDValue RetOps[] = { Value, TF };
8360     return DAG.getMergeValues(RetOps, dl);
8361   }
8362
8363   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8364   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8365
8366   // To lower v4i1 from a byte array, we load the byte elements of the
8367   // vector and then reuse the BUILD_VECTOR logic.
8368
8369   SDValue VectElmts[4], VectElmtChains[4];
8370   for (unsigned i = 0; i < 4; ++i) {
8371     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8372     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8373
8374     VectElmts[i] = DAG.getExtLoad(
8375         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8376         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8377         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8378     VectElmtChains[i] = VectElmts[i].getValue(1);
8379   }
8380
8381   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8382   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8383
8384   SDValue RVals[] = { Value, LoadChain };
8385   return DAG.getMergeValues(RVals, dl);
8386 }
8387
8388 /// Lowering for QPX v4i1 stores
8389 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8390                                             SelectionDAG &DAG) const {
8391   SDLoc dl(Op);
8392   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8393   SDValue StoreChain = SN->getChain();
8394   SDValue BasePtr = SN->getBasePtr();
8395   SDValue Value = SN->getValue();
8396
8397   if (Value.getValueType() == MVT::v4f64 ||
8398       Value.getValueType() == MVT::v4f32) {
8399     EVT MemVT = SN->getMemoryVT();
8400     unsigned Alignment = SN->getAlignment();
8401
8402     // If this store is properly aligned, then it is legal.
8403     if (Alignment >= MemVT.getStoreSize())
8404       return Op;
8405
8406     EVT ScalarVT = Value.getValueType().getScalarType(),
8407         ScalarMemVT = MemVT.getScalarType();
8408     unsigned Stride = ScalarMemVT.getStoreSize();
8409
8410     SDValue Stores[4];
8411     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8412       SDValue Ex = DAG.getNode(
8413           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8414           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8415       SDValue Store;
8416       if (ScalarVT != ScalarMemVT)
8417         Store =
8418             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8419                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8420                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8421                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8422       else
8423         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8424                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8425                              MinAlign(Alignment, Idx * Stride),
8426                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8427
8428       if (Idx == 0 && SN->isIndexed()) {
8429         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8430                "Unknown addressing mode on vector store");
8431         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8432                                     SN->getAddressingMode());
8433       }
8434
8435       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8436                             DAG.getConstant(Stride, dl,
8437                                             BasePtr.getValueType()));
8438       Stores[Idx] = Store;
8439     }
8440
8441     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8442
8443     if (SN->isIndexed()) {
8444       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8445       return DAG.getMergeValues(RetOps, dl);
8446     }
8447
8448     return TF;
8449   }
8450
8451   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8452   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8453
8454   // The values are now known to be -1 (false) or 1 (true). To convert this
8455   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8456   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8457   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8458
8459   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8460   // understand how to form the extending load.
8461   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8462
8463   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8464
8465   // Now convert to an integer and store.
8466   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8467     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8468     Value);
8469
8470   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8471   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8472   MachinePointerInfo PtrInfo =
8473       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8474   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8475   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8476
8477   SDValue Ops[] = {StoreChain,
8478                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8479                    Value, FIdx};
8480   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8481
8482   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8483     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8484
8485   // Move data into the byte array.
8486   SDValue Loads[4], LoadChains[4];
8487   for (unsigned i = 0; i < 4; ++i) {
8488     unsigned Offset = 4*i;
8489     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8490     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8491
8492     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8493                            PtrInfo.getWithOffset(Offset));
8494     LoadChains[i] = Loads[i].getValue(1);
8495   }
8496
8497   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8498
8499   SDValue Stores[4];
8500   for (unsigned i = 0; i < 4; ++i) {
8501     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8502     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8503
8504     Stores[i] = DAG.getTruncStore(
8505         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8506         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8507         SN->getAAInfo());
8508   }
8509
8510   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8511
8512   return StoreChain;
8513 }
8514
8515 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8516   SDLoc dl(Op);
8517   if (Op.getValueType() == MVT::v4i32) {
8518     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8519
8520     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8521     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8522
8523     SDValue RHSSwap =   // = vrlw RHS, 16
8524       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8525
8526     // Shrinkify inputs to v8i16.
8527     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8528     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8529     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8530
8531     // Low parts multiplied together, generating 32-bit results (we ignore the
8532     // top parts).
8533     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8534                                         LHS, RHS, DAG, dl, MVT::v4i32);
8535
8536     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8537                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8538     // Shift the high parts up 16 bits.
8539     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8540                               Neg16, DAG, dl);
8541     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8542   } else if (Op.getValueType() == MVT::v8i16) {
8543     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8544
8545     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8546
8547     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8548                             LHS, RHS, Zero, DAG, dl);
8549   } else if (Op.getValueType() == MVT::v16i8) {
8550     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8551     bool isLittleEndian = Subtarget.isLittleEndian();
8552
8553     // Multiply the even 8-bit parts, producing 16-bit sums.
8554     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8555                                            LHS, RHS, DAG, dl, MVT::v8i16);
8556     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8557
8558     // Multiply the odd 8-bit parts, producing 16-bit sums.
8559     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8560                                           LHS, RHS, DAG, dl, MVT::v8i16);
8561     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8562
8563     // Merge the results together.  Because vmuleub and vmuloub are
8564     // instructions with a big-endian bias, we must reverse the
8565     // element numbering and reverse the meaning of "odd" and "even"
8566     // when generating little endian code.
8567     int Ops[16];
8568     for (unsigned i = 0; i != 8; ++i) {
8569       if (isLittleEndian) {
8570         Ops[i*2  ] = 2*i;
8571         Ops[i*2+1] = 2*i+16;
8572       } else {
8573         Ops[i*2  ] = 2*i+1;
8574         Ops[i*2+1] = 2*i+1+16;
8575       }
8576     }
8577     if (isLittleEndian)
8578       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8579     else
8580       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8581   } else {
8582     llvm_unreachable("Unknown mul to lower!");
8583   }
8584 }
8585
8586 /// LowerOperation - Provide custom lowering hooks for some operations.
8587 ///
8588 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8589   switch (Op.getOpcode()) {
8590   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8591   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8592   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8593   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8594   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8595   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8596   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8597   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8598   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8599   case ISD::VASTART:
8600     return LowerVASTART(Op, DAG);
8601
8602   case ISD::VAARG:
8603     return LowerVAARG(Op, DAG);
8604
8605   case ISD::VACOPY:
8606     return LowerVACOPY(Op, DAG);
8607
8608   case ISD::STACKRESTORE:
8609     return LowerSTACKRESTORE(Op, DAG);
8610
8611   case ISD::DYNAMIC_STACKALLOC:
8612     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8613
8614   case ISD::GET_DYNAMIC_AREA_OFFSET:
8615     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8616
8617   case ISD::EH_DWARF_CFA:
8618     return LowerEH_DWARF_CFA(Op, DAG);
8619
8620   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8621   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8622
8623   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8624   case ISD::STORE:              return LowerSTORE(Op, DAG);
8625   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8626   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8627   case ISD::FP_TO_UINT:
8628   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8629                                                       SDLoc(Op));
8630   case ISD::UINT_TO_FP:
8631   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8632   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8633
8634   // Lower 64-bit shifts.
8635   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8636   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8637   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8638
8639   // Vector-related lowering.
8640   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8641   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8642   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8643   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8644   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8645   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8646   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8647   case ISD::MUL:                return LowerMUL(Op, DAG);
8648
8649   // For counter-based loop handling.
8650   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8651
8652   // Frame & Return address.
8653   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8654   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8655   }
8656 }
8657
8658 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8659                                            SmallVectorImpl<SDValue>&Results,
8660                                            SelectionDAG &DAG) const {
8661   SDLoc dl(N);
8662   switch (N->getOpcode()) {
8663   default:
8664     llvm_unreachable("Do not know how to custom type legalize this operation!");
8665   case ISD::READCYCLECOUNTER: {
8666     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8667     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8668
8669     Results.push_back(RTB);
8670     Results.push_back(RTB.getValue(1));
8671     Results.push_back(RTB.getValue(2));
8672     break;
8673   }
8674   case ISD::INTRINSIC_W_CHAIN: {
8675     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8676         Intrinsic::ppc_is_decremented_ctr_nonzero)
8677       break;
8678
8679     assert(N->getValueType(0) == MVT::i1 &&
8680            "Unexpected result type for CTR decrement intrinsic");
8681     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8682                                  N->getValueType(0));
8683     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8684     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8685                                  N->getOperand(1));
8686
8687     Results.push_back(NewInt);
8688     Results.push_back(NewInt.getValue(1));
8689     break;
8690   }
8691   case ISD::VAARG: {
8692     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8693       return;
8694
8695     EVT VT = N->getValueType(0);
8696
8697     if (VT == MVT::i64) {
8698       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8699
8700       Results.push_back(NewNode);
8701       Results.push_back(NewNode.getValue(1));
8702     }
8703     return;
8704   }
8705   case ISD::FP_ROUND_INREG: {
8706     assert(N->getValueType(0) == MVT::ppcf128);
8707     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8708     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8709                              MVT::f64, N->getOperand(0),
8710                              DAG.getIntPtrConstant(0, dl));
8711     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8712                              MVT::f64, N->getOperand(0),
8713                              DAG.getIntPtrConstant(1, dl));
8714
8715     // Add the two halves of the long double in round-to-zero mode.
8716     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8717
8718     // We know the low half is about to be thrown away, so just use something
8719     // convenient.
8720     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8721                                 FPreg, FPreg));
8722     return;
8723   }
8724   case ISD::FP_TO_SINT:
8725   case ISD::FP_TO_UINT:
8726     // LowerFP_TO_INT() can only handle f32 and f64.
8727     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8728       return;
8729     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8730     return;
8731   }
8732 }
8733
8734 //===----------------------------------------------------------------------===//
8735 //  Other Lowering Code
8736 //===----------------------------------------------------------------------===//
8737
8738 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8739   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8740   Function *Func = Intrinsic::getDeclaration(M, Id);
8741   return Builder.CreateCall(Func, {});
8742 }
8743
8744 // The mappings for emitLeading/TrailingFence is taken from
8745 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8746 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8747                                          AtomicOrdering Ord, bool IsStore,
8748                                          bool IsLoad) const {
8749   if (Ord == AtomicOrdering::SequentiallyConsistent)
8750     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8751   if (isReleaseOrStronger(Ord))
8752     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8753   return nullptr;
8754 }
8755
8756 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8757                                           AtomicOrdering Ord, bool IsStore,
8758                                           bool IsLoad) const {
8759   if (IsLoad && isAcquireOrStronger(Ord))
8760     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8761   // FIXME: this is too conservative, a dependent branch + isync is enough.
8762   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8763   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8764   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8765   return nullptr;
8766 }
8767
8768 MachineBasicBlock *
8769 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8770                                     unsigned AtomicSize,
8771                                     unsigned BinOpcode,
8772                                     unsigned CmpOpcode,
8773                                     unsigned CmpPred) const {
8774   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8775   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8776
8777   auto LoadMnemonic = PPC::LDARX;
8778   auto StoreMnemonic = PPC::STDCX;
8779   switch (AtomicSize) {
8780   default:
8781     llvm_unreachable("Unexpected size of atomic entity");
8782   case 1:
8783     LoadMnemonic = PPC::LBARX;
8784     StoreMnemonic = PPC::STBCX;
8785     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8786     break;
8787   case 2:
8788     LoadMnemonic = PPC::LHARX;
8789     StoreMnemonic = PPC::STHCX;
8790     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8791     break;
8792   case 4:
8793     LoadMnemonic = PPC::LWARX;
8794     StoreMnemonic = PPC::STWCX;
8795     break;
8796   case 8:
8797     LoadMnemonic = PPC::LDARX;
8798     StoreMnemonic = PPC::STDCX;
8799     break;
8800   }
8801
8802   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8803   MachineFunction *F = BB->getParent();
8804   MachineFunction::iterator It = ++BB->getIterator();
8805
8806   unsigned dest = MI.getOperand(0).getReg();
8807   unsigned ptrA = MI.getOperand(1).getReg();
8808   unsigned ptrB = MI.getOperand(2).getReg();
8809   unsigned incr = MI.getOperand(3).getReg();
8810   DebugLoc dl = MI.getDebugLoc();
8811
8812   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8813   MachineBasicBlock *loop2MBB =
8814     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8815   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8816   F->insert(It, loopMBB);
8817   if (CmpOpcode)
8818     F->insert(It, loop2MBB);
8819   F->insert(It, exitMBB);
8820   exitMBB->splice(exitMBB->begin(), BB,
8821                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8822   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8823
8824   MachineRegisterInfo &RegInfo = F->getRegInfo();
8825   unsigned TmpReg = (!BinOpcode) ? incr :
8826     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8827                                            : &PPC::GPRCRegClass);
8828
8829   //  thisMBB:
8830   //   ...
8831   //   fallthrough --> loopMBB
8832   BB->addSuccessor(loopMBB);
8833
8834   //  loopMBB:
8835   //   l[wd]arx dest, ptr
8836   //   add r0, dest, incr
8837   //   st[wd]cx. r0, ptr
8838   //   bne- loopMBB
8839   //   fallthrough --> exitMBB
8840
8841   // For max/min...
8842   //  loopMBB:
8843   //   l[wd]arx dest, ptr
8844   //   cmpl?[wd] incr, dest
8845   //   bgt exitMBB
8846   //  loop2MBB:
8847   //   st[wd]cx. dest, ptr
8848   //   bne- loopMBB
8849   //   fallthrough --> exitMBB
8850
8851   BB = loopMBB;
8852   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8853     .addReg(ptrA).addReg(ptrB);
8854   if (BinOpcode)
8855     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8856   if (CmpOpcode) {
8857     // Signed comparisons of byte or halfword values must be sign-extended.
8858     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8859       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8860       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8861               ExtReg).addReg(dest);
8862       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8863         .addReg(incr).addReg(ExtReg);
8864     } else
8865       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8866         .addReg(incr).addReg(dest);
8867
8868     BuildMI(BB, dl, TII->get(PPC::BCC))
8869       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8870     BB->addSuccessor(loop2MBB);
8871     BB->addSuccessor(exitMBB);
8872     BB = loop2MBB;
8873   }
8874   BuildMI(BB, dl, TII->get(StoreMnemonic))
8875     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8876   BuildMI(BB, dl, TII->get(PPC::BCC))
8877     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8878   BB->addSuccessor(loopMBB);
8879   BB->addSuccessor(exitMBB);
8880
8881   //  exitMBB:
8882   //   ...
8883   BB = exitMBB;
8884   return BB;
8885 }
8886
8887 MachineBasicBlock *
8888 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8889                                             MachineBasicBlock *BB,
8890                                             bool is8bit, // operation
8891                                             unsigned BinOpcode,
8892                                             unsigned CmpOpcode,
8893                                             unsigned CmpPred) const {
8894   // If we support part-word atomic mnemonics, just use them
8895   if (Subtarget.hasPartwordAtomics())
8896     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8897                             CmpOpcode, CmpPred);
8898
8899   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8900   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8901   // In 64 bit mode we have to use 64 bits for addresses, even though the
8902   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8903   // registers without caring whether they're 32 or 64, but here we're
8904   // doing actual arithmetic on the addresses.
8905   bool is64bit = Subtarget.isPPC64();
8906   bool isLittleEndian = Subtarget.isLittleEndian();
8907   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8908
8909   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8910   MachineFunction *F = BB->getParent();
8911   MachineFunction::iterator It = ++BB->getIterator();
8912
8913   unsigned dest = MI.getOperand(0).getReg();
8914   unsigned ptrA = MI.getOperand(1).getReg();
8915   unsigned ptrB = MI.getOperand(2).getReg();
8916   unsigned incr = MI.getOperand(3).getReg();
8917   DebugLoc dl = MI.getDebugLoc();
8918
8919   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8920   MachineBasicBlock *loop2MBB =
8921     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8922   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8923   F->insert(It, loopMBB);
8924   if (CmpOpcode)
8925     F->insert(It, loop2MBB);
8926   F->insert(It, exitMBB);
8927   exitMBB->splice(exitMBB->begin(), BB,
8928                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8929   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8930
8931   MachineRegisterInfo &RegInfo = F->getRegInfo();
8932   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8933                                           : &PPC::GPRCRegClass;
8934   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8935   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8936   unsigned ShiftReg =
8937     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8938   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8939   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8940   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8941   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8942   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8943   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8944   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8945   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8946   unsigned Ptr1Reg;
8947   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8948
8949   //  thisMBB:
8950   //   ...
8951   //   fallthrough --> loopMBB
8952   BB->addSuccessor(loopMBB);
8953
8954   // The 4-byte load must be aligned, while a char or short may be
8955   // anywhere in the word.  Hence all this nasty bookkeeping code.
8956   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8957   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8958   //   xori shift, shift1, 24 [16]
8959   //   rlwinm ptr, ptr1, 0, 0, 29
8960   //   slw incr2, incr, shift
8961   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8962   //   slw mask, mask2, shift
8963   //  loopMBB:
8964   //   lwarx tmpDest, ptr
8965   //   add tmp, tmpDest, incr2
8966   //   andc tmp2, tmpDest, mask
8967   //   and tmp3, tmp, mask
8968   //   or tmp4, tmp3, tmp2
8969   //   stwcx. tmp4, ptr
8970   //   bne- loopMBB
8971   //   fallthrough --> exitMBB
8972   //   srw dest, tmpDest, shift
8973   if (ptrA != ZeroReg) {
8974     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8975     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8976       .addReg(ptrA).addReg(ptrB);
8977   } else {
8978     Ptr1Reg = ptrB;
8979   }
8980   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8981       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8982   if (!isLittleEndian)
8983     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8984         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8985   if (is64bit)
8986     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8987       .addReg(Ptr1Reg).addImm(0).addImm(61);
8988   else
8989     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8990       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8991   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8992       .addReg(incr).addReg(ShiftReg);
8993   if (is8bit)
8994     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8995   else {
8996     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8997     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8998   }
8999   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9000       .addReg(Mask2Reg).addReg(ShiftReg);
9001
9002   BB = loopMBB;
9003   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9004     .addReg(ZeroReg).addReg(PtrReg);
9005   if (BinOpcode)
9006     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9007       .addReg(Incr2Reg).addReg(TmpDestReg);
9008   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9009     .addReg(TmpDestReg).addReg(MaskReg);
9010   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9011     .addReg(TmpReg).addReg(MaskReg);
9012   if (CmpOpcode) {
9013     // For unsigned comparisons, we can directly compare the shifted values.
9014     // For signed comparisons we shift and sign extend.
9015     unsigned SReg = RegInfo.createVirtualRegister(RC);
9016     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9017       .addReg(TmpDestReg).addReg(MaskReg);
9018     unsigned ValueReg = SReg;
9019     unsigned CmpReg = Incr2Reg;
9020     if (CmpOpcode == PPC::CMPW) {
9021       ValueReg = RegInfo.createVirtualRegister(RC);
9022       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9023         .addReg(SReg).addReg(ShiftReg);
9024       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9025       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9026         .addReg(ValueReg);
9027       ValueReg = ValueSReg;
9028       CmpReg = incr;
9029     }
9030     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9031       .addReg(CmpReg).addReg(ValueReg);
9032     BuildMI(BB, dl, TII->get(PPC::BCC))
9033       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9034     BB->addSuccessor(loop2MBB);
9035     BB->addSuccessor(exitMBB);
9036     BB = loop2MBB;
9037   }
9038   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9039     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9040   BuildMI(BB, dl, TII->get(PPC::STWCX))
9041     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9042   BuildMI(BB, dl, TII->get(PPC::BCC))
9043     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9044   BB->addSuccessor(loopMBB);
9045   BB->addSuccessor(exitMBB);
9046
9047   //  exitMBB:
9048   //   ...
9049   BB = exitMBB;
9050   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9051     .addReg(ShiftReg);
9052   return BB;
9053 }
9054
9055 llvm::MachineBasicBlock *
9056 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9057                                     MachineBasicBlock *MBB) const {
9058   DebugLoc DL = MI.getDebugLoc();
9059   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9060
9061   MachineFunction *MF = MBB->getParent();
9062   MachineRegisterInfo &MRI = MF->getRegInfo();
9063
9064   const BasicBlock *BB = MBB->getBasicBlock();
9065   MachineFunction::iterator I = ++MBB->getIterator();
9066
9067   // Memory Reference
9068   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9069   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9070
9071   unsigned DstReg = MI.getOperand(0).getReg();
9072   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9073   assert(RC->hasType(MVT::i32) && "Invalid destination!");
9074   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9075   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9076
9077   MVT PVT = getPointerTy(MF->getDataLayout());
9078   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9079          "Invalid Pointer Size!");
9080   // For v = setjmp(buf), we generate
9081   //
9082   // thisMBB:
9083   //  SjLjSetup mainMBB
9084   //  bl mainMBB
9085   //  v_restore = 1
9086   //  b sinkMBB
9087   //
9088   // mainMBB:
9089   //  buf[LabelOffset] = LR
9090   //  v_main = 0
9091   //
9092   // sinkMBB:
9093   //  v = phi(main, restore)
9094   //
9095
9096   MachineBasicBlock *thisMBB = MBB;
9097   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9098   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9099   MF->insert(I, mainMBB);
9100   MF->insert(I, sinkMBB);
9101
9102   MachineInstrBuilder MIB;
9103
9104   // Transfer the remainder of BB and its successor edges to sinkMBB.
9105   sinkMBB->splice(sinkMBB->begin(), MBB,
9106                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9107   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9108
9109   // Note that the structure of the jmp_buf used here is not compatible
9110   // with that used by libc, and is not designed to be. Specifically, it
9111   // stores only those 'reserved' registers that LLVM does not otherwise
9112   // understand how to spill. Also, by convention, by the time this
9113   // intrinsic is called, Clang has already stored the frame address in the
9114   // first slot of the buffer and stack address in the third. Following the
9115   // X86 target code, we'll store the jump address in the second slot. We also
9116   // need to save the TOC pointer (R2) to handle jumps between shared
9117   // libraries, and that will be stored in the fourth slot. The thread
9118   // identifier (R13) is not affected.
9119
9120   // thisMBB:
9121   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9122   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9123   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9124
9125   // Prepare IP either in reg.
9126   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9127   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9128   unsigned BufReg = MI.getOperand(1).getReg();
9129
9130   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9131     setUsesTOCBasePtr(*MBB->getParent());
9132     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9133             .addReg(PPC::X2)
9134             .addImm(TOCOffset)
9135             .addReg(BufReg);
9136     MIB.setMemRefs(MMOBegin, MMOEnd);
9137   }
9138
9139   // Naked functions never have a base pointer, and so we use r1. For all
9140   // other functions, this decision must be delayed until during PEI.
9141   unsigned BaseReg;
9142   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9143     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9144   else
9145     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9146
9147   MIB = BuildMI(*thisMBB, MI, DL,
9148                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9149             .addReg(BaseReg)
9150             .addImm(BPOffset)
9151             .addReg(BufReg);
9152   MIB.setMemRefs(MMOBegin, MMOEnd);
9153
9154   // Setup
9155   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9156   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9157   MIB.addRegMask(TRI->getNoPreservedMask());
9158
9159   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9160
9161   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9162           .addMBB(mainMBB);
9163   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9164
9165   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9166   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9167
9168   // mainMBB:
9169   //  mainDstReg = 0
9170   MIB =
9171       BuildMI(mainMBB, DL,
9172               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9173
9174   // Store IP
9175   if (Subtarget.isPPC64()) {
9176     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9177             .addReg(LabelReg)
9178             .addImm(LabelOffset)
9179             .addReg(BufReg);
9180   } else {
9181     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9182             .addReg(LabelReg)
9183             .addImm(LabelOffset)
9184             .addReg(BufReg);
9185   }
9186
9187   MIB.setMemRefs(MMOBegin, MMOEnd);
9188
9189   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9190   mainMBB->addSuccessor(sinkMBB);
9191
9192   // sinkMBB:
9193   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9194           TII->get(PPC::PHI), DstReg)
9195     .addReg(mainDstReg).addMBB(mainMBB)
9196     .addReg(restoreDstReg).addMBB(thisMBB);
9197
9198   MI.eraseFromParent();
9199   return sinkMBB;
9200 }
9201
9202 MachineBasicBlock *
9203 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9204                                      MachineBasicBlock *MBB) const {
9205   DebugLoc DL = MI.getDebugLoc();
9206   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9207
9208   MachineFunction *MF = MBB->getParent();
9209   MachineRegisterInfo &MRI = MF->getRegInfo();
9210
9211   // Memory Reference
9212   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9213   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9214
9215   MVT PVT = getPointerTy(MF->getDataLayout());
9216   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9217          "Invalid Pointer Size!");
9218
9219   const TargetRegisterClass *RC =
9220     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9221   unsigned Tmp = MRI.createVirtualRegister(RC);
9222   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9223   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9224   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9225   unsigned BP =
9226       (PVT == MVT::i64)
9227           ? PPC::X30
9228           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9229                                                               : PPC::R30);
9230
9231   MachineInstrBuilder MIB;
9232
9233   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9234   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9235   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9236   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9237
9238   unsigned BufReg = MI.getOperand(0).getReg();
9239
9240   // Reload FP (the jumped-to function may not have had a
9241   // frame pointer, and if so, then its r31 will be restored
9242   // as necessary).
9243   if (PVT == MVT::i64) {
9244     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9245             .addImm(0)
9246             .addReg(BufReg);
9247   } else {
9248     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9249             .addImm(0)
9250             .addReg(BufReg);
9251   }
9252   MIB.setMemRefs(MMOBegin, MMOEnd);
9253
9254   // Reload IP
9255   if (PVT == MVT::i64) {
9256     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9257             .addImm(LabelOffset)
9258             .addReg(BufReg);
9259   } else {
9260     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9261             .addImm(LabelOffset)
9262             .addReg(BufReg);
9263   }
9264   MIB.setMemRefs(MMOBegin, MMOEnd);
9265
9266   // Reload SP
9267   if (PVT == MVT::i64) {
9268     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9269             .addImm(SPOffset)
9270             .addReg(BufReg);
9271   } else {
9272     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9273             .addImm(SPOffset)
9274             .addReg(BufReg);
9275   }
9276   MIB.setMemRefs(MMOBegin, MMOEnd);
9277
9278   // Reload BP
9279   if (PVT == MVT::i64) {
9280     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9281             .addImm(BPOffset)
9282             .addReg(BufReg);
9283   } else {
9284     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9285             .addImm(BPOffset)
9286             .addReg(BufReg);
9287   }
9288   MIB.setMemRefs(MMOBegin, MMOEnd);
9289
9290   // Reload TOC
9291   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9292     setUsesTOCBasePtr(*MBB->getParent());
9293     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9294             .addImm(TOCOffset)
9295             .addReg(BufReg);
9296
9297     MIB.setMemRefs(MMOBegin, MMOEnd);
9298   }
9299
9300   // Jump
9301   BuildMI(*MBB, MI, DL,
9302           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9303   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9304
9305   MI.eraseFromParent();
9306   return MBB;
9307 }
9308
9309 MachineBasicBlock *
9310 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9311                                                MachineBasicBlock *BB) const {
9312   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9313       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9314     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9315         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9316       // Call lowering should have added an r2 operand to indicate a dependence
9317       // on the TOC base pointer value. It can't however, because there is no
9318       // way to mark the dependence as implicit there, and so the stackmap code
9319       // will confuse it with a regular operand. Instead, add the dependence
9320       // here.
9321       setUsesTOCBasePtr(*BB->getParent());
9322       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9323     }
9324
9325     return emitPatchPoint(MI, BB);
9326   }
9327
9328   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9329       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9330     return emitEHSjLjSetJmp(MI, BB);
9331   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9332              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9333     return emitEHSjLjLongJmp(MI, BB);
9334   }
9335
9336   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9337
9338   // To "insert" these instructions we actually have to insert their
9339   // control-flow patterns.
9340   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9341   MachineFunction::iterator It = ++BB->getIterator();
9342
9343   MachineFunction *F = BB->getParent();
9344
9345   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9346        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9347        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9348     SmallVector<MachineOperand, 2> Cond;
9349     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9350         MI.getOpcode() == PPC::SELECT_CC_I8)
9351       Cond.push_back(MI.getOperand(4));
9352     else
9353       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9354     Cond.push_back(MI.getOperand(1));
9355
9356     DebugLoc dl = MI.getDebugLoc();
9357     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9358                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9359   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9360              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9361              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9362              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9363              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9364              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9365              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9366              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9367              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9368              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9369              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9370              MI.getOpcode() == PPC::SELECT_I4 ||
9371              MI.getOpcode() == PPC::SELECT_I8 ||
9372              MI.getOpcode() == PPC::SELECT_F4 ||
9373              MI.getOpcode() == PPC::SELECT_F8 ||
9374              MI.getOpcode() == PPC::SELECT_QFRC ||
9375              MI.getOpcode() == PPC::SELECT_QSRC ||
9376              MI.getOpcode() == PPC::SELECT_QBRC ||
9377              MI.getOpcode() == PPC::SELECT_VRRC ||
9378              MI.getOpcode() == PPC::SELECT_VSFRC ||
9379              MI.getOpcode() == PPC::SELECT_VSSRC ||
9380              MI.getOpcode() == PPC::SELECT_VSRC) {
9381     // The incoming instruction knows the destination vreg to set, the
9382     // condition code register to branch on, the true/false values to
9383     // select between, and a branch opcode to use.
9384
9385     //  thisMBB:
9386     //  ...
9387     //   TrueVal = ...
9388     //   cmpTY ccX, r1, r2
9389     //   bCC copy1MBB
9390     //   fallthrough --> copy0MBB
9391     MachineBasicBlock *thisMBB = BB;
9392     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9393     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9394     DebugLoc dl = MI.getDebugLoc();
9395     F->insert(It, copy0MBB);
9396     F->insert(It, sinkMBB);
9397
9398     // Transfer the remainder of BB and its successor edges to sinkMBB.
9399     sinkMBB->splice(sinkMBB->begin(), BB,
9400                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9401     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9402
9403     // Next, add the true and fallthrough blocks as its successors.
9404     BB->addSuccessor(copy0MBB);
9405     BB->addSuccessor(sinkMBB);
9406
9407     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9408         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9409         MI.getOpcode() == PPC::SELECT_QFRC ||
9410         MI.getOpcode() == PPC::SELECT_QSRC ||
9411         MI.getOpcode() == PPC::SELECT_QBRC ||
9412         MI.getOpcode() == PPC::SELECT_VRRC ||
9413         MI.getOpcode() == PPC::SELECT_VSFRC ||
9414         MI.getOpcode() == PPC::SELECT_VSSRC ||
9415         MI.getOpcode() == PPC::SELECT_VSRC) {
9416       BuildMI(BB, dl, TII->get(PPC::BC))
9417           .addReg(MI.getOperand(1).getReg())
9418           .addMBB(sinkMBB);
9419     } else {
9420       unsigned SelectPred = MI.getOperand(4).getImm();
9421       BuildMI(BB, dl, TII->get(PPC::BCC))
9422           .addImm(SelectPred)
9423           .addReg(MI.getOperand(1).getReg())
9424           .addMBB(sinkMBB);
9425     }
9426
9427     //  copy0MBB:
9428     //   %FalseValue = ...
9429     //   # fallthrough to sinkMBB
9430     BB = copy0MBB;
9431
9432     // Update machine-CFG edges
9433     BB->addSuccessor(sinkMBB);
9434
9435     //  sinkMBB:
9436     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9437     //  ...
9438     BB = sinkMBB;
9439     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9440         .addReg(MI.getOperand(3).getReg())
9441         .addMBB(copy0MBB)
9442         .addReg(MI.getOperand(2).getReg())
9443         .addMBB(thisMBB);
9444   } else if (MI.getOpcode() == PPC::ReadTB) {
9445     // To read the 64-bit time-base register on a 32-bit target, we read the
9446     // two halves. Should the counter have wrapped while it was being read, we
9447     // need to try again.
9448     // ...
9449     // readLoop:
9450     // mfspr Rx,TBU # load from TBU
9451     // mfspr Ry,TB  # load from TB
9452     // mfspr Rz,TBU # load from TBU
9453     // cmpw crX,Rx,Rz # check if 'old'='new'
9454     // bne readLoop   # branch if they're not equal
9455     // ...
9456
9457     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9458     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9459     DebugLoc dl = MI.getDebugLoc();
9460     F->insert(It, readMBB);
9461     F->insert(It, sinkMBB);
9462
9463     // Transfer the remainder of BB and its successor edges to sinkMBB.
9464     sinkMBB->splice(sinkMBB->begin(), BB,
9465                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9466     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9467
9468     BB->addSuccessor(readMBB);
9469     BB = readMBB;
9470
9471     MachineRegisterInfo &RegInfo = F->getRegInfo();
9472     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9473     unsigned LoReg = MI.getOperand(0).getReg();
9474     unsigned HiReg = MI.getOperand(1).getReg();
9475
9476     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9477     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9478     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9479
9480     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9481
9482     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9483       .addReg(HiReg).addReg(ReadAgainReg);
9484     BuildMI(BB, dl, TII->get(PPC::BCC))
9485       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9486
9487     BB->addSuccessor(readMBB);
9488     BB->addSuccessor(sinkMBB);
9489   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9490     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9491   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9492     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9493   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9494     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9495   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9496     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9497
9498   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9499     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9500   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9501     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9502   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9503     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9504   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9505     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9506
9507   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9508     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9509   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9510     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9511   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9512     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9513   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9514     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9515
9516   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9517     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9518   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9519     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9520   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9521     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9522   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9523     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9524
9525   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9526     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9527   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9528     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9529   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9530     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9531   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9532     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9533
9534   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9535     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9536   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9537     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9538   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9539     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9540   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9541     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9542
9543   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9544     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9545   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9546     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9547   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9548     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9549   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9550     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9551
9552   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9553     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9554   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9555     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9556   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9557     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9558   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9559     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9560
9561   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9562     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9563   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9564     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9565   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9566     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9567   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9568     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9569
9570   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9571     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9572   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9573     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9574   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9575     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9576   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9577     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9578
9579   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9580     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9581   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9582     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9583   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9584     BB = EmitAtomicBinary(MI, BB, 4, 0);
9585   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9586     BB = EmitAtomicBinary(MI, BB, 8, 0);
9587   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9588            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9589            (Subtarget.hasPartwordAtomics() &&
9590             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9591            (Subtarget.hasPartwordAtomics() &&
9592             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9593     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9594
9595     auto LoadMnemonic = PPC::LDARX;
9596     auto StoreMnemonic = PPC::STDCX;
9597     switch (MI.getOpcode()) {
9598     default:
9599       llvm_unreachable("Compare and swap of unknown size");
9600     case PPC::ATOMIC_CMP_SWAP_I8:
9601       LoadMnemonic = PPC::LBARX;
9602       StoreMnemonic = PPC::STBCX;
9603       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9604       break;
9605     case PPC::ATOMIC_CMP_SWAP_I16:
9606       LoadMnemonic = PPC::LHARX;
9607       StoreMnemonic = PPC::STHCX;
9608       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9609       break;
9610     case PPC::ATOMIC_CMP_SWAP_I32:
9611       LoadMnemonic = PPC::LWARX;
9612       StoreMnemonic = PPC::STWCX;
9613       break;
9614     case PPC::ATOMIC_CMP_SWAP_I64:
9615       LoadMnemonic = PPC::LDARX;
9616       StoreMnemonic = PPC::STDCX;
9617       break;
9618     }
9619     unsigned dest = MI.getOperand(0).getReg();
9620     unsigned ptrA = MI.getOperand(1).getReg();
9621     unsigned ptrB = MI.getOperand(2).getReg();
9622     unsigned oldval = MI.getOperand(3).getReg();
9623     unsigned newval = MI.getOperand(4).getReg();
9624     DebugLoc dl = MI.getDebugLoc();
9625
9626     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9627     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9628     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9629     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9630     F->insert(It, loop1MBB);
9631     F->insert(It, loop2MBB);
9632     F->insert(It, midMBB);
9633     F->insert(It, exitMBB);
9634     exitMBB->splice(exitMBB->begin(), BB,
9635                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9636     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9637
9638     //  thisMBB:
9639     //   ...
9640     //   fallthrough --> loopMBB
9641     BB->addSuccessor(loop1MBB);
9642
9643     // loop1MBB:
9644     //   l[bhwd]arx dest, ptr
9645     //   cmp[wd] dest, oldval
9646     //   bne- midMBB
9647     // loop2MBB:
9648     //   st[bhwd]cx. newval, ptr
9649     //   bne- loopMBB
9650     //   b exitBB
9651     // midMBB:
9652     //   st[bhwd]cx. dest, ptr
9653     // exitBB:
9654     BB = loop1MBB;
9655     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9656       .addReg(ptrA).addReg(ptrB);
9657     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9658       .addReg(oldval).addReg(dest);
9659     BuildMI(BB, dl, TII->get(PPC::BCC))
9660       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9661     BB->addSuccessor(loop2MBB);
9662     BB->addSuccessor(midMBB);
9663
9664     BB = loop2MBB;
9665     BuildMI(BB, dl, TII->get(StoreMnemonic))
9666       .addReg(newval).addReg(ptrA).addReg(ptrB);
9667     BuildMI(BB, dl, TII->get(PPC::BCC))
9668       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9669     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9670     BB->addSuccessor(loop1MBB);
9671     BB->addSuccessor(exitMBB);
9672
9673     BB = midMBB;
9674     BuildMI(BB, dl, TII->get(StoreMnemonic))
9675       .addReg(dest).addReg(ptrA).addReg(ptrB);
9676     BB->addSuccessor(exitMBB);
9677
9678     //  exitMBB:
9679     //   ...
9680     BB = exitMBB;
9681   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9682              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9683     // We must use 64-bit registers for addresses when targeting 64-bit,
9684     // since we're actually doing arithmetic on them.  Other registers
9685     // can be 32-bit.
9686     bool is64bit = Subtarget.isPPC64();
9687     bool isLittleEndian = Subtarget.isLittleEndian();
9688     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9689
9690     unsigned dest = MI.getOperand(0).getReg();
9691     unsigned ptrA = MI.getOperand(1).getReg();
9692     unsigned ptrB = MI.getOperand(2).getReg();
9693     unsigned oldval = MI.getOperand(3).getReg();
9694     unsigned newval = MI.getOperand(4).getReg();
9695     DebugLoc dl = MI.getDebugLoc();
9696
9697     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9698     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9699     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9700     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9701     F->insert(It, loop1MBB);
9702     F->insert(It, loop2MBB);
9703     F->insert(It, midMBB);
9704     F->insert(It, exitMBB);
9705     exitMBB->splice(exitMBB->begin(), BB,
9706                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9707     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9708
9709     MachineRegisterInfo &RegInfo = F->getRegInfo();
9710     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9711                                             : &PPC::GPRCRegClass;
9712     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9713     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9714     unsigned ShiftReg =
9715       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9716     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9717     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9718     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9719     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9720     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9721     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9722     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9723     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9724     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9725     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9726     unsigned Ptr1Reg;
9727     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9728     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9729     //  thisMBB:
9730     //   ...
9731     //   fallthrough --> loopMBB
9732     BB->addSuccessor(loop1MBB);
9733
9734     // The 4-byte load must be aligned, while a char or short may be
9735     // anywhere in the word.  Hence all this nasty bookkeeping code.
9736     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9737     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9738     //   xori shift, shift1, 24 [16]
9739     //   rlwinm ptr, ptr1, 0, 0, 29
9740     //   slw newval2, newval, shift
9741     //   slw oldval2, oldval,shift
9742     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9743     //   slw mask, mask2, shift
9744     //   and newval3, newval2, mask
9745     //   and oldval3, oldval2, mask
9746     // loop1MBB:
9747     //   lwarx tmpDest, ptr
9748     //   and tmp, tmpDest, mask
9749     //   cmpw tmp, oldval3
9750     //   bne- midMBB
9751     // loop2MBB:
9752     //   andc tmp2, tmpDest, mask
9753     //   or tmp4, tmp2, newval3
9754     //   stwcx. tmp4, ptr
9755     //   bne- loop1MBB
9756     //   b exitBB
9757     // midMBB:
9758     //   stwcx. tmpDest, ptr
9759     // exitBB:
9760     //   srw dest, tmpDest, shift
9761     if (ptrA != ZeroReg) {
9762       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9763       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9764         .addReg(ptrA).addReg(ptrB);
9765     } else {
9766       Ptr1Reg = ptrB;
9767     }
9768     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9769         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9770     if (!isLittleEndian)
9771       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9772           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9773     if (is64bit)
9774       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9775         .addReg(Ptr1Reg).addImm(0).addImm(61);
9776     else
9777       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9778         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9779     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9780         .addReg(newval).addReg(ShiftReg);
9781     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9782         .addReg(oldval).addReg(ShiftReg);
9783     if (is8bit)
9784       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9785     else {
9786       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9787       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9788         .addReg(Mask3Reg).addImm(65535);
9789     }
9790     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9791         .addReg(Mask2Reg).addReg(ShiftReg);
9792     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9793         .addReg(NewVal2Reg).addReg(MaskReg);
9794     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9795         .addReg(OldVal2Reg).addReg(MaskReg);
9796
9797     BB = loop1MBB;
9798     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9799         .addReg(ZeroReg).addReg(PtrReg);
9800     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9801         .addReg(TmpDestReg).addReg(MaskReg);
9802     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9803         .addReg(TmpReg).addReg(OldVal3Reg);
9804     BuildMI(BB, dl, TII->get(PPC::BCC))
9805         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9806     BB->addSuccessor(loop2MBB);
9807     BB->addSuccessor(midMBB);
9808
9809     BB = loop2MBB;
9810     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9811         .addReg(TmpDestReg).addReg(MaskReg);
9812     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9813         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9814     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9815         .addReg(ZeroReg).addReg(PtrReg);
9816     BuildMI(BB, dl, TII->get(PPC::BCC))
9817       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9818     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9819     BB->addSuccessor(loop1MBB);
9820     BB->addSuccessor(exitMBB);
9821
9822     BB = midMBB;
9823     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9824       .addReg(ZeroReg).addReg(PtrReg);
9825     BB->addSuccessor(exitMBB);
9826
9827     //  exitMBB:
9828     //   ...
9829     BB = exitMBB;
9830     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9831       .addReg(ShiftReg);
9832   } else if (MI.getOpcode() == PPC::FADDrtz) {
9833     // This pseudo performs an FADD with rounding mode temporarily forced
9834     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9835     // is not modeled at the SelectionDAG level.
9836     unsigned Dest = MI.getOperand(0).getReg();
9837     unsigned Src1 = MI.getOperand(1).getReg();
9838     unsigned Src2 = MI.getOperand(2).getReg();
9839     DebugLoc dl = MI.getDebugLoc();
9840
9841     MachineRegisterInfo &RegInfo = F->getRegInfo();
9842     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9843
9844     // Save FPSCR value.
9845     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9846
9847     // Set rounding mode to round-to-zero.
9848     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9849     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9850
9851     // Perform addition.
9852     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9853
9854     // Restore FPSCR value.
9855     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9856   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9857              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9858              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9859              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9860     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9861                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9862                           ? PPC::ANDIo8
9863                           : PPC::ANDIo;
9864     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9865                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9866
9867     MachineRegisterInfo &RegInfo = F->getRegInfo();
9868     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9869                                                   &PPC::GPRCRegClass :
9870                                                   &PPC::G8RCRegClass);
9871
9872     DebugLoc dl = MI.getDebugLoc();
9873     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9874         .addReg(MI.getOperand(1).getReg())
9875         .addImm(1);
9876     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9877             MI.getOperand(0).getReg())
9878         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9879   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9880     DebugLoc Dl = MI.getDebugLoc();
9881     MachineRegisterInfo &RegInfo = F->getRegInfo();
9882     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9883     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9884     return BB;
9885   } else {
9886     llvm_unreachable("Unexpected instr type to insert");
9887   }
9888
9889   MI.eraseFromParent(); // The pseudo instruction is gone now.
9890   return BB;
9891 }
9892
9893 //===----------------------------------------------------------------------===//
9894 // Target Optimization Hooks
9895 //===----------------------------------------------------------------------===//
9896
9897 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9898   // For the estimates, convergence is quadratic, so we essentially double the
9899   // number of digits correct after every iteration. For both FRE and FRSQRTE,
9900   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9901   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9902   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9903   if (VT.getScalarType() == MVT::f64)
9904     RefinementSteps++;
9905   return RefinementSteps;
9906 }
9907
9908 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9909                                            int Enabled, int &RefinementSteps,
9910                                            bool &UseOneConstNR,
9911                                            bool Reciprocal) const {
9912   EVT VT = Operand.getValueType();
9913   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9914       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9915       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9916       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9917       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9918       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9919     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9920       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9921
9922     UseOneConstNR = true;
9923     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9924   }
9925   return SDValue();
9926 }
9927
9928 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9929                                             int Enabled,
9930                                             int &RefinementSteps) const {
9931   EVT VT = Operand.getValueType();
9932   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9933       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9934       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9935       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9936       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9937       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9938     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9939       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9940     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9941   }
9942   return SDValue();
9943 }
9944
9945 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9946   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9947   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9948   // enabled for division), this functionality is redundant with the default
9949   // combiner logic (once the division -> reciprocal/multiply transformation
9950   // has taken place). As a result, this matters more for older cores than for
9951   // newer ones.
9952
9953   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9954   // reciprocal if there are two or more FDIVs (for embedded cores with only
9955   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9956   switch (Subtarget.getDarwinDirective()) {
9957   default:
9958     return 3;
9959   case PPC::DIR_440:
9960   case PPC::DIR_A2:
9961   case PPC::DIR_E500mc:
9962   case PPC::DIR_E5500:
9963     return 2;
9964   }
9965 }
9966
9967 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9968 // collapsed, and so we need to look through chains of them.
9969 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9970                                      int64_t& Offset, SelectionDAG &DAG) {
9971   if (DAG.isBaseWithConstantOffset(Loc)) {
9972     Base = Loc.getOperand(0);
9973     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9974
9975     // The base might itself be a base plus an offset, and if so, accumulate
9976     // that as well.
9977     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9978   }
9979 }
9980
9981 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9982                             unsigned Bytes, int Dist,
9983                             SelectionDAG &DAG) {
9984   if (VT.getSizeInBits() / 8 != Bytes)
9985     return false;
9986
9987   SDValue BaseLoc = Base->getBasePtr();
9988   if (Loc.getOpcode() == ISD::FrameIndex) {
9989     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9990       return false;
9991     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9992     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9993     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9994     int FS  = MFI.getObjectSize(FI);
9995     int BFS = MFI.getObjectSize(BFI);
9996     if (FS != BFS || FS != (int)Bytes) return false;
9997     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9998   }
9999
10000   SDValue Base1 = Loc, Base2 = BaseLoc;
10001   int64_t Offset1 = 0, Offset2 = 0;
10002   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10003   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10004   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10005     return true;
10006
10007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10008   const GlobalValue *GV1 = nullptr;
10009   const GlobalValue *GV2 = nullptr;
10010   Offset1 = 0;
10011   Offset2 = 0;
10012   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10013   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10014   if (isGA1 && isGA2 && GV1 == GV2)
10015     return Offset1 == (Offset2 + Dist*Bytes);
10016   return false;
10017 }
10018
10019 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10020 // not enforce equality of the chain operands.
10021 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10022                             unsigned Bytes, int Dist,
10023                             SelectionDAG &DAG) {
10024   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10025     EVT VT = LS->getMemoryVT();
10026     SDValue Loc = LS->getBasePtr();
10027     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10028   }
10029
10030   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10031     EVT VT;
10032     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10033     default: return false;
10034     case Intrinsic::ppc_qpx_qvlfd:
10035     case Intrinsic::ppc_qpx_qvlfda:
10036       VT = MVT::v4f64;
10037       break;
10038     case Intrinsic::ppc_qpx_qvlfs:
10039     case Intrinsic::ppc_qpx_qvlfsa:
10040       VT = MVT::v4f32;
10041       break;
10042     case Intrinsic::ppc_qpx_qvlfcd:
10043     case Intrinsic::ppc_qpx_qvlfcda:
10044       VT = MVT::v2f64;
10045       break;
10046     case Intrinsic::ppc_qpx_qvlfcs:
10047     case Intrinsic::ppc_qpx_qvlfcsa:
10048       VT = MVT::v2f32;
10049       break;
10050     case Intrinsic::ppc_qpx_qvlfiwa:
10051     case Intrinsic::ppc_qpx_qvlfiwz:
10052     case Intrinsic::ppc_altivec_lvx:
10053     case Intrinsic::ppc_altivec_lvxl:
10054     case Intrinsic::ppc_vsx_lxvw4x:
10055     case Intrinsic::ppc_vsx_lxvw4x_be:
10056       VT = MVT::v4i32;
10057       break;
10058     case Intrinsic::ppc_vsx_lxvd2x:
10059     case Intrinsic::ppc_vsx_lxvd2x_be:
10060       VT = MVT::v2f64;
10061       break;
10062     case Intrinsic::ppc_altivec_lvebx:
10063       VT = MVT::i8;
10064       break;
10065     case Intrinsic::ppc_altivec_lvehx:
10066       VT = MVT::i16;
10067       break;
10068     case Intrinsic::ppc_altivec_lvewx:
10069       VT = MVT::i32;
10070       break;
10071     }
10072
10073     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10074   }
10075
10076   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10077     EVT VT;
10078     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10079     default: return false;
10080     case Intrinsic::ppc_qpx_qvstfd:
10081     case Intrinsic::ppc_qpx_qvstfda:
10082       VT = MVT::v4f64;
10083       break;
10084     case Intrinsic::ppc_qpx_qvstfs:
10085     case Intrinsic::ppc_qpx_qvstfsa:
10086       VT = MVT::v4f32;
10087       break;
10088     case Intrinsic::ppc_qpx_qvstfcd:
10089     case Intrinsic::ppc_qpx_qvstfcda:
10090       VT = MVT::v2f64;
10091       break;
10092     case Intrinsic::ppc_qpx_qvstfcs:
10093     case Intrinsic::ppc_qpx_qvstfcsa:
10094       VT = MVT::v2f32;
10095       break;
10096     case Intrinsic::ppc_qpx_qvstfiw:
10097     case Intrinsic::ppc_qpx_qvstfiwa:
10098     case Intrinsic::ppc_altivec_stvx:
10099     case Intrinsic::ppc_altivec_stvxl:
10100     case Intrinsic::ppc_vsx_stxvw4x:
10101       VT = MVT::v4i32;
10102       break;
10103     case Intrinsic::ppc_vsx_stxvd2x:
10104       VT = MVT::v2f64;
10105       break;
10106     case Intrinsic::ppc_vsx_stxvw4x_be:
10107       VT = MVT::v4i32;
10108       break;
10109     case Intrinsic::ppc_vsx_stxvd2x_be:
10110       VT = MVT::v2f64;
10111       break;
10112     case Intrinsic::ppc_altivec_stvebx:
10113       VT = MVT::i8;
10114       break;
10115     case Intrinsic::ppc_altivec_stvehx:
10116       VT = MVT::i16;
10117       break;
10118     case Intrinsic::ppc_altivec_stvewx:
10119       VT = MVT::i32;
10120       break;
10121     }
10122
10123     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10124   }
10125
10126   return false;
10127 }
10128
10129 // Return true is there is a nearyby consecutive load to the one provided
10130 // (regardless of alignment). We search up and down the chain, looking though
10131 // token factors and other loads (but nothing else). As a result, a true result
10132 // indicates that it is safe to create a new consecutive load adjacent to the
10133 // load provided.
10134 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10135   SDValue Chain = LD->getChain();
10136   EVT VT = LD->getMemoryVT();
10137
10138   SmallSet<SDNode *, 16> LoadRoots;
10139   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10140   SmallSet<SDNode *, 16> Visited;
10141
10142   // First, search up the chain, branching to follow all token-factor operands.
10143   // If we find a consecutive load, then we're done, otherwise, record all
10144   // nodes just above the top-level loads and token factors.
10145   while (!Queue.empty()) {
10146     SDNode *ChainNext = Queue.pop_back_val();
10147     if (!Visited.insert(ChainNext).second)
10148       continue;
10149
10150     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10151       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10152         return true;
10153
10154       if (!Visited.count(ChainLD->getChain().getNode()))
10155         Queue.push_back(ChainLD->getChain().getNode());
10156     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10157       for (const SDUse &O : ChainNext->ops())
10158         if (!Visited.count(O.getNode()))
10159           Queue.push_back(O.getNode());
10160     } else
10161       LoadRoots.insert(ChainNext);
10162   }
10163
10164   // Second, search down the chain, starting from the top-level nodes recorded
10165   // in the first phase. These top-level nodes are the nodes just above all
10166   // loads and token factors. Starting with their uses, recursively look though
10167   // all loads (just the chain uses) and token factors to find a consecutive
10168   // load.
10169   Visited.clear();
10170   Queue.clear();
10171
10172   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10173        IE = LoadRoots.end(); I != IE; ++I) {
10174     Queue.push_back(*I);
10175
10176     while (!Queue.empty()) {
10177       SDNode *LoadRoot = Queue.pop_back_val();
10178       if (!Visited.insert(LoadRoot).second)
10179         continue;
10180
10181       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10182         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10183           return true;
10184
10185       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10186            UE = LoadRoot->use_end(); UI != UE; ++UI)
10187         if (((isa<MemSDNode>(*UI) &&
10188             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10189             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10190           Queue.push_back(*UI);
10191     }
10192   }
10193
10194   return false;
10195 }
10196
10197 /// This function is called when we have proved that a SETCC node can be replaced
10198 /// by subtraction (and other supporting instructions) so that the result of
10199 /// comparison is kept in a GPR instead of CR. This function is purely for
10200 /// codegen purposes and has some flags to guide the codegen process.
10201 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10202                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10203   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10204
10205   // Zero extend the operands to the largest legal integer. Originally, they
10206   // must be of a strictly smaller size.
10207   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10208                          DAG.getConstant(Size, DL, MVT::i32));
10209   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10210                          DAG.getConstant(Size, DL, MVT::i32));
10211
10212   // Swap if needed. Depends on the condition code.
10213   if (Swap)
10214     std::swap(Op0, Op1);
10215
10216   // Subtract extended integers.
10217   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10218
10219   // Move the sign bit to the least significant position and zero out the rest.
10220   // Now the least significant bit carries the result of original comparison.
10221   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10222                              DAG.getConstant(Size - 1, DL, MVT::i32));
10223   auto Final = Shifted;
10224
10225   // Complement the result if needed. Based on the condition code.
10226   if (Complement)
10227     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10228                         DAG.getConstant(1, DL, MVT::i64));
10229
10230   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10231 }
10232
10233 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10234                                                   DAGCombinerInfo &DCI) const {
10235   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10236
10237   SelectionDAG &DAG = DCI.DAG;
10238   SDLoc DL(N);
10239
10240   // Size of integers being compared has a critical role in the following
10241   // analysis, so we prefer to do this when all types are legal.
10242   if (!DCI.isAfterLegalizeVectorOps())
10243     return SDValue();
10244
10245   // If all users of SETCC extend its value to a legal integer type
10246   // then we replace SETCC with a subtraction
10247   for (SDNode::use_iterator UI = N->use_begin(),
10248        UE = N->use_end(); UI != UE; ++UI) {
10249     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10250       return SDValue();
10251   }
10252
10253   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10254   auto OpSize = N->getOperand(0).getValueSizeInBits();
10255
10256   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10257
10258   if (OpSize < Size) {
10259     switch (CC) {
10260     default: break;
10261     case ISD::SETULT:
10262       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10263     case ISD::SETULE:
10264       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10265     case ISD::SETUGT:
10266       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10267     case ISD::SETUGE:
10268       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10269     }
10270   }
10271
10272   return SDValue();
10273 }
10274
10275 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10276                                                   DAGCombinerInfo &DCI) const {
10277   SelectionDAG &DAG = DCI.DAG;
10278   SDLoc dl(N);
10279
10280   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10281   // If we're tracking CR bits, we need to be careful that we don't have:
10282   //   trunc(binary-ops(zext(x), zext(y)))
10283   // or
10284   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10285   // such that we're unnecessarily moving things into GPRs when it would be
10286   // better to keep them in CR bits.
10287
10288   // Note that trunc here can be an actual i1 trunc, or can be the effective
10289   // truncation that comes from a setcc or select_cc.
10290   if (N->getOpcode() == ISD::TRUNCATE &&
10291       N->getValueType(0) != MVT::i1)
10292     return SDValue();
10293
10294   if (N->getOperand(0).getValueType() != MVT::i32 &&
10295       N->getOperand(0).getValueType() != MVT::i64)
10296     return SDValue();
10297
10298   if (N->getOpcode() == ISD::SETCC ||
10299       N->getOpcode() == ISD::SELECT_CC) {
10300     // If we're looking at a comparison, then we need to make sure that the
10301     // high bits (all except for the first) don't matter the result.
10302     ISD::CondCode CC =
10303       cast<CondCodeSDNode>(N->getOperand(
10304         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10305     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10306
10307     if (ISD::isSignedIntSetCC(CC)) {
10308       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10309           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10310         return SDValue();
10311     } else if (ISD::isUnsignedIntSetCC(CC)) {
10312       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10313                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10314           !DAG.MaskedValueIsZero(N->getOperand(1),
10315                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10316         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10317                                              : SDValue());
10318     } else {
10319       // This is neither a signed nor an unsigned comparison, just make sure
10320       // that the high bits are equal.
10321       APInt Op1Zero, Op1One;
10322       APInt Op2Zero, Op2One;
10323       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
10324       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
10325
10326       // We don't really care about what is known about the first bit (if
10327       // anything), so clear it in all masks prior to comparing them.
10328       Op1Zero.clearBit(0); Op1One.clearBit(0);
10329       Op2Zero.clearBit(0); Op2One.clearBit(0);
10330
10331       if (Op1Zero != Op2Zero || Op1One != Op2One)
10332         return SDValue();
10333     }
10334   }
10335
10336   // We now know that the higher-order bits are irrelevant, we just need to
10337   // make sure that all of the intermediate operations are bit operations, and
10338   // all inputs are extensions.
10339   if (N->getOperand(0).getOpcode() != ISD::AND &&
10340       N->getOperand(0).getOpcode() != ISD::OR  &&
10341       N->getOperand(0).getOpcode() != ISD::XOR &&
10342       N->getOperand(0).getOpcode() != ISD::SELECT &&
10343       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10344       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10345       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10346       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10347       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10348     return SDValue();
10349
10350   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10351       N->getOperand(1).getOpcode() != ISD::AND &&
10352       N->getOperand(1).getOpcode() != ISD::OR  &&
10353       N->getOperand(1).getOpcode() != ISD::XOR &&
10354       N->getOperand(1).getOpcode() != ISD::SELECT &&
10355       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10356       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10357       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10358       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10359       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10360     return SDValue();
10361
10362   SmallVector<SDValue, 4> Inputs;
10363   SmallVector<SDValue, 8> BinOps, PromOps;
10364   SmallPtrSet<SDNode *, 16> Visited;
10365
10366   for (unsigned i = 0; i < 2; ++i) {
10367     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10368           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10369           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10370           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10371         isa<ConstantSDNode>(N->getOperand(i)))
10372       Inputs.push_back(N->getOperand(i));
10373     else
10374       BinOps.push_back(N->getOperand(i));
10375
10376     if (N->getOpcode() == ISD::TRUNCATE)
10377       break;
10378   }
10379
10380   // Visit all inputs, collect all binary operations (and, or, xor and
10381   // select) that are all fed by extensions.
10382   while (!BinOps.empty()) {
10383     SDValue BinOp = BinOps.back();
10384     BinOps.pop_back();
10385
10386     if (!Visited.insert(BinOp.getNode()).second)
10387       continue;
10388
10389     PromOps.push_back(BinOp);
10390
10391     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10392       // The condition of the select is not promoted.
10393       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10394         continue;
10395       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10396         continue;
10397
10398       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10399             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10400             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10401            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10402           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10403         Inputs.push_back(BinOp.getOperand(i));
10404       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10405                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10406                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10407                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10408                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10409                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10410                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10411                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10412                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10413         BinOps.push_back(BinOp.getOperand(i));
10414       } else {
10415         // We have an input that is not an extension or another binary
10416         // operation; we'll abort this transformation.
10417         return SDValue();
10418       }
10419     }
10420   }
10421
10422   // Make sure that this is a self-contained cluster of operations (which
10423   // is not quite the same thing as saying that everything has only one
10424   // use).
10425   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10426     if (isa<ConstantSDNode>(Inputs[i]))
10427       continue;
10428
10429     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10430                               UE = Inputs[i].getNode()->use_end();
10431          UI != UE; ++UI) {
10432       SDNode *User = *UI;
10433       if (User != N && !Visited.count(User))
10434         return SDValue();
10435
10436       // Make sure that we're not going to promote the non-output-value
10437       // operand(s) or SELECT or SELECT_CC.
10438       // FIXME: Although we could sometimes handle this, and it does occur in
10439       // practice that one of the condition inputs to the select is also one of
10440       // the outputs, we currently can't deal with this.
10441       if (User->getOpcode() == ISD::SELECT) {
10442         if (User->getOperand(0) == Inputs[i])
10443           return SDValue();
10444       } else if (User->getOpcode() == ISD::SELECT_CC) {
10445         if (User->getOperand(0) == Inputs[i] ||
10446             User->getOperand(1) == Inputs[i])
10447           return SDValue();
10448       }
10449     }
10450   }
10451
10452   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10453     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10454                               UE = PromOps[i].getNode()->use_end();
10455          UI != UE; ++UI) {
10456       SDNode *User = *UI;
10457       if (User != N && !Visited.count(User))
10458         return SDValue();
10459
10460       // Make sure that we're not going to promote the non-output-value
10461       // operand(s) or SELECT or SELECT_CC.
10462       // FIXME: Although we could sometimes handle this, and it does occur in
10463       // practice that one of the condition inputs to the select is also one of
10464       // the outputs, we currently can't deal with this.
10465       if (User->getOpcode() == ISD::SELECT) {
10466         if (User->getOperand(0) == PromOps[i])
10467           return SDValue();
10468       } else if (User->getOpcode() == ISD::SELECT_CC) {
10469         if (User->getOperand(0) == PromOps[i] ||
10470             User->getOperand(1) == PromOps[i])
10471           return SDValue();
10472       }
10473     }
10474   }
10475
10476   // Replace all inputs with the extension operand.
10477   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10478     // Constants may have users outside the cluster of to-be-promoted nodes,
10479     // and so we need to replace those as we do the promotions.
10480     if (isa<ConstantSDNode>(Inputs[i]))
10481       continue;
10482     else
10483       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10484   }
10485
10486   std::list<HandleSDNode> PromOpHandles;
10487   for (auto &PromOp : PromOps)
10488     PromOpHandles.emplace_back(PromOp);
10489
10490   // Replace all operations (these are all the same, but have a different
10491   // (i1) return type). DAG.getNode will validate that the types of
10492   // a binary operator match, so go through the list in reverse so that
10493   // we've likely promoted both operands first. Any intermediate truncations or
10494   // extensions disappear.
10495   while (!PromOpHandles.empty()) {
10496     SDValue PromOp = PromOpHandles.back().getValue();
10497     PromOpHandles.pop_back();
10498
10499     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10500         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10501         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10502         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10503       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10504           PromOp.getOperand(0).getValueType() != MVT::i1) {
10505         // The operand is not yet ready (see comment below).
10506         PromOpHandles.emplace_front(PromOp);
10507         continue;
10508       }
10509
10510       SDValue RepValue = PromOp.getOperand(0);
10511       if (isa<ConstantSDNode>(RepValue))
10512         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10513
10514       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10515       continue;
10516     }
10517
10518     unsigned C;
10519     switch (PromOp.getOpcode()) {
10520     default:             C = 0; break;
10521     case ISD::SELECT:    C = 1; break;
10522     case ISD::SELECT_CC: C = 2; break;
10523     }
10524
10525     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10526          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10527         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10528          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10529       // The to-be-promoted operands of this node have not yet been
10530       // promoted (this should be rare because we're going through the
10531       // list backward, but if one of the operands has several users in
10532       // this cluster of to-be-promoted nodes, it is possible).
10533       PromOpHandles.emplace_front(PromOp);
10534       continue;
10535     }
10536
10537     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10538                                 PromOp.getNode()->op_end());
10539
10540     // If there are any constant inputs, make sure they're replaced now.
10541     for (unsigned i = 0; i < 2; ++i)
10542       if (isa<ConstantSDNode>(Ops[C+i]))
10543         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10544
10545     DAG.ReplaceAllUsesOfValueWith(PromOp,
10546       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10547   }
10548
10549   // Now we're left with the initial truncation itself.
10550   if (N->getOpcode() == ISD::TRUNCATE)
10551     return N->getOperand(0);
10552
10553   // Otherwise, this is a comparison. The operands to be compared have just
10554   // changed type (to i1), but everything else is the same.
10555   return SDValue(N, 0);
10556 }
10557
10558 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10559                                                   DAGCombinerInfo &DCI) const {
10560   SelectionDAG &DAG = DCI.DAG;
10561   SDLoc dl(N);
10562
10563   // If we're tracking CR bits, we need to be careful that we don't have:
10564   //   zext(binary-ops(trunc(x), trunc(y)))
10565   // or
10566   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10567   // such that we're unnecessarily moving things into CR bits that can more
10568   // efficiently stay in GPRs. Note that if we're not certain that the high
10569   // bits are set as required by the final extension, we still may need to do
10570   // some masking to get the proper behavior.
10571
10572   // This same functionality is important on PPC64 when dealing with
10573   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10574   // the return values of functions. Because it is so similar, it is handled
10575   // here as well.
10576
10577   if (N->getValueType(0) != MVT::i32 &&
10578       N->getValueType(0) != MVT::i64)
10579     return SDValue();
10580
10581   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10582         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10583     return SDValue();
10584
10585   if (N->getOperand(0).getOpcode() != ISD::AND &&
10586       N->getOperand(0).getOpcode() != ISD::OR  &&
10587       N->getOperand(0).getOpcode() != ISD::XOR &&
10588       N->getOperand(0).getOpcode() != ISD::SELECT &&
10589       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10590     return SDValue();
10591
10592   SmallVector<SDValue, 4> Inputs;
10593   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10594   SmallPtrSet<SDNode *, 16> Visited;
10595
10596   // Visit all inputs, collect all binary operations (and, or, xor and
10597   // select) that are all fed by truncations.
10598   while (!BinOps.empty()) {
10599     SDValue BinOp = BinOps.back();
10600     BinOps.pop_back();
10601
10602     if (!Visited.insert(BinOp.getNode()).second)
10603       continue;
10604
10605     PromOps.push_back(BinOp);
10606
10607     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10608       // The condition of the select is not promoted.
10609       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10610         continue;
10611       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10612         continue;
10613
10614       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10615           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10616         Inputs.push_back(BinOp.getOperand(i));
10617       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10618                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10619                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10620                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10621                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10622         BinOps.push_back(BinOp.getOperand(i));
10623       } else {
10624         // We have an input that is not a truncation or another binary
10625         // operation; we'll abort this transformation.
10626         return SDValue();
10627       }
10628     }
10629   }
10630
10631   // The operands of a select that must be truncated when the select is
10632   // promoted because the operand is actually part of the to-be-promoted set.
10633   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10634
10635   // Make sure that this is a self-contained cluster of operations (which
10636   // is not quite the same thing as saying that everything has only one
10637   // use).
10638   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10639     if (isa<ConstantSDNode>(Inputs[i]))
10640       continue;
10641
10642     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10643                               UE = Inputs[i].getNode()->use_end();
10644          UI != UE; ++UI) {
10645       SDNode *User = *UI;
10646       if (User != N && !Visited.count(User))
10647         return SDValue();
10648
10649       // If we're going to promote the non-output-value operand(s) or SELECT or
10650       // SELECT_CC, record them for truncation.
10651       if (User->getOpcode() == ISD::SELECT) {
10652         if (User->getOperand(0) == Inputs[i])
10653           SelectTruncOp[0].insert(std::make_pair(User,
10654                                     User->getOperand(0).getValueType()));
10655       } else if (User->getOpcode() == ISD::SELECT_CC) {
10656         if (User->getOperand(0) == Inputs[i])
10657           SelectTruncOp[0].insert(std::make_pair(User,
10658                                     User->getOperand(0).getValueType()));
10659         if (User->getOperand(1) == Inputs[i])
10660           SelectTruncOp[1].insert(std::make_pair(User,
10661                                     User->getOperand(1).getValueType()));
10662       }
10663     }
10664   }
10665
10666   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10667     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10668                               UE = PromOps[i].getNode()->use_end();
10669          UI != UE; ++UI) {
10670       SDNode *User = *UI;
10671       if (User != N && !Visited.count(User))
10672         return SDValue();
10673
10674       // If we're going to promote the non-output-value operand(s) or SELECT or
10675       // SELECT_CC, record them for truncation.
10676       if (User->getOpcode() == ISD::SELECT) {
10677         if (User->getOperand(0) == PromOps[i])
10678           SelectTruncOp[0].insert(std::make_pair(User,
10679                                     User->getOperand(0).getValueType()));
10680       } else if (User->getOpcode() == ISD::SELECT_CC) {
10681         if (User->getOperand(0) == PromOps[i])
10682           SelectTruncOp[0].insert(std::make_pair(User,
10683                                     User->getOperand(0).getValueType()));
10684         if (User->getOperand(1) == PromOps[i])
10685           SelectTruncOp[1].insert(std::make_pair(User,
10686                                     User->getOperand(1).getValueType()));
10687       }
10688     }
10689   }
10690
10691   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10692   bool ReallyNeedsExt = false;
10693   if (N->getOpcode() != ISD::ANY_EXTEND) {
10694     // If all of the inputs are not already sign/zero extended, then
10695     // we'll still need to do that at the end.
10696     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10697       if (isa<ConstantSDNode>(Inputs[i]))
10698         continue;
10699
10700       unsigned OpBits =
10701         Inputs[i].getOperand(0).getValueSizeInBits();
10702       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10703
10704       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10705            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10706                                   APInt::getHighBitsSet(OpBits,
10707                                                         OpBits-PromBits))) ||
10708           (N->getOpcode() == ISD::SIGN_EXTEND &&
10709            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10710              (OpBits-(PromBits-1)))) {
10711         ReallyNeedsExt = true;
10712         break;
10713       }
10714     }
10715   }
10716
10717   // Replace all inputs, either with the truncation operand, or a
10718   // truncation or extension to the final output type.
10719   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10720     // Constant inputs need to be replaced with the to-be-promoted nodes that
10721     // use them because they might have users outside of the cluster of
10722     // promoted nodes.
10723     if (isa<ConstantSDNode>(Inputs[i]))
10724       continue;
10725
10726     SDValue InSrc = Inputs[i].getOperand(0);
10727     if (Inputs[i].getValueType() == N->getValueType(0))
10728       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10729     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10730       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10731         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10732     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10733       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10734         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10735     else
10736       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10737         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10738   }
10739
10740   std::list<HandleSDNode> PromOpHandles;
10741   for (auto &PromOp : PromOps)
10742     PromOpHandles.emplace_back(PromOp);
10743
10744   // Replace all operations (these are all the same, but have a different
10745   // (promoted) return type). DAG.getNode will validate that the types of
10746   // a binary operator match, so go through the list in reverse so that
10747   // we've likely promoted both operands first.
10748   while (!PromOpHandles.empty()) {
10749     SDValue PromOp = PromOpHandles.back().getValue();
10750     PromOpHandles.pop_back();
10751
10752     unsigned C;
10753     switch (PromOp.getOpcode()) {
10754     default:             C = 0; break;
10755     case ISD::SELECT:    C = 1; break;
10756     case ISD::SELECT_CC: C = 2; break;
10757     }
10758
10759     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10760          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10761         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10762          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10763       // The to-be-promoted operands of this node have not yet been
10764       // promoted (this should be rare because we're going through the
10765       // list backward, but if one of the operands has several users in
10766       // this cluster of to-be-promoted nodes, it is possible).
10767       PromOpHandles.emplace_front(PromOp);
10768       continue;
10769     }
10770
10771     // For SELECT and SELECT_CC nodes, we do a similar check for any
10772     // to-be-promoted comparison inputs.
10773     if (PromOp.getOpcode() == ISD::SELECT ||
10774         PromOp.getOpcode() == ISD::SELECT_CC) {
10775       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10776            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10777           (SelectTruncOp[1].count(PromOp.getNode()) &&
10778            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10779         PromOpHandles.emplace_front(PromOp);
10780         continue;
10781       }
10782     }
10783
10784     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10785                                 PromOp.getNode()->op_end());
10786
10787     // If this node has constant inputs, then they'll need to be promoted here.
10788     for (unsigned i = 0; i < 2; ++i) {
10789       if (!isa<ConstantSDNode>(Ops[C+i]))
10790         continue;
10791       if (Ops[C+i].getValueType() == N->getValueType(0))
10792         continue;
10793
10794       if (N->getOpcode() == ISD::SIGN_EXTEND)
10795         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10796       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10797         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10798       else
10799         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10800     }
10801
10802     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10803     // truncate them again to the original value type.
10804     if (PromOp.getOpcode() == ISD::SELECT ||
10805         PromOp.getOpcode() == ISD::SELECT_CC) {
10806       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10807       if (SI0 != SelectTruncOp[0].end())
10808         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10809       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10810       if (SI1 != SelectTruncOp[1].end())
10811         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10812     }
10813
10814     DAG.ReplaceAllUsesOfValueWith(PromOp,
10815       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10816   }
10817
10818   // Now we're left with the initial extension itself.
10819   if (!ReallyNeedsExt)
10820     return N->getOperand(0);
10821
10822   // To zero extend, just mask off everything except for the first bit (in the
10823   // i1 case).
10824   if (N->getOpcode() == ISD::ZERO_EXTEND)
10825     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10826                        DAG.getConstant(APInt::getLowBitsSet(
10827                                          N->getValueSizeInBits(0), PromBits),
10828                                        dl, N->getValueType(0)));
10829
10830   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10831          "Invalid extension type");
10832   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10833   SDValue ShiftCst =
10834       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10835   return DAG.getNode(
10836       ISD::SRA, dl, N->getValueType(0),
10837       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10838       ShiftCst);
10839 }
10840
10841 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10842 ///
10843 /// If this vector is built out of floating to integer conversions,
10844 /// transform it to a vector built out of floating point values followed by a
10845 /// single floating to integer conversion of the vector.
10846 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
10847 /// becomes (fptosi (build_vector ($A, $B, ...)))
10848 SDValue PPCTargetLowering::
10849 combineElementTruncationToVectorTruncation(SDNode *N,
10850                                            DAGCombinerInfo &DCI) const {
10851   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10852          "Should be called with a BUILD_VECTOR node");
10853
10854   SelectionDAG &DAG = DCI.DAG;
10855   SDLoc dl(N);
10856
10857   SDValue FirstInput = N->getOperand(0);
10858   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10859          "The input operand must be an fp-to-int conversion.");
10860
10861   // This combine happens after legalization so the fp_to_[su]i nodes are
10862   // already converted to PPCSISD nodes.
10863   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10864   if (FirstConversion == PPCISD::FCTIDZ ||
10865       FirstConversion == PPCISD::FCTIDUZ ||
10866       FirstConversion == PPCISD::FCTIWZ ||
10867       FirstConversion == PPCISD::FCTIWUZ) {
10868     bool IsSplat = true;
10869     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10870       FirstConversion == PPCISD::FCTIWUZ;
10871     EVT SrcVT = FirstInput.getOperand(0).getValueType();
10872     SmallVector<SDValue, 4> Ops;
10873     EVT TargetVT = N->getValueType(0);
10874     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10875       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10876         return SDValue();
10877       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10878       if (NextConversion != FirstConversion)
10879         return SDValue();
10880       if (N->getOperand(i) != FirstInput)
10881         IsSplat = false;
10882     }
10883
10884     // If this is a splat, we leave it as-is since there will be only a single
10885     // fp-to-int conversion followed by a splat of the integer. This is better
10886     // for 32-bit and smaller ints and neutral for 64-bit ints.
10887     if (IsSplat)
10888       return SDValue();
10889
10890     // Now that we know we have the right type of node, get its operands
10891     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10892       SDValue In = N->getOperand(i).getOperand(0);
10893       // For 32-bit values, we need to add an FP_ROUND node.
10894       if (Is32Bit) {
10895         if (In.isUndef())
10896           Ops.push_back(DAG.getUNDEF(SrcVT));
10897         else {
10898           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10899                                       MVT::f32, In.getOperand(0),
10900                                       DAG.getIntPtrConstant(1, dl));
10901           Ops.push_back(Trunc);
10902         }
10903       } else
10904         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10905     }
10906
10907     unsigned Opcode;
10908     if (FirstConversion == PPCISD::FCTIDZ ||
10909         FirstConversion == PPCISD::FCTIWZ)
10910       Opcode = ISD::FP_TO_SINT;
10911     else
10912       Opcode = ISD::FP_TO_UINT;
10913
10914     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10915     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10916     return DAG.getNode(Opcode, dl, TargetVT, BV);
10917   }
10918   return SDValue();
10919 }
10920
10921 /// \brief Reduce the number of loads when building a vector.
10922 ///
10923 /// Building a vector out of multiple loads can be converted to a load
10924 /// of the vector type if the loads are consecutive. If the loads are
10925 /// consecutive but in descending order, a shuffle is added at the end
10926 /// to reorder the vector.
10927 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10928   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10929          "Should be called with a BUILD_VECTOR node");
10930
10931   SDLoc dl(N);
10932   bool InputsAreConsecutiveLoads = true;
10933   bool InputsAreReverseConsecutive = true;
10934   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10935   SDValue FirstInput = N->getOperand(0);
10936   bool IsRoundOfExtLoad = false;
10937
10938   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10939       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10940     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10941     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10942   }
10943   // Not a build vector of (possibly fp_rounded) loads.
10944   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10945     return SDValue();
10946
10947   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10948     // If any inputs are fp_round(extload), they all must be.
10949     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10950       return SDValue();
10951
10952     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
10953       N->getOperand(i);
10954     if (NextInput.getOpcode() != ISD::LOAD)
10955       return SDValue();
10956
10957     SDValue PreviousInput =
10958       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
10959     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
10960     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
10961
10962     // If any inputs are fp_round(extload), they all must be.
10963     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
10964       return SDValue();
10965
10966     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
10967       InputsAreConsecutiveLoads = false;
10968     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
10969       InputsAreReverseConsecutive = false;
10970
10971     // Exit early if the loads are neither consecutive nor reverse consecutive.
10972     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
10973       return SDValue();
10974   }
10975
10976   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
10977          "The loads cannot be both consecutive and reverse consecutive.");
10978
10979   SDValue FirstLoadOp =
10980     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
10981   SDValue LastLoadOp =
10982     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
10983                        N->getOperand(N->getNumOperands()-1);
10984
10985   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
10986   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
10987   if (InputsAreConsecutiveLoads) {
10988     assert(LD1 && "Input needs to be a LoadSDNode.");
10989     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
10990                        LD1->getBasePtr(), LD1->getPointerInfo(),
10991                        LD1->getAlignment());
10992   }
10993   if (InputsAreReverseConsecutive) {
10994     assert(LDL && "Input needs to be a LoadSDNode.");
10995     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
10996                                LDL->getBasePtr(), LDL->getPointerInfo(),
10997                                LDL->getAlignment());
10998     SmallVector<int, 16> Ops;
10999     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11000       Ops.push_back(i);
11001
11002     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11003                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11004   }
11005   return SDValue();
11006 }
11007
11008 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11009                                                  DAGCombinerInfo &DCI) const {
11010   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11011          "Should be called with a BUILD_VECTOR node");
11012
11013   SelectionDAG &DAG = DCI.DAG;
11014   SDLoc dl(N);
11015
11016   if (!Subtarget.hasVSX())
11017     return SDValue();
11018
11019   // The target independent DAG combiner will leave a build_vector of
11020   // float-to-int conversions intact. We can generate MUCH better code for
11021   // a float-to-int conversion of a vector of floats.
11022   SDValue FirstInput = N->getOperand(0);
11023   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11024     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11025     if (Reduced)
11026       return Reduced;
11027   }
11028
11029   // If we're building a vector out of consecutive loads, just load that
11030   // vector type.
11031   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11032   if (Reduced)
11033     return Reduced;
11034
11035   if (N->getValueType(0) != MVT::v2f64)
11036     return SDValue();
11037
11038   // Looking for:
11039   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11040   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11041       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11042     return SDValue();
11043   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11044       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11045     return SDValue();
11046   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11047     return SDValue();
11048
11049   SDValue Ext1 = FirstInput.getOperand(0);
11050   SDValue Ext2 = N->getOperand(1).getOperand(0);
11051   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11052      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11053     return SDValue();
11054
11055   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11056   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11057   if (!Ext1Op || !Ext2Op)
11058     return SDValue();
11059   if (Ext1.getValueType() != MVT::i32 ||
11060       Ext2.getValueType() != MVT::i32)
11061   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11062     return SDValue();
11063
11064   int FirstElem = Ext1Op->getZExtValue();
11065   int SecondElem = Ext2Op->getZExtValue();
11066   int SubvecIdx;
11067   if (FirstElem == 0 && SecondElem == 1)
11068     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11069   else if (FirstElem == 2 && SecondElem == 3)
11070     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11071   else
11072     return SDValue();
11073
11074   SDValue SrcVec = Ext1.getOperand(0);
11075   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11076     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11077   return DAG.getNode(NodeType, dl, MVT::v2f64,
11078                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11079 }
11080
11081 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11082                                               DAGCombinerInfo &DCI) const {
11083   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11084           N->getOpcode() == ISD::UINT_TO_FP) &&
11085          "Need an int -> FP conversion node here");
11086
11087   if (useSoftFloat() || !Subtarget.has64BitSupport())
11088     return SDValue();
11089
11090   SelectionDAG &DAG = DCI.DAG;
11091   SDLoc dl(N);
11092   SDValue Op(N, 0);
11093
11094   SDValue FirstOperand(Op.getOperand(0));
11095   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11096     (FirstOperand.getValueType() == MVT::i8 ||
11097      FirstOperand.getValueType() == MVT::i16);
11098   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11099     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11100     bool DstDouble = Op.getValueType() == MVT::f64;
11101     unsigned ConvOp = Signed ?
11102       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11103       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11104     SDValue WidthConst =
11105       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11106                             dl, false);
11107     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11108     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11109     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11110                                          DAG.getVTList(MVT::f64, MVT::Other),
11111                                          Ops, MVT::i8, LDN->getMemOperand());
11112
11113     // For signed conversion, we need to sign-extend the value in the VSR
11114     if (Signed) {
11115       SDValue ExtOps[] = { Ld, WidthConst };
11116       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11117       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11118     } else
11119       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11120   }
11121
11122   // Don't handle ppc_fp128 here or i1 conversions.
11123   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11124     return SDValue();
11125   if (Op.getOperand(0).getValueType() == MVT::i1)
11126     return SDValue();
11127
11128   // For i32 intermediate values, unfortunately, the conversion functions
11129   // leave the upper 32 bits of the value are undefined. Within the set of
11130   // scalar instructions, we have no method for zero- or sign-extending the
11131   // value. Thus, we cannot handle i32 intermediate values here.
11132   if (Op.getOperand(0).getValueType() == MVT::i32)
11133     return SDValue();
11134
11135   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11136          "UINT_TO_FP is supported only with FPCVT");
11137
11138   // If we have FCFIDS, then use it when converting to single-precision.
11139   // Otherwise, convert to double-precision and then round.
11140   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11141                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11142                                                             : PPCISD::FCFIDS)
11143                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11144                                                             : PPCISD::FCFID);
11145   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11146                   ? MVT::f32
11147                   : MVT::f64;
11148
11149   // If we're converting from a float, to an int, and back to a float again,
11150   // then we don't need the store/load pair at all.
11151   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11152        Subtarget.hasFPCVT()) ||
11153       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11154     SDValue Src = Op.getOperand(0).getOperand(0);
11155     if (Src.getValueType() == MVT::f32) {
11156       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11157       DCI.AddToWorklist(Src.getNode());
11158     } else if (Src.getValueType() != MVT::f64) {
11159       // Make sure that we don't pick up a ppc_fp128 source value.
11160       return SDValue();
11161     }
11162
11163     unsigned FCTOp =
11164       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11165                                                         PPCISD::FCTIDUZ;
11166
11167     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11168     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11169
11170     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11171       FP = DAG.getNode(ISD::FP_ROUND, dl,
11172                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11173       DCI.AddToWorklist(FP.getNode());
11174     }
11175
11176     return FP;
11177   }
11178
11179   return SDValue();
11180 }
11181
11182 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11183 // builtins) into loads with swaps.
11184 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11185                                               DAGCombinerInfo &DCI) const {
11186   SelectionDAG &DAG = DCI.DAG;
11187   SDLoc dl(N);
11188   SDValue Chain;
11189   SDValue Base;
11190   MachineMemOperand *MMO;
11191
11192   switch (N->getOpcode()) {
11193   default:
11194     llvm_unreachable("Unexpected opcode for little endian VSX load");
11195   case ISD::LOAD: {
11196     LoadSDNode *LD = cast<LoadSDNode>(N);
11197     Chain = LD->getChain();
11198     Base = LD->getBasePtr();
11199     MMO = LD->getMemOperand();
11200     // If the MMO suggests this isn't a load of a full vector, leave
11201     // things alone.  For a built-in, we have to make the change for
11202     // correctness, so if there is a size problem that will be a bug.
11203     if (MMO->getSize() < 16)
11204       return SDValue();
11205     break;
11206   }
11207   case ISD::INTRINSIC_W_CHAIN: {
11208     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11209     Chain = Intrin->getChain();
11210     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11211     // us what we want. Get operand 2 instead.
11212     Base = Intrin->getOperand(2);
11213     MMO = Intrin->getMemOperand();
11214     break;
11215   }
11216   }
11217
11218   MVT VecTy = N->getValueType(0).getSimpleVT();
11219   SDValue LoadOps[] = { Chain, Base };
11220   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11221                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11222                                          LoadOps, MVT::v2f64, MMO);
11223
11224   DCI.AddToWorklist(Load.getNode());
11225   Chain = Load.getValue(1);
11226   SDValue Swap = DAG.getNode(
11227       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11228   DCI.AddToWorklist(Swap.getNode());
11229
11230   // Add a bitcast if the resulting load type doesn't match v2f64.
11231   if (VecTy != MVT::v2f64) {
11232     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11233     DCI.AddToWorklist(N.getNode());
11234     // Package {bitcast value, swap's chain} to match Load's shape.
11235     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11236                        N, Swap.getValue(1));
11237   }
11238
11239   return Swap;
11240 }
11241
11242 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11243 // builtins) into stores with swaps.
11244 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11245                                                DAGCombinerInfo &DCI) const {
11246   SelectionDAG &DAG = DCI.DAG;
11247   SDLoc dl(N);
11248   SDValue Chain;
11249   SDValue Base;
11250   unsigned SrcOpnd;
11251   MachineMemOperand *MMO;
11252
11253   switch (N->getOpcode()) {
11254   default:
11255     llvm_unreachable("Unexpected opcode for little endian VSX store");
11256   case ISD::STORE: {
11257     StoreSDNode *ST = cast<StoreSDNode>(N);
11258     Chain = ST->getChain();
11259     Base = ST->getBasePtr();
11260     MMO = ST->getMemOperand();
11261     SrcOpnd = 1;
11262     // If the MMO suggests this isn't a store of a full vector, leave
11263     // things alone.  For a built-in, we have to make the change for
11264     // correctness, so if there is a size problem that will be a bug.
11265     if (MMO->getSize() < 16)
11266       return SDValue();
11267     break;
11268   }
11269   case ISD::INTRINSIC_VOID: {
11270     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11271     Chain = Intrin->getChain();
11272     // Intrin->getBasePtr() oddly does not get what we want.
11273     Base = Intrin->getOperand(3);
11274     MMO = Intrin->getMemOperand();
11275     SrcOpnd = 2;
11276     break;
11277   }
11278   }
11279
11280   SDValue Src = N->getOperand(SrcOpnd);
11281   MVT VecTy = Src.getValueType().getSimpleVT();
11282
11283   // All stores are done as v2f64 and possible bit cast.
11284   if (VecTy != MVT::v2f64) {
11285     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11286     DCI.AddToWorklist(Src.getNode());
11287   }
11288
11289   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11290                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11291   DCI.AddToWorklist(Swap.getNode());
11292   Chain = Swap.getValue(1);
11293   SDValue StoreOps[] = { Chain, Swap, Base };
11294   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11295                                           DAG.getVTList(MVT::Other),
11296                                           StoreOps, VecTy, MMO);
11297   DCI.AddToWorklist(Store.getNode());
11298   return Store;
11299 }
11300
11301 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11302                                              DAGCombinerInfo &DCI) const {
11303   SelectionDAG &DAG = DCI.DAG;
11304   SDLoc dl(N);
11305   switch (N->getOpcode()) {
11306   default: break;
11307   case PPCISD::SHL:
11308     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11309         return N->getOperand(0);
11310     break;
11311   case PPCISD::SRL:
11312     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11313         return N->getOperand(0);
11314     break;
11315   case PPCISD::SRA:
11316     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11317       if (C->isNullValue() ||   //  0 >>s V -> 0.
11318           C->isAllOnesValue())    // -1 >>s V -> -1.
11319         return N->getOperand(0);
11320     }
11321     break;
11322   case ISD::SIGN_EXTEND:
11323   case ISD::ZERO_EXTEND:
11324   case ISD::ANY_EXTEND:
11325     return DAGCombineExtBoolTrunc(N, DCI);
11326   case ISD::TRUNCATE:
11327   case ISD::SETCC:
11328   case ISD::SELECT_CC:
11329     return DAGCombineTruncBoolExt(N, DCI);
11330   case ISD::SINT_TO_FP:
11331   case ISD::UINT_TO_FP:
11332     return combineFPToIntToFP(N, DCI);
11333   case ISD::STORE: {
11334     EVT Op1VT = N->getOperand(1).getValueType();
11335     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11336       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11337
11338     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11339     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11340         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11341         ValidTypeForStoreFltAsInt &&
11342         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11343       SDValue Val = N->getOperand(1).getOperand(0);
11344       if (Val.getValueType() == MVT::f32) {
11345         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11346         DCI.AddToWorklist(Val.getNode());
11347       }
11348       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11349       DCI.AddToWorklist(Val.getNode());
11350
11351       if (Op1VT == MVT::i32) {
11352         SDValue Ops[] = {
11353           N->getOperand(0), Val, N->getOperand(2),
11354           DAG.getValueType(N->getOperand(1).getValueType())
11355         };
11356
11357         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11358                 DAG.getVTList(MVT::Other), Ops,
11359                 cast<StoreSDNode>(N)->getMemoryVT(),
11360                 cast<StoreSDNode>(N)->getMemOperand());
11361       } else {
11362         unsigned WidthInBytes =
11363           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11364         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11365
11366         SDValue Ops[] = {
11367           N->getOperand(0), Val, N->getOperand(2), WidthConst,
11368           DAG.getValueType(N->getOperand(1).getValueType())
11369         };
11370         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11371                                       DAG.getVTList(MVT::Other), Ops,
11372                                       cast<StoreSDNode>(N)->getMemoryVT(),
11373                                       cast<StoreSDNode>(N)->getMemOperand());
11374       }
11375
11376       DCI.AddToWorklist(Val.getNode());
11377       return Val;
11378     }
11379
11380     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11381     if (cast<StoreSDNode>(N)->isUnindexed() &&
11382         N->getOperand(1).getOpcode() == ISD::BSWAP &&
11383         N->getOperand(1).getNode()->hasOneUse() &&
11384         (N->getOperand(1).getValueType() == MVT::i32 ||
11385          N->getOperand(1).getValueType() == MVT::i16 ||
11386          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11387           N->getOperand(1).getValueType() == MVT::i64))) {
11388       SDValue BSwapOp = N->getOperand(1).getOperand(0);
11389       // Do an any-extend to 32-bits if this is a half-word input.
11390       if (BSwapOp.getValueType() == MVT::i16)
11391         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11392
11393       // If the type of BSWAP operand is wider than stored memory width
11394       // it need to be shifted to the right side before STBRX.
11395       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11396       if (Op1VT.bitsGT(mVT)) {
11397         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11398         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11399                               DAG.getConstant(Shift, dl, MVT::i32));
11400         // Need to truncate if this is a bswap of i64 stored as i32/i16.
11401         if (Op1VT == MVT::i64)
11402           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11403       }
11404
11405       SDValue Ops[] = {
11406         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11407       };
11408       return
11409         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11410                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11411                                 cast<StoreSDNode>(N)->getMemOperand());
11412     }
11413
11414     // For little endian, VSX stores require generating xxswapd/lxvd2x.
11415     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11416     EVT VT = N->getOperand(1).getValueType();
11417     if (VT.isSimple()) {
11418       MVT StoreVT = VT.getSimpleVT();
11419       if (Subtarget.needsSwapsForVSXMemOps() &&
11420           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11421            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11422         return expandVSXStoreForLE(N, DCI);
11423     }
11424     break;
11425   }
11426   case ISD::LOAD: {
11427     LoadSDNode *LD = cast<LoadSDNode>(N);
11428     EVT VT = LD->getValueType(0);
11429
11430     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11431     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11432     if (VT.isSimple()) {
11433       MVT LoadVT = VT.getSimpleVT();
11434       if (Subtarget.needsSwapsForVSXMemOps() &&
11435           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11436            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11437         return expandVSXLoadForLE(N, DCI);
11438     }
11439
11440     // We sometimes end up with a 64-bit integer load, from which we extract
11441     // two single-precision floating-point numbers. This happens with
11442     // std::complex<float>, and other similar structures, because of the way we
11443     // canonicalize structure copies. However, if we lack direct moves,
11444     // then the final bitcasts from the extracted integer values to the
11445     // floating-point numbers turn into store/load pairs. Even with direct moves,
11446     // just loading the two floating-point numbers is likely better.
11447     auto ReplaceTwoFloatLoad = [&]() {
11448       if (VT != MVT::i64)
11449         return false;
11450
11451       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11452           LD->isVolatile())
11453         return false;
11454
11455       //  We're looking for a sequence like this:
11456       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11457       //      t16: i64 = srl t13, Constant:i32<32>
11458       //    t17: i32 = truncate t16
11459       //  t18: f32 = bitcast t17
11460       //    t19: i32 = truncate t13
11461       //  t20: f32 = bitcast t19
11462
11463       if (!LD->hasNUsesOfValue(2, 0))
11464         return false;
11465
11466       auto UI = LD->use_begin();
11467       while (UI.getUse().getResNo() != 0) ++UI;
11468       SDNode *Trunc = *UI++;
11469       while (UI.getUse().getResNo() != 0) ++UI;
11470       SDNode *RightShift = *UI;
11471       if (Trunc->getOpcode() != ISD::TRUNCATE)
11472         std::swap(Trunc, RightShift);
11473
11474       if (Trunc->getOpcode() != ISD::TRUNCATE ||
11475           Trunc->getValueType(0) != MVT::i32 ||
11476           !Trunc->hasOneUse())
11477         return false;
11478       if (RightShift->getOpcode() != ISD::SRL ||
11479           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11480           RightShift->getConstantOperandVal(1) != 32 ||
11481           !RightShift->hasOneUse())
11482         return false;
11483
11484       SDNode *Trunc2 = *RightShift->use_begin();
11485       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11486           Trunc2->getValueType(0) != MVT::i32 ||
11487           !Trunc2->hasOneUse())
11488         return false;
11489
11490       SDNode *Bitcast = *Trunc->use_begin();
11491       SDNode *Bitcast2 = *Trunc2->use_begin();
11492
11493       if (Bitcast->getOpcode() != ISD::BITCAST ||
11494           Bitcast->getValueType(0) != MVT::f32)
11495         return false;
11496       if (Bitcast2->getOpcode() != ISD::BITCAST ||
11497           Bitcast2->getValueType(0) != MVT::f32)
11498         return false;
11499
11500       if (Subtarget.isLittleEndian())
11501         std::swap(Bitcast, Bitcast2);
11502
11503       // Bitcast has the second float (in memory-layout order) and Bitcast2
11504       // has the first one.
11505
11506       SDValue BasePtr = LD->getBasePtr();
11507       if (LD->isIndexed()) {
11508         assert(LD->getAddressingMode() == ISD::PRE_INC &&
11509                "Non-pre-inc AM on PPC?");
11510         BasePtr =
11511           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11512                       LD->getOffset());
11513       }
11514
11515       auto MMOFlags =
11516           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11517       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11518                                       LD->getPointerInfo(), LD->getAlignment(),
11519                                       MMOFlags, LD->getAAInfo());
11520       SDValue AddPtr =
11521         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11522                     BasePtr, DAG.getIntPtrConstant(4, dl));
11523       SDValue FloatLoad2 = DAG.getLoad(
11524           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11525           LD->getPointerInfo().getWithOffset(4),
11526           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11527
11528       if (LD->isIndexed()) {
11529         // Note that DAGCombine should re-form any pre-increment load(s) from
11530         // what is produced here if that makes sense.
11531         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11532       }
11533
11534       DCI.CombineTo(Bitcast2, FloatLoad);
11535       DCI.CombineTo(Bitcast, FloatLoad2);
11536
11537       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11538                                     SDValue(FloatLoad2.getNode(), 1));
11539       return true;
11540     };
11541
11542     if (ReplaceTwoFloatLoad())
11543       return SDValue(N, 0);
11544
11545     EVT MemVT = LD->getMemoryVT();
11546     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11547     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11548     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11549     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11550     if (LD->isUnindexed() && VT.isVector() &&
11551         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11552           // P8 and later hardware should just use LOAD.
11553           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11554                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11555          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11556           LD->getAlignment() >= ScalarABIAlignment)) &&
11557         LD->getAlignment() < ABIAlignment) {
11558       // This is a type-legal unaligned Altivec or QPX load.
11559       SDValue Chain = LD->getChain();
11560       SDValue Ptr = LD->getBasePtr();
11561       bool isLittleEndian = Subtarget.isLittleEndian();
11562
11563       // This implements the loading of unaligned vectors as described in
11564       // the venerable Apple Velocity Engine overview. Specifically:
11565       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11566       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11567       //
11568       // The general idea is to expand a sequence of one or more unaligned
11569       // loads into an alignment-based permutation-control instruction (lvsl
11570       // or lvsr), a series of regular vector loads (which always truncate
11571       // their input address to an aligned address), and a series of
11572       // permutations.  The results of these permutations are the requested
11573       // loaded values.  The trick is that the last "extra" load is not taken
11574       // from the address you might suspect (sizeof(vector) bytes after the
11575       // last requested load), but rather sizeof(vector) - 1 bytes after the
11576       // last requested vector. The point of this is to avoid a page fault if
11577       // the base address happened to be aligned. This works because if the
11578       // base address is aligned, then adding less than a full vector length
11579       // will cause the last vector in the sequence to be (re)loaded.
11580       // Otherwise, the next vector will be fetched as you might suspect was
11581       // necessary.
11582
11583       // We might be able to reuse the permutation generation from
11584       // a different base address offset from this one by an aligned amount.
11585       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11586       // optimization later.
11587       Intrinsic::ID Intr, IntrLD, IntrPerm;
11588       MVT PermCntlTy, PermTy, LDTy;
11589       if (Subtarget.hasAltivec()) {
11590         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
11591                                  Intrinsic::ppc_altivec_lvsl;
11592         IntrLD = Intrinsic::ppc_altivec_lvx;
11593         IntrPerm = Intrinsic::ppc_altivec_vperm;
11594         PermCntlTy = MVT::v16i8;
11595         PermTy = MVT::v4i32;
11596         LDTy = MVT::v4i32;
11597       } else {
11598         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11599                                        Intrinsic::ppc_qpx_qvlpcls;
11600         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11601                                        Intrinsic::ppc_qpx_qvlfs;
11602         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11603         PermCntlTy = MVT::v4f64;
11604         PermTy = MVT::v4f64;
11605         LDTy = MemVT.getSimpleVT();
11606       }
11607
11608       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11609
11610       // Create the new MMO for the new base load. It is like the original MMO,
11611       // but represents an area in memory almost twice the vector size centered
11612       // on the original address. If the address is unaligned, we might start
11613       // reading up to (sizeof(vector)-1) bytes below the address of the
11614       // original unaligned load.
11615       MachineFunction &MF = DAG.getMachineFunction();
11616       MachineMemOperand *BaseMMO =
11617         MF.getMachineMemOperand(LD->getMemOperand(),
11618                                 -(long)MemVT.getStoreSize()+1,
11619                                 2*MemVT.getStoreSize()-1);
11620
11621       // Create the new base load.
11622       SDValue LDXIntID =
11623           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11624       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11625       SDValue BaseLoad =
11626         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11627                                 DAG.getVTList(PermTy, MVT::Other),
11628                                 BaseLoadOps, LDTy, BaseMMO);
11629
11630       // Note that the value of IncOffset (which is provided to the next
11631       // load's pointer info offset value, and thus used to calculate the
11632       // alignment), and the value of IncValue (which is actually used to
11633       // increment the pointer value) are different! This is because we
11634       // require the next load to appear to be aligned, even though it
11635       // is actually offset from the base pointer by a lesser amount.
11636       int IncOffset = VT.getSizeInBits() / 8;
11637       int IncValue = IncOffset;
11638
11639       // Walk (both up and down) the chain looking for another load at the real
11640       // (aligned) offset (the alignment of the other load does not matter in
11641       // this case). If found, then do not use the offset reduction trick, as
11642       // that will prevent the loads from being later combined (as they would
11643       // otherwise be duplicates).
11644       if (!findConsecutiveLoad(LD, DAG))
11645         --IncValue;
11646
11647       SDValue Increment =
11648           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11649       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11650
11651       MachineMemOperand *ExtraMMO =
11652         MF.getMachineMemOperand(LD->getMemOperand(),
11653                                 1, 2*MemVT.getStoreSize()-1);
11654       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11655       SDValue ExtraLoad =
11656         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11657                                 DAG.getVTList(PermTy, MVT::Other),
11658                                 ExtraLoadOps, LDTy, ExtraMMO);
11659
11660       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11661         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11662
11663       // Because vperm has a big-endian bias, we must reverse the order
11664       // of the input vectors and complement the permute control vector
11665       // when generating little endian code.  We have already handled the
11666       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11667       // and ExtraLoad here.
11668       SDValue Perm;
11669       if (isLittleEndian)
11670         Perm = BuildIntrinsicOp(IntrPerm,
11671                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11672       else
11673         Perm = BuildIntrinsicOp(IntrPerm,
11674                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11675
11676       if (VT != PermTy)
11677         Perm = Subtarget.hasAltivec() ?
11678                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11679                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11680                                DAG.getTargetConstant(1, dl, MVT::i64));
11681                                // second argument is 1 because this rounding
11682                                // is always exact.
11683
11684       // The output of the permutation is our loaded result, the TokenFactor is
11685       // our new chain.
11686       DCI.CombineTo(N, Perm, TF);
11687       return SDValue(N, 0);
11688     }
11689     }
11690     break;
11691     case ISD::INTRINSIC_WO_CHAIN: {
11692       bool isLittleEndian = Subtarget.isLittleEndian();
11693       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11694       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11695                                            : Intrinsic::ppc_altivec_lvsl);
11696       if ((IID == Intr ||
11697            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11698            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11699         N->getOperand(1)->getOpcode() == ISD::ADD) {
11700         SDValue Add = N->getOperand(1);
11701
11702         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11703                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11704
11705         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11706                                   APInt::getAllOnesValue(Bits /* alignment */)
11707                                       .zext(Add.getScalarValueSizeInBits()))) {
11708           SDNode *BasePtr = Add->getOperand(0).getNode();
11709           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11710                                     UE = BasePtr->use_end();
11711                UI != UE; ++UI) {
11712             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11713                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11714               // We've found another LVSL/LVSR, and this address is an aligned
11715               // multiple of that one. The results will be the same, so use the
11716               // one we've just found instead.
11717
11718               return SDValue(*UI, 0);
11719             }
11720           }
11721         }
11722
11723         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11724           SDNode *BasePtr = Add->getOperand(0).getNode();
11725           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11726                UE = BasePtr->use_end(); UI != UE; ++UI) {
11727             if (UI->getOpcode() == ISD::ADD &&
11728                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11729                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11730                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11731                 (1ULL << Bits) == 0) {
11732               SDNode *OtherAdd = *UI;
11733               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11734                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11735                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11736                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11737                   return SDValue(*VI, 0);
11738                 }
11739               }
11740             }
11741           }
11742         }
11743       }
11744     }
11745
11746     break;
11747   case ISD::INTRINSIC_W_CHAIN:
11748     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11749     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11750     if (Subtarget.needsSwapsForVSXMemOps()) {
11751       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11752       default:
11753         break;
11754       case Intrinsic::ppc_vsx_lxvw4x:
11755       case Intrinsic::ppc_vsx_lxvd2x:
11756         return expandVSXLoadForLE(N, DCI);
11757       }
11758     }
11759     break;
11760   case ISD::INTRINSIC_VOID:
11761     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11762     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11763     if (Subtarget.needsSwapsForVSXMemOps()) {
11764       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11765       default:
11766         break;
11767       case Intrinsic::ppc_vsx_stxvw4x:
11768       case Intrinsic::ppc_vsx_stxvd2x:
11769         return expandVSXStoreForLE(N, DCI);
11770       }
11771     }
11772     break;
11773   case ISD::BSWAP:
11774     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11775     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11776         N->getOperand(0).hasOneUse() &&
11777         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11778          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11779           N->getValueType(0) == MVT::i64))) {
11780       SDValue Load = N->getOperand(0);
11781       LoadSDNode *LD = cast<LoadSDNode>(Load);
11782       // Create the byte-swapping load.
11783       SDValue Ops[] = {
11784         LD->getChain(),    // Chain
11785         LD->getBasePtr(),  // Ptr
11786         DAG.getValueType(N->getValueType(0)) // VT
11787       };
11788       SDValue BSLoad =
11789         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11790                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11791                                               MVT::i64 : MVT::i32, MVT::Other),
11792                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11793
11794       // If this is an i16 load, insert the truncate.
11795       SDValue ResVal = BSLoad;
11796       if (N->getValueType(0) == MVT::i16)
11797         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11798
11799       // First, combine the bswap away.  This makes the value produced by the
11800       // load dead.
11801       DCI.CombineTo(N, ResVal);
11802
11803       // Next, combine the load away, we give it a bogus result value but a real
11804       // chain result.  The result value is dead because the bswap is dead.
11805       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11806
11807       // Return N so it doesn't get rechecked!
11808       return SDValue(N, 0);
11809     }
11810     break;
11811   case PPCISD::VCMP:
11812     // If a VCMPo node already exists with exactly the same operands as this
11813     // node, use its result instead of this node (VCMPo computes both a CR6 and
11814     // a normal output).
11815     //
11816     if (!N->getOperand(0).hasOneUse() &&
11817         !N->getOperand(1).hasOneUse() &&
11818         !N->getOperand(2).hasOneUse()) {
11819
11820       // Scan all of the users of the LHS, looking for VCMPo's that match.
11821       SDNode *VCMPoNode = nullptr;
11822
11823       SDNode *LHSN = N->getOperand(0).getNode();
11824       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11825            UI != E; ++UI)
11826         if (UI->getOpcode() == PPCISD::VCMPo &&
11827             UI->getOperand(1) == N->getOperand(1) &&
11828             UI->getOperand(2) == N->getOperand(2) &&
11829             UI->getOperand(0) == N->getOperand(0)) {
11830           VCMPoNode = *UI;
11831           break;
11832         }
11833
11834       // If there is no VCMPo node, or if the flag value has a single use, don't
11835       // transform this.
11836       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11837         break;
11838
11839       // Look at the (necessarily single) use of the flag value.  If it has a
11840       // chain, this transformation is more complex.  Note that multiple things
11841       // could use the value result, which we should ignore.
11842       SDNode *FlagUser = nullptr;
11843       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11844            FlagUser == nullptr; ++UI) {
11845         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11846         SDNode *User = *UI;
11847         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11848           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11849             FlagUser = User;
11850             break;
11851           }
11852         }
11853       }
11854
11855       // If the user is a MFOCRF instruction, we know this is safe.
11856       // Otherwise we give up for right now.
11857       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11858         return SDValue(VCMPoNode, 0);
11859     }
11860     break;
11861   case ISD::BRCOND: {
11862     SDValue Cond = N->getOperand(1);
11863     SDValue Target = N->getOperand(2);
11864
11865     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11866         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11867           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11868
11869       // We now need to make the intrinsic dead (it cannot be instruction
11870       // selected).
11871       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11872       assert(Cond.getNode()->hasOneUse() &&
11873              "Counter decrement has more than one use");
11874
11875       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11876                          N->getOperand(0), Target);
11877     }
11878   }
11879   break;
11880   case ISD::BR_CC: {
11881     // If this is a branch on an altivec predicate comparison, lower this so
11882     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11883     // lowering is done pre-legalize, because the legalizer lowers the predicate
11884     // compare down to code that is difficult to reassemble.
11885     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11886     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11887
11888     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11889     // value. If so, pass-through the AND to get to the intrinsic.
11890     if (LHS.getOpcode() == ISD::AND &&
11891         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11892         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11893           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11894         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11895         !isNullConstant(LHS.getOperand(1)))
11896       LHS = LHS.getOperand(0);
11897
11898     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11899         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11900           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11901         isa<ConstantSDNode>(RHS)) {
11902       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11903              "Counter decrement comparison is not EQ or NE");
11904
11905       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11906       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11907                     (CC == ISD::SETNE && !Val);
11908
11909       // We now need to make the intrinsic dead (it cannot be instruction
11910       // selected).
11911       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11912       assert(LHS.getNode()->hasOneUse() &&
11913              "Counter decrement has more than one use");
11914
11915       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11916                          N->getOperand(0), N->getOperand(4));
11917     }
11918
11919     int CompareOpc;
11920     bool isDot;
11921
11922     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11923         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11924         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11925       assert(isDot && "Can't compare against a vector result!");
11926
11927       // If this is a comparison against something other than 0/1, then we know
11928       // that the condition is never/always true.
11929       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11930       if (Val != 0 && Val != 1) {
11931         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11932           return N->getOperand(0);
11933         // Always !=, turn it into an unconditional branch.
11934         return DAG.getNode(ISD::BR, dl, MVT::Other,
11935                            N->getOperand(0), N->getOperand(4));
11936       }
11937
11938       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11939
11940       // Create the PPCISD altivec 'dot' comparison node.
11941       SDValue Ops[] = {
11942         LHS.getOperand(2),  // LHS of compare
11943         LHS.getOperand(3),  // RHS of compare
11944         DAG.getConstant(CompareOpc, dl, MVT::i32)
11945       };
11946       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11947       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11948
11949       // Unpack the result based on how the target uses it.
11950       PPC::Predicate CompOpc;
11951       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11952       default:  // Can't happen, don't crash on invalid number though.
11953       case 0:   // Branch on the value of the EQ bit of CR6.
11954         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11955         break;
11956       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11957         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11958         break;
11959       case 2:   // Branch on the value of the LT bit of CR6.
11960         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11961         break;
11962       case 3:   // Branch on the inverted value of the LT bit of CR6.
11963         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11964         break;
11965       }
11966
11967       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11968                          DAG.getConstant(CompOpc, dl, MVT::i32),
11969                          DAG.getRegister(PPC::CR6, MVT::i32),
11970                          N->getOperand(4), CompNode.getValue(1));
11971     }
11972     break;
11973   }
11974   case ISD::BUILD_VECTOR:
11975     return DAGCombineBuildVector(N, DCI);
11976   }
11977
11978   return SDValue();
11979 }
11980
11981 SDValue
11982 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11983                                   SelectionDAG &DAG,
11984                                   std::vector<SDNode *> *Created) const {
11985   // fold (sdiv X, pow2)
11986   EVT VT = N->getValueType(0);
11987   if (VT == MVT::i64 && !Subtarget.isPPC64())
11988     return SDValue();
11989   if ((VT != MVT::i32 && VT != MVT::i64) ||
11990       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11991     return SDValue();
11992
11993   SDLoc DL(N);
11994   SDValue N0 = N->getOperand(0);
11995
11996   bool IsNegPow2 = (-Divisor).isPowerOf2();
11997   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11998   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11999
12000   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12001   if (Created)
12002     Created->push_back(Op.getNode());
12003
12004   if (IsNegPow2) {
12005     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12006     if (Created)
12007       Created->push_back(Op.getNode());
12008   }
12009
12010   return Op;
12011 }
12012
12013 //===----------------------------------------------------------------------===//
12014 // Inline Assembly Support
12015 //===----------------------------------------------------------------------===//
12016
12017 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12018                                                       APInt &KnownZero,
12019                                                       APInt &KnownOne,
12020                                                       const APInt &DemandedElts,
12021                                                       const SelectionDAG &DAG,
12022                                                       unsigned Depth) const {
12023   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
12024   switch (Op.getOpcode()) {
12025   default: break;
12026   case PPCISD::LBRX: {
12027     // lhbrx is known to have the top bits cleared out.
12028     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12029       KnownZero = 0xFFFF0000;
12030     break;
12031   }
12032   case ISD::INTRINSIC_WO_CHAIN: {
12033     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12034     default: break;
12035     case Intrinsic::ppc_altivec_vcmpbfp_p:
12036     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12037     case Intrinsic::ppc_altivec_vcmpequb_p:
12038     case Intrinsic::ppc_altivec_vcmpequh_p:
12039     case Intrinsic::ppc_altivec_vcmpequw_p:
12040     case Intrinsic::ppc_altivec_vcmpequd_p:
12041     case Intrinsic::ppc_altivec_vcmpgefp_p:
12042     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12043     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12044     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12045     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12046     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12047     case Intrinsic::ppc_altivec_vcmpgtub_p:
12048     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12049     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12050     case Intrinsic::ppc_altivec_vcmpgtud_p:
12051       KnownZero = ~1U;  // All bits but the low one are known to be zero.
12052       break;
12053     }
12054   }
12055   }
12056 }
12057
12058 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12059   switch (Subtarget.getDarwinDirective()) {
12060   default: break;
12061   case PPC::DIR_970:
12062   case PPC::DIR_PWR4:
12063   case PPC::DIR_PWR5:
12064   case PPC::DIR_PWR5X:
12065   case PPC::DIR_PWR6:
12066   case PPC::DIR_PWR6X:
12067   case PPC::DIR_PWR7:
12068   case PPC::DIR_PWR8:
12069   case PPC::DIR_PWR9: {
12070     if (!ML)
12071       break;
12072
12073     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12074
12075     // For small loops (between 5 and 8 instructions), align to a 32-byte
12076     // boundary so that the entire loop fits in one instruction-cache line.
12077     uint64_t LoopSize = 0;
12078     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12079       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12080         LoopSize += TII->getInstSizeInBytes(*J);
12081         if (LoopSize > 32)
12082           break;
12083       }
12084
12085     if (LoopSize > 16 && LoopSize <= 32)
12086       return 5;
12087
12088     break;
12089   }
12090   }
12091
12092   return TargetLowering::getPrefLoopAlignment(ML);
12093 }
12094
12095 /// getConstraintType - Given a constraint, return the type of
12096 /// constraint it is for this target.
12097 PPCTargetLowering::ConstraintType
12098 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12099   if (Constraint.size() == 1) {
12100     switch (Constraint[0]) {
12101     default: break;
12102     case 'b':
12103     case 'r':
12104     case 'f':
12105     case 'd':
12106     case 'v':
12107     case 'y':
12108       return C_RegisterClass;
12109     case 'Z':
12110       // FIXME: While Z does indicate a memory constraint, it specifically
12111       // indicates an r+r address (used in conjunction with the 'y' modifier
12112       // in the replacement string). Currently, we're forcing the base
12113       // register to be r0 in the asm printer (which is interpreted as zero)
12114       // and forming the complete address in the second register. This is
12115       // suboptimal.
12116       return C_Memory;
12117     }
12118   } else if (Constraint == "wc") { // individual CR bits.
12119     return C_RegisterClass;
12120   } else if (Constraint == "wa" || Constraint == "wd" ||
12121              Constraint == "wf" || Constraint == "ws") {
12122     return C_RegisterClass; // VSX registers.
12123   }
12124   return TargetLowering::getConstraintType(Constraint);
12125 }
12126
12127 /// Examine constraint type and operand type and determine a weight value.
12128 /// This object must already have been set up with the operand type
12129 /// and the current alternative constraint selected.
12130 TargetLowering::ConstraintWeight
12131 PPCTargetLowering::getSingleConstraintMatchWeight(
12132     AsmOperandInfo &info, const char *constraint) const {
12133   ConstraintWeight weight = CW_Invalid;
12134   Value *CallOperandVal = info.CallOperandVal;
12135     // If we don't have a value, we can't do a match,
12136     // but allow it at the lowest weight.
12137   if (!CallOperandVal)
12138     return CW_Default;
12139   Type *type = CallOperandVal->getType();
12140
12141   // Look at the constraint type.
12142   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12143     return CW_Register; // an individual CR bit.
12144   else if ((StringRef(constraint) == "wa" ||
12145             StringRef(constraint) == "wd" ||
12146             StringRef(constraint) == "wf") &&
12147            type->isVectorTy())
12148     return CW_Register;
12149   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12150     return CW_Register;
12151
12152   switch (*constraint) {
12153   default:
12154     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12155     break;
12156   case 'b':
12157     if (type->isIntegerTy())
12158       weight = CW_Register;
12159     break;
12160   case 'f':
12161     if (type->isFloatTy())
12162       weight = CW_Register;
12163     break;
12164   case 'd':
12165     if (type->isDoubleTy())
12166       weight = CW_Register;
12167     break;
12168   case 'v':
12169     if (type->isVectorTy())
12170       weight = CW_Register;
12171     break;
12172   case 'y':
12173     weight = CW_Register;
12174     break;
12175   case 'Z':
12176     weight = CW_Memory;
12177     break;
12178   }
12179   return weight;
12180 }
12181
12182 std::pair<unsigned, const TargetRegisterClass *>
12183 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12184                                                 StringRef Constraint,
12185                                                 MVT VT) const {
12186   if (Constraint.size() == 1) {
12187     // GCC RS6000 Constraint Letters
12188     switch (Constraint[0]) {
12189     case 'b':   // R1-R31
12190       if (VT == MVT::i64 && Subtarget.isPPC64())
12191         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12192       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12193     case 'r':   // R0-R31
12194       if (VT == MVT::i64 && Subtarget.isPPC64())
12195         return std::make_pair(0U, &PPC::G8RCRegClass);
12196       return std::make_pair(0U, &PPC::GPRCRegClass);
12197     // 'd' and 'f' constraints are both defined to be "the floating point
12198     // registers", where one is for 32-bit and the other for 64-bit. We don't
12199     // really care overly much here so just give them all the same reg classes.
12200     case 'd':
12201     case 'f':
12202       if (VT == MVT::f32 || VT == MVT::i32)
12203         return std::make_pair(0U, &PPC::F4RCRegClass);
12204       if (VT == MVT::f64 || VT == MVT::i64)
12205         return std::make_pair(0U, &PPC::F8RCRegClass);
12206       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12207         return std::make_pair(0U, &PPC::QFRCRegClass);
12208       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12209         return std::make_pair(0U, &PPC::QSRCRegClass);
12210       break;
12211     case 'v':
12212       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12213         return std::make_pair(0U, &PPC::QFRCRegClass);
12214       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12215         return std::make_pair(0U, &PPC::QSRCRegClass);
12216       if (Subtarget.hasAltivec())
12217         return std::make_pair(0U, &PPC::VRRCRegClass);
12218     case 'y':   // crrc
12219       return std::make_pair(0U, &PPC::CRRCRegClass);
12220     }
12221   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12222     // An individual CR bit.
12223     return std::make_pair(0U, &PPC::CRBITRCRegClass);
12224   } else if ((Constraint == "wa" || Constraint == "wd" ||
12225              Constraint == "wf") && Subtarget.hasVSX()) {
12226     return std::make_pair(0U, &PPC::VSRCRegClass);
12227   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12228     if (VT == MVT::f32 && Subtarget.hasP8Vector())
12229       return std::make_pair(0U, &PPC::VSSRCRegClass);
12230     else
12231       return std::make_pair(0U, &PPC::VSFRCRegClass);
12232   }
12233
12234   std::pair<unsigned, const TargetRegisterClass *> R =
12235       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12236
12237   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12238   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12239   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12240   // register.
12241   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12242   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12243   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12244       PPC::GPRCRegClass.contains(R.first))
12245     return std::make_pair(TRI->getMatchingSuperReg(R.first,
12246                             PPC::sub_32, &PPC::G8RCRegClass),
12247                           &PPC::G8RCRegClass);
12248
12249   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12250   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12251     R.first = PPC::CR0;
12252     R.second = &PPC::CRRCRegClass;
12253   }
12254
12255   return R;
12256 }
12257
12258 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12259 /// vector.  If it is invalid, don't add anything to Ops.
12260 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12261                                                      std::string &Constraint,
12262                                                      std::vector<SDValue>&Ops,
12263                                                      SelectionDAG &DAG) const {
12264   SDValue Result;
12265
12266   // Only support length 1 constraints.
12267   if (Constraint.length() > 1) return;
12268
12269   char Letter = Constraint[0];
12270   switch (Letter) {
12271   default: break;
12272   case 'I':
12273   case 'J':
12274   case 'K':
12275   case 'L':
12276   case 'M':
12277   case 'N':
12278   case 'O':
12279   case 'P': {
12280     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12281     if (!CST) return; // Must be an immediate to match.
12282     SDLoc dl(Op);
12283     int64_t Value = CST->getSExtValue();
12284     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12285                          // numbers are printed as such.
12286     switch (Letter) {
12287     default: llvm_unreachable("Unknown constraint letter!");
12288     case 'I':  // "I" is a signed 16-bit constant.
12289       if (isInt<16>(Value))
12290         Result = DAG.getTargetConstant(Value, dl, TCVT);
12291       break;
12292     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
12293       if (isShiftedUInt<16, 16>(Value))
12294         Result = DAG.getTargetConstant(Value, dl, TCVT);
12295       break;
12296     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
12297       if (isShiftedInt<16, 16>(Value))
12298         Result = DAG.getTargetConstant(Value, dl, TCVT);
12299       break;
12300     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
12301       if (isUInt<16>(Value))
12302         Result = DAG.getTargetConstant(Value, dl, TCVT);
12303       break;
12304     case 'M':  // "M" is a constant that is greater than 31.
12305       if (Value > 31)
12306         Result = DAG.getTargetConstant(Value, dl, TCVT);
12307       break;
12308     case 'N':  // "N" is a positive constant that is an exact power of two.
12309       if (Value > 0 && isPowerOf2_64(Value))
12310         Result = DAG.getTargetConstant(Value, dl, TCVT);
12311       break;
12312     case 'O':  // "O" is the constant zero.
12313       if (Value == 0)
12314         Result = DAG.getTargetConstant(Value, dl, TCVT);
12315       break;
12316     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
12317       if (isInt<16>(-Value))
12318         Result = DAG.getTargetConstant(Value, dl, TCVT);
12319       break;
12320     }
12321     break;
12322   }
12323   }
12324
12325   if (Result.getNode()) {
12326     Ops.push_back(Result);
12327     return;
12328   }
12329
12330   // Handle standard constraint letters.
12331   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12332 }
12333
12334 // isLegalAddressingMode - Return true if the addressing mode represented
12335 // by AM is legal for this target, for a load/store of the specified type.
12336 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12337                                               const AddrMode &AM, Type *Ty,
12338                                               unsigned AS) const {
12339   // PPC does not allow r+i addressing modes for vectors!
12340   if (Ty->isVectorTy() && AM.BaseOffs != 0)
12341     return false;
12342
12343   // PPC allows a sign-extended 16-bit immediate field.
12344   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12345     return false;
12346
12347   // No global is ever allowed as a base.
12348   if (AM.BaseGV)
12349     return false;
12350
12351   // PPC only support r+r,
12352   switch (AM.Scale) {
12353   case 0:  // "r+i" or just "i", depending on HasBaseReg.
12354     break;
12355   case 1:
12356     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
12357       return false;
12358     // Otherwise we have r+r or r+i.
12359     break;
12360   case 2:
12361     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
12362       return false;
12363     // Allow 2*r as r+r.
12364     break;
12365   default:
12366     // No other scales are supported.
12367     return false;
12368   }
12369
12370   return true;
12371 }
12372
12373 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12374                                            SelectionDAG &DAG) const {
12375   MachineFunction &MF = DAG.getMachineFunction();
12376   MachineFrameInfo &MFI = MF.getFrameInfo();
12377   MFI.setReturnAddressIsTaken(true);
12378
12379   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12380     return SDValue();
12381
12382   SDLoc dl(Op);
12383   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12384
12385   // Make sure the function does not optimize away the store of the RA to
12386   // the stack.
12387   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12388   FuncInfo->setLRStoreRequired();
12389   bool isPPC64 = Subtarget.isPPC64();
12390   auto PtrVT = getPointerTy(MF.getDataLayout());
12391
12392   if (Depth > 0) {
12393     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12394     SDValue Offset =
12395         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12396                         isPPC64 ? MVT::i64 : MVT::i32);
12397     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12398                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12399                        MachinePointerInfo());
12400   }
12401
12402   // Just load the return address off the stack.
12403   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12404   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12405                      MachinePointerInfo());
12406 }
12407
12408 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12409                                           SelectionDAG &DAG) const {
12410   SDLoc dl(Op);
12411   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12412
12413   MachineFunction &MF = DAG.getMachineFunction();
12414   MachineFrameInfo &MFI = MF.getFrameInfo();
12415   MFI.setFrameAddressIsTaken(true);
12416
12417   EVT PtrVT = getPointerTy(MF.getDataLayout());
12418   bool isPPC64 = PtrVT == MVT::i64;
12419
12420   // Naked functions never have a frame pointer, and so we use r1. For all
12421   // other functions, this decision must be delayed until during PEI.
12422   unsigned FrameReg;
12423   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12424     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12425   else
12426     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12427
12428   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12429                                          PtrVT);
12430   while (Depth--)
12431     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12432                             FrameAddr, MachinePointerInfo());
12433   return FrameAddr;
12434 }
12435
12436 // FIXME? Maybe this could be a TableGen attribute on some registers and
12437 // this table could be generated automatically from RegInfo.
12438 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12439                                               SelectionDAG &DAG) const {
12440   bool isPPC64 = Subtarget.isPPC64();
12441   bool isDarwinABI = Subtarget.isDarwinABI();
12442
12443   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12444       (!isPPC64 && VT != MVT::i32))
12445     report_fatal_error("Invalid register global variable type");
12446
12447   bool is64Bit = isPPC64 && VT == MVT::i64;
12448   unsigned Reg = StringSwitch<unsigned>(RegName)
12449                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12450                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12451                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12452                                   (is64Bit ? PPC::X13 : PPC::R13))
12453                    .Default(0);
12454
12455   if (Reg)
12456     return Reg;
12457   report_fatal_error("Invalid register name global variable");
12458 }
12459
12460 bool
12461 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12462   // The PowerPC target isn't yet aware of offsets.
12463   return false;
12464 }
12465
12466 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12467                                            const CallInst &I,
12468                                            unsigned Intrinsic) const {
12469   switch (Intrinsic) {
12470   case Intrinsic::ppc_qpx_qvlfd:
12471   case Intrinsic::ppc_qpx_qvlfs:
12472   case Intrinsic::ppc_qpx_qvlfcd:
12473   case Intrinsic::ppc_qpx_qvlfcs:
12474   case Intrinsic::ppc_qpx_qvlfiwa:
12475   case Intrinsic::ppc_qpx_qvlfiwz:
12476   case Intrinsic::ppc_altivec_lvx:
12477   case Intrinsic::ppc_altivec_lvxl:
12478   case Intrinsic::ppc_altivec_lvebx:
12479   case Intrinsic::ppc_altivec_lvehx:
12480   case Intrinsic::ppc_altivec_lvewx:
12481   case Intrinsic::ppc_vsx_lxvd2x:
12482   case Intrinsic::ppc_vsx_lxvw4x: {
12483     EVT VT;
12484     switch (Intrinsic) {
12485     case Intrinsic::ppc_altivec_lvebx:
12486       VT = MVT::i8;
12487       break;
12488     case Intrinsic::ppc_altivec_lvehx:
12489       VT = MVT::i16;
12490       break;
12491     case Intrinsic::ppc_altivec_lvewx:
12492       VT = MVT::i32;
12493       break;
12494     case Intrinsic::ppc_vsx_lxvd2x:
12495       VT = MVT::v2f64;
12496       break;
12497     case Intrinsic::ppc_qpx_qvlfd:
12498       VT = MVT::v4f64;
12499       break;
12500     case Intrinsic::ppc_qpx_qvlfs:
12501       VT = MVT::v4f32;
12502       break;
12503     case Intrinsic::ppc_qpx_qvlfcd:
12504       VT = MVT::v2f64;
12505       break;
12506     case Intrinsic::ppc_qpx_qvlfcs:
12507       VT = MVT::v2f32;
12508       break;
12509     default:
12510       VT = MVT::v4i32;
12511       break;
12512     }
12513
12514     Info.opc = ISD::INTRINSIC_W_CHAIN;
12515     Info.memVT = VT;
12516     Info.ptrVal = I.getArgOperand(0);
12517     Info.offset = -VT.getStoreSize()+1;
12518     Info.size = 2*VT.getStoreSize()-1;
12519     Info.align = 1;
12520     Info.vol = false;
12521     Info.readMem = true;
12522     Info.writeMem = false;
12523     return true;
12524   }
12525   case Intrinsic::ppc_qpx_qvlfda:
12526   case Intrinsic::ppc_qpx_qvlfsa:
12527   case Intrinsic::ppc_qpx_qvlfcda:
12528   case Intrinsic::ppc_qpx_qvlfcsa:
12529   case Intrinsic::ppc_qpx_qvlfiwaa:
12530   case Intrinsic::ppc_qpx_qvlfiwza: {
12531     EVT VT;
12532     switch (Intrinsic) {
12533     case Intrinsic::ppc_qpx_qvlfda:
12534       VT = MVT::v4f64;
12535       break;
12536     case Intrinsic::ppc_qpx_qvlfsa:
12537       VT = MVT::v4f32;
12538       break;
12539     case Intrinsic::ppc_qpx_qvlfcda:
12540       VT = MVT::v2f64;
12541       break;
12542     case Intrinsic::ppc_qpx_qvlfcsa:
12543       VT = MVT::v2f32;
12544       break;
12545     default:
12546       VT = MVT::v4i32;
12547       break;
12548     }
12549
12550     Info.opc = ISD::INTRINSIC_W_CHAIN;
12551     Info.memVT = VT;
12552     Info.ptrVal = I.getArgOperand(0);
12553     Info.offset = 0;
12554     Info.size = VT.getStoreSize();
12555     Info.align = 1;
12556     Info.vol = false;
12557     Info.readMem = true;
12558     Info.writeMem = false;
12559     return true;
12560   }
12561   case Intrinsic::ppc_qpx_qvstfd:
12562   case Intrinsic::ppc_qpx_qvstfs:
12563   case Intrinsic::ppc_qpx_qvstfcd:
12564   case Intrinsic::ppc_qpx_qvstfcs:
12565   case Intrinsic::ppc_qpx_qvstfiw:
12566   case Intrinsic::ppc_altivec_stvx:
12567   case Intrinsic::ppc_altivec_stvxl:
12568   case Intrinsic::ppc_altivec_stvebx:
12569   case Intrinsic::ppc_altivec_stvehx:
12570   case Intrinsic::ppc_altivec_stvewx:
12571   case Intrinsic::ppc_vsx_stxvd2x:
12572   case Intrinsic::ppc_vsx_stxvw4x: {
12573     EVT VT;
12574     switch (Intrinsic) {
12575     case Intrinsic::ppc_altivec_stvebx:
12576       VT = MVT::i8;
12577       break;
12578     case Intrinsic::ppc_altivec_stvehx:
12579       VT = MVT::i16;
12580       break;
12581     case Intrinsic::ppc_altivec_stvewx:
12582       VT = MVT::i32;
12583       break;
12584     case Intrinsic::ppc_vsx_stxvd2x:
12585       VT = MVT::v2f64;
12586       break;
12587     case Intrinsic::ppc_qpx_qvstfd:
12588       VT = MVT::v4f64;
12589       break;
12590     case Intrinsic::ppc_qpx_qvstfs:
12591       VT = MVT::v4f32;
12592       break;
12593     case Intrinsic::ppc_qpx_qvstfcd:
12594       VT = MVT::v2f64;
12595       break;
12596     case Intrinsic::ppc_qpx_qvstfcs:
12597       VT = MVT::v2f32;
12598       break;
12599     default:
12600       VT = MVT::v4i32;
12601       break;
12602     }
12603
12604     Info.opc = ISD::INTRINSIC_VOID;
12605     Info.memVT = VT;
12606     Info.ptrVal = I.getArgOperand(1);
12607     Info.offset = -VT.getStoreSize()+1;
12608     Info.size = 2*VT.getStoreSize()-1;
12609     Info.align = 1;
12610     Info.vol = false;
12611     Info.readMem = false;
12612     Info.writeMem = true;
12613     return true;
12614   }
12615   case Intrinsic::ppc_qpx_qvstfda:
12616   case Intrinsic::ppc_qpx_qvstfsa:
12617   case Intrinsic::ppc_qpx_qvstfcda:
12618   case Intrinsic::ppc_qpx_qvstfcsa:
12619   case Intrinsic::ppc_qpx_qvstfiwa: {
12620     EVT VT;
12621     switch (Intrinsic) {
12622     case Intrinsic::ppc_qpx_qvstfda:
12623       VT = MVT::v4f64;
12624       break;
12625     case Intrinsic::ppc_qpx_qvstfsa:
12626       VT = MVT::v4f32;
12627       break;
12628     case Intrinsic::ppc_qpx_qvstfcda:
12629       VT = MVT::v2f64;
12630       break;
12631     case Intrinsic::ppc_qpx_qvstfcsa:
12632       VT = MVT::v2f32;
12633       break;
12634     default:
12635       VT = MVT::v4i32;
12636       break;
12637     }
12638
12639     Info.opc = ISD::INTRINSIC_VOID;
12640     Info.memVT = VT;
12641     Info.ptrVal = I.getArgOperand(1);
12642     Info.offset = 0;
12643     Info.size = VT.getStoreSize();
12644     Info.align = 1;
12645     Info.vol = false;
12646     Info.readMem = false;
12647     Info.writeMem = true;
12648     return true;
12649   }
12650   default:
12651     break;
12652   }
12653
12654   return false;
12655 }
12656
12657 /// getOptimalMemOpType - Returns the target specific optimal type for load
12658 /// and store operations as a result of memset, memcpy, and memmove
12659 /// lowering. If DstAlign is zero that means it's safe to destination
12660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12661 /// means there isn't a need to check it against alignment requirement,
12662 /// probably because the source does not need to be loaded. If 'IsMemset' is
12663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12665 /// source is constant so it does not need to be loaded.
12666 /// It returns EVT::Other if the type should be determined using generic
12667 /// target-independent logic.
12668 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12669                                            unsigned DstAlign, unsigned SrcAlign,
12670                                            bool IsMemset, bool ZeroMemset,
12671                                            bool MemcpyStrSrc,
12672                                            MachineFunction &MF) const {
12673   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12674     const Function *F = MF.getFunction();
12675     // When expanding a memset, require at least two QPX instructions to cover
12676     // the cost of loading the value to be stored from the constant pool.
12677     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12678        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12679         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12680       return MVT::v4f64;
12681     }
12682
12683     // We should use Altivec/VSX loads and stores when available. For unaligned
12684     // addresses, unaligned VSX loads are only fast starting with the P8.
12685     if (Subtarget.hasAltivec() && Size >= 16 &&
12686         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12687          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12688       return MVT::v4i32;
12689   }
12690
12691   if (Subtarget.isPPC64()) {
12692     return MVT::i64;
12693   }
12694
12695   return MVT::i32;
12696 }
12697
12698 /// \brief Returns true if it is beneficial to convert a load of a constant
12699 /// to just the constant itself.
12700 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12701                                                           Type *Ty) const {
12702   assert(Ty->isIntegerTy());
12703
12704   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12705   return !(BitSize == 0 || BitSize > 64);
12706 }
12707
12708 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12709   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12710     return false;
12711   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12712   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12713   return NumBits1 == 64 && NumBits2 == 32;
12714 }
12715
12716 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12717   if (!VT1.isInteger() || !VT2.isInteger())
12718     return false;
12719   unsigned NumBits1 = VT1.getSizeInBits();
12720   unsigned NumBits2 = VT2.getSizeInBits();
12721   return NumBits1 == 64 && NumBits2 == 32;
12722 }
12723
12724 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12725   // Generally speaking, zexts are not free, but they are free when they can be
12726   // folded with other operations.
12727   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12728     EVT MemVT = LD->getMemoryVT();
12729     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12730          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12731         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12732          LD->getExtensionType() == ISD::ZEXTLOAD))
12733       return true;
12734   }
12735
12736   // FIXME: Add other cases...
12737   //  - 32-bit shifts with a zext to i64
12738   //  - zext after ctlz, bswap, etc.
12739   //  - zext after and by a constant mask
12740
12741   return TargetLowering::isZExtFree(Val, VT2);
12742 }
12743
12744 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12745   assert(VT.isFloatingPoint());
12746   return true;
12747 }
12748
12749 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12750   return isInt<16>(Imm) || isUInt<16>(Imm);
12751 }
12752
12753 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12754   return isInt<16>(Imm) || isUInt<16>(Imm);
12755 }
12756
12757 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12758                                                        unsigned,
12759                                                        unsigned,
12760                                                        bool *Fast) const {
12761   if (DisablePPCUnaligned)
12762     return false;
12763
12764   // PowerPC supports unaligned memory access for simple non-vector types.
12765   // Although accessing unaligned addresses is not as efficient as accessing
12766   // aligned addresses, it is generally more efficient than manual expansion,
12767   // and generally only traps for software emulation when crossing page
12768   // boundaries.
12769
12770   if (!VT.isSimple())
12771     return false;
12772
12773   if (VT.getSimpleVT().isVector()) {
12774     if (Subtarget.hasVSX()) {
12775       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12776           VT != MVT::v4f32 && VT != MVT::v4i32)
12777         return false;
12778     } else {
12779       return false;
12780     }
12781   }
12782
12783   if (VT == MVT::ppcf128)
12784     return false;
12785
12786   if (Fast)
12787     *Fast = true;
12788
12789   return true;
12790 }
12791
12792 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12793   VT = VT.getScalarType();
12794
12795   if (!VT.isSimple())
12796     return false;
12797
12798   switch (VT.getSimpleVT().SimpleTy) {
12799   case MVT::f32:
12800   case MVT::f64:
12801     return true;
12802   default:
12803     break;
12804   }
12805
12806   return false;
12807 }
12808
12809 const MCPhysReg *
12810 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12811   // LR is a callee-save register, but we must treat it as clobbered by any call
12812   // site. Hence we include LR in the scratch registers, which are in turn added
12813   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12814   // to CTR, which is used by any indirect call.
12815   static const MCPhysReg ScratchRegs[] = {
12816     PPC::X12, PPC::LR8, PPC::CTR8, 0
12817   };
12818
12819   return ScratchRegs;
12820 }
12821
12822 unsigned PPCTargetLowering::getExceptionPointerRegister(
12823     const Constant *PersonalityFn) const {
12824   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12825 }
12826
12827 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12828     const Constant *PersonalityFn) const {
12829   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12830 }
12831
12832 bool
12833 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12834                      EVT VT , unsigned DefinedValues) const {
12835   if (VT == MVT::v2i64)
12836     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12837
12838   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12839     return true;
12840
12841   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12842 }
12843
12844 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12845   if (DisableILPPref || Subtarget.enableMachineScheduler())
12846     return TargetLowering::getSchedulingPreference(N);
12847
12848   return Sched::ILP;
12849 }
12850
12851 // Create a fast isel object.
12852 FastISel *
12853 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12854                                   const TargetLibraryInfo *LibInfo) const {
12855   return PPC::createFastISel(FuncInfo, LibInfo);
12856 }
12857
12858 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12859   if (Subtarget.isDarwinABI()) return;
12860   if (!Subtarget.isPPC64()) return;
12861
12862   // Update IsSplitCSR in PPCFunctionInfo
12863   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12864   PFI->setIsSplitCSR(true);
12865 }
12866
12867 void PPCTargetLowering::insertCopiesSplitCSR(
12868   MachineBasicBlock *Entry,
12869   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12870   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12871   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12872   if (!IStart)
12873     return;
12874
12875   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12876   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12877   MachineBasicBlock::iterator MBBI = Entry->begin();
12878   for (const MCPhysReg *I = IStart; *I; ++I) {
12879     const TargetRegisterClass *RC = nullptr;
12880     if (PPC::G8RCRegClass.contains(*I))
12881       RC = &PPC::G8RCRegClass;
12882     else if (PPC::F8RCRegClass.contains(*I))
12883       RC = &PPC::F8RCRegClass;
12884     else if (PPC::CRRCRegClass.contains(*I))
12885       RC = &PPC::CRRCRegClass;
12886     else if (PPC::VRRCRegClass.contains(*I))
12887       RC = &PPC::VRRCRegClass;
12888     else
12889       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12890
12891     unsigned NewVR = MRI->createVirtualRegister(RC);
12892     // Create copy from CSR to a virtual register.
12893     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12894     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12895     // nounwind. If we want to generalize this later, we may need to emit
12896     // CFI pseudo-instructions.
12897     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12898              Attribute::NoUnwind) &&
12899            "Function should be nounwind in insertCopiesSplitCSR!");
12900     Entry->addLiveIn(*I);
12901     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12902       .addReg(*I);
12903
12904     // Insert the copy-back instructions right before the terminator
12905     for (auto *Exit : Exits)
12906       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12907               TII->get(TargetOpcode::COPY), *I)
12908         .addReg(NewVR);
12909   }
12910 }
12911
12912 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12913 bool PPCTargetLowering::useLoadStackGuardNode() const {
12914   if (!Subtarget.isTargetLinux())
12915     return TargetLowering::useLoadStackGuardNode();
12916   return true;
12917 }
12918
12919 // Override to disable global variable loading on Linux.
12920 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12921   if (!Subtarget.isTargetLinux())
12922     return TargetLowering::insertSSPDeclarations(M);
12923 }
12924
12925 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12926   if (!VT.isSimple() || !Subtarget.hasVSX())
12927     return false;
12928
12929   switch(VT.getSimpleVT().SimpleTy) {
12930   default:
12931     // For FP types that are currently not supported by PPC backend, return
12932     // false. Examples: f16, f80.
12933     return false;
12934   case MVT::f32:
12935   case MVT::f64:
12936   case MVT::ppcf128:
12937     return Imm.isPosZero();
12938   }
12939 }