1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "MCTargetDesc/PPCPredicates.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/KnownBits.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetLowering.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include "llvm/Target/TargetRegisterInfo.h"
100 #define DEBUG_TYPE "ppc-lowering"
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumSiblingCalls, "Number of sibling calls");
117 // FIXME: Remove this once the bug has been fixed!
118 extern cl::opt<bool> ANDIGlueBug;
120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
121 const PPCSubtarget &STI)
122 : TargetLowering(TM), Subtarget(STI) {
123 // Use _setjmp/_longjmp instead of setjmp/longjmp.
124 setUseUnderscoreSetJmp(true);
125 setUseUnderscoreLongJmp(true);
127 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
128 // arguments are at least 4/8 bytes aligned.
129 bool isPPC64 = Subtarget.isPPC64();
130 setMinStackArgumentAlignment(isPPC64 ? 8:4);
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
134 if (!useSoftFloat()) {
135 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
136 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
139 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
140 for (MVT VT : MVT::integer_valuetypes()) {
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
145 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
147 // PowerPC has pre-inc load and store's.
148 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
149 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
150 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
151 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
152 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
153 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
154 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
155 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
156 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
157 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
158 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
159 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
160 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
161 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
163 if (Subtarget.useCRBits()) {
164 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
166 if (isPPC64 || Subtarget.hasFPCVT()) {
167 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
168 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
169 isPPC64 ? MVT::i64 : MVT::i32);
170 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
171 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
172 isPPC64 ? MVT::i64 : MVT::i32);
174 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
175 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
178 // PowerPC does not support direct load / store of condition registers
179 setOperationAction(ISD::LOAD, MVT::i1, Custom);
180 setOperationAction(ISD::STORE, MVT::i1, Custom);
182 // FIXME: Remove this once the ANDI glue bug is fixed:
184 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
186 for (MVT VT : MVT::integer_valuetypes()) {
187 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
189 setTruncStoreAction(VT, MVT::i1, Expand);
192 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
195 // This is used in the ppcf128->int sequence. Note it has different semantics
196 // from FP_ROUND: that rounds to nearest, this rounds to zero.
197 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
199 // We do not currently implement these libm ops for PowerPC.
200 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
201 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
202 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
203 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
204 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
205 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
207 // PowerPC has no SREM/UREM instructions
208 setOperationAction(ISD::SREM, MVT::i32, Expand);
209 setOperationAction(ISD::UREM, MVT::i32, Expand);
210 setOperationAction(ISD::SREM, MVT::i64, Expand);
211 setOperationAction(ISD::UREM, MVT::i64, Expand);
213 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
214 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
215 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
216 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
217 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
218 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
219 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
220 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
221 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
223 // We don't support sin/cos/sqrt/fmod/pow
224 setOperationAction(ISD::FSIN , MVT::f64, Expand);
225 setOperationAction(ISD::FCOS , MVT::f64, Expand);
226 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
227 setOperationAction(ISD::FREM , MVT::f64, Expand);
228 setOperationAction(ISD::FPOW , MVT::f64, Expand);
229 setOperationAction(ISD::FMA , MVT::f64, Legal);
230 setOperationAction(ISD::FSIN , MVT::f32, Expand);
231 setOperationAction(ISD::FCOS , MVT::f32, Expand);
232 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
233 setOperationAction(ISD::FREM , MVT::f32, Expand);
234 setOperationAction(ISD::FPOW , MVT::f32, Expand);
235 setOperationAction(ISD::FMA , MVT::f32, Legal);
237 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
239 // If we're enabling GP optimizations, use hardware square root
240 if (!Subtarget.hasFSQRT() &&
241 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
243 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
245 if (!Subtarget.hasFSQRT() &&
246 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
247 Subtarget.hasFRES()))
248 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
250 if (Subtarget.hasFCPSGN()) {
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
252 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
254 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
255 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
258 if (Subtarget.hasFPRND()) {
259 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
260 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
261 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
262 setOperationAction(ISD::FROUND, MVT::f64, Legal);
264 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
265 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
266 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
267 setOperationAction(ISD::FROUND, MVT::f32, Legal);
270 // PowerPC does not have BSWAP
271 // CTPOP or CTTZ were introduced in P8/P9 respectivelly
272 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
273 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
274 if (Subtarget.isISA3_0()) {
275 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
276 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
278 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
279 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
282 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
283 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
284 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
286 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
287 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
290 // PowerPC does not have ROTR
291 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
292 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
294 if (!Subtarget.useCRBits()) {
295 // PowerPC does not have Select
296 setOperationAction(ISD::SELECT, MVT::i32, Expand);
297 setOperationAction(ISD::SELECT, MVT::i64, Expand);
298 setOperationAction(ISD::SELECT, MVT::f32, Expand);
299 setOperationAction(ISD::SELECT, MVT::f64, Expand);
302 // PowerPC wants to turn select_cc of FP into fsel when possible.
303 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
304 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
306 // PowerPC wants to optimize integer setcc a bit
307 if (!Subtarget.useCRBits())
308 setOperationAction(ISD::SETCC, MVT::i32, Custom);
310 // PowerPC does not have BRCOND which requires SetCC
311 if (!Subtarget.useCRBits())
312 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
314 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
316 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
317 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
319 // PowerPC does not have [U|S]INT_TO_FP
320 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
321 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
323 if (Subtarget.hasDirectMove() && isPPC64) {
324 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
325 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
326 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
327 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
329 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
330 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
331 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
332 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
335 // We cannot sextinreg(i1). Expand to shifts.
336 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
338 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
339 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
340 // support continuation, user-level threading, and etc.. As a result, no
341 // other SjLj exception interfaces are implemented and please don't build
342 // your own exception handling based on them.
343 // LLVM/Clang supports zero-cost DWARF exception handling.
344 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
345 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
347 // We want to legalize GlobalAddress and ConstantPool nodes into the
348 // appropriate instructions to materialize the address.
349 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
350 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
351 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
352 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
353 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
354 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
355 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
356 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
357 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
358 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
361 setOperationAction(ISD::TRAP, MVT::Other, Legal);
363 // TRAMPOLINE is custom lowered.
364 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
365 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
367 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
368 setOperationAction(ISD::VASTART , MVT::Other, Custom);
370 if (Subtarget.isSVR4ABI()) {
372 // VAARG always uses double-word chunks, so promote anything smaller.
373 setOperationAction(ISD::VAARG, MVT::i1, Promote);
374 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
375 setOperationAction(ISD::VAARG, MVT::i8, Promote);
376 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
377 setOperationAction(ISD::VAARG, MVT::i16, Promote);
378 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
379 setOperationAction(ISD::VAARG, MVT::i32, Promote);
380 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
381 setOperationAction(ISD::VAARG, MVT::Other, Expand);
383 // VAARG is custom lowered with the 32-bit SVR4 ABI.
384 setOperationAction(ISD::VAARG, MVT::Other, Custom);
385 setOperationAction(ISD::VAARG, MVT::i64, Custom);
388 setOperationAction(ISD::VAARG, MVT::Other, Expand);
390 if (Subtarget.isSVR4ABI() && !isPPC64)
391 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
392 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
394 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
396 // Use the default implementation.
397 setOperationAction(ISD::VAEND , MVT::Other, Expand);
398 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
399 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
400 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
401 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
402 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
403 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
404 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
405 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
407 // We want to custom lower some of our intrinsics.
408 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
410 // To handle counter-based loop conditions.
411 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
413 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
414 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
415 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
416 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
418 // Comparisons that require checking two conditions.
419 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
420 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
421 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
422 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
423 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
424 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
425 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
426 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
427 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
428 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
429 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
430 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
432 if (Subtarget.has64BitSupport()) {
433 // They also have instructions for converting between i64 and fp.
434 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
435 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
436 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
437 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
438 // This is just the low 32 bits of a (signed) fp->i64 conversion.
439 // We cannot do this with Promote because i64 is not a legal type.
440 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
442 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
443 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
445 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
446 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
449 // With the instructions enabled under FPCVT, we can do everything.
450 if (Subtarget.hasFPCVT()) {
451 if (Subtarget.has64BitSupport()) {
452 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
453 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
454 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
455 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
458 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
459 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
460 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
461 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
464 if (Subtarget.use64BitRegs()) {
465 // 64-bit PowerPC implementations can support i64 types directly
466 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
467 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
468 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
469 // 64-bit PowerPC wants to expand i128 shifts itself.
470 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
471 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
472 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
474 // 32-bit PowerPC wants to expand i64 shifts itself.
475 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
476 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
477 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
480 if (Subtarget.hasAltivec()) {
481 // First set operation action for all vector types to expand. Then we
482 // will selectively turn on ones that can be effectively codegen'd.
483 for (MVT VT : MVT::vector_valuetypes()) {
484 // add/sub are legal for all supported vector VT's.
485 setOperationAction(ISD::ADD, VT, Legal);
486 setOperationAction(ISD::SUB, VT, Legal);
488 // Vector instructions introduced in P8
489 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
490 setOperationAction(ISD::CTPOP, VT, Legal);
491 setOperationAction(ISD::CTLZ, VT, Legal);
494 setOperationAction(ISD::CTPOP, VT, Expand);
495 setOperationAction(ISD::CTLZ, VT, Expand);
498 // Vector instructions introduced in P9
499 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
500 setOperationAction(ISD::CTTZ, VT, Legal);
502 setOperationAction(ISD::CTTZ, VT, Expand);
504 // We promote all shuffles to v16i8.
505 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
506 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
508 // We promote all non-typed operations to v4i32.
509 setOperationAction(ISD::AND , VT, Promote);
510 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
511 setOperationAction(ISD::OR , VT, Promote);
512 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
513 setOperationAction(ISD::XOR , VT, Promote);
514 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
515 setOperationAction(ISD::LOAD , VT, Promote);
516 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
517 setOperationAction(ISD::SELECT, VT, Promote);
518 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
519 setOperationAction(ISD::SELECT_CC, VT, Promote);
520 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
521 setOperationAction(ISD::STORE, VT, Promote);
522 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
524 // No other operations are legal.
525 setOperationAction(ISD::MUL , VT, Expand);
526 setOperationAction(ISD::SDIV, VT, Expand);
527 setOperationAction(ISD::SREM, VT, Expand);
528 setOperationAction(ISD::UDIV, VT, Expand);
529 setOperationAction(ISD::UREM, VT, Expand);
530 setOperationAction(ISD::FDIV, VT, Expand);
531 setOperationAction(ISD::FREM, VT, Expand);
532 setOperationAction(ISD::FNEG, VT, Expand);
533 setOperationAction(ISD::FSQRT, VT, Expand);
534 setOperationAction(ISD::FLOG, VT, Expand);
535 setOperationAction(ISD::FLOG10, VT, Expand);
536 setOperationAction(ISD::FLOG2, VT, Expand);
537 setOperationAction(ISD::FEXP, VT, Expand);
538 setOperationAction(ISD::FEXP2, VT, Expand);
539 setOperationAction(ISD::FSIN, VT, Expand);
540 setOperationAction(ISD::FCOS, VT, Expand);
541 setOperationAction(ISD::FABS, VT, Expand);
542 setOperationAction(ISD::FPOWI, VT, Expand);
543 setOperationAction(ISD::FFLOOR, VT, Expand);
544 setOperationAction(ISD::FCEIL, VT, Expand);
545 setOperationAction(ISD::FTRUNC, VT, Expand);
546 setOperationAction(ISD::FRINT, VT, Expand);
547 setOperationAction(ISD::FNEARBYINT, VT, Expand);
548 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
549 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
550 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
551 setOperationAction(ISD::MULHU, VT, Expand);
552 setOperationAction(ISD::MULHS, VT, Expand);
553 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
554 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
555 setOperationAction(ISD::UDIVREM, VT, Expand);
556 setOperationAction(ISD::SDIVREM, VT, Expand);
557 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
558 setOperationAction(ISD::FPOW, VT, Expand);
559 setOperationAction(ISD::BSWAP, VT, Expand);
560 setOperationAction(ISD::VSELECT, VT, Expand);
561 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
562 setOperationAction(ISD::ROTL, VT, Expand);
563 setOperationAction(ISD::ROTR, VT, Expand);
565 for (MVT InnerVT : MVT::vector_valuetypes()) {
566 setTruncStoreAction(VT, InnerVT, Expand);
567 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
568 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
569 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
573 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
574 // with merges, splats, etc.
575 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
577 setOperationAction(ISD::AND , MVT::v4i32, Legal);
578 setOperationAction(ISD::OR , MVT::v4i32, Legal);
579 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
580 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
581 setOperationAction(ISD::SELECT, MVT::v4i32,
582 Subtarget.useCRBits() ? Legal : Expand);
583 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
584 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
585 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
586 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
587 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
588 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
589 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
590 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
591 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
593 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
594 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
595 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
596 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
598 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
599 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
601 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
602 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
603 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
606 if (Subtarget.hasP8Altivec())
607 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
609 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
611 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
612 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
614 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
615 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
620 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
622 // Altivec does not contain unordered floating-point compare instructions
623 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
624 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
625 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
626 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
628 if (Subtarget.hasVSX()) {
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
630 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
631 if (Subtarget.hasP8Vector()) {
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
633 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
635 if (Subtarget.hasDirectMove() && isPPC64) {
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
637 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
638 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
640 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
641 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
642 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
643 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
645 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
647 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
648 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
649 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
650 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
651 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
653 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
655 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
656 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
658 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
659 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
661 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
662 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
663 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
664 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
665 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
667 // Share the Altivec comparison restrictions.
668 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
669 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
670 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
671 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
673 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
674 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
676 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
678 if (Subtarget.hasP8Vector())
679 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
681 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
683 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
684 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
685 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
687 if (Subtarget.hasP8Altivec()) {
688 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
689 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
690 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
692 // 128 bit shifts can be accomplished via 3 instructions for SHL and
693 // SRL, but not for SRA because of the instructions available:
694 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
696 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
697 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
698 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
700 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
703 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
704 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
705 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
707 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
709 // VSX v2i64 only supports non-arithmetic operations.
710 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
711 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
714 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
715 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
716 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
717 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
719 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
721 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
722 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
723 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
724 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
726 // Vector operation legalization checks the result type of
727 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
728 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
729 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
730 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
731 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
733 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
734 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
735 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
736 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
738 if (Subtarget.hasDirectMove())
739 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
740 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
742 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
745 if (Subtarget.hasP8Altivec()) {
746 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
747 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
750 if (Subtarget.hasP9Vector()) {
751 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
752 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
754 // 128 bit shifts can be accomplished via 3 instructions for SHL and
755 // SRL, but not for SRA because of the instructions available:
756 // VS{RL} and VS{RL}O.
757 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
758 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
759 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
763 if (Subtarget.hasQPX()) {
764 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
765 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
766 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
767 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
769 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
770 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
772 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
773 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
775 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
776 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
778 if (!Subtarget.useCRBits())
779 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
780 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
782 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
783 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
784 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
785 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
786 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
787 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
788 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
790 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
791 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
793 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
794 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
795 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
797 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
798 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
799 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
800 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
801 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
802 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
803 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
804 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
805 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
806 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
807 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
809 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
810 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
812 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
813 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
815 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
817 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
818 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
819 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
820 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
822 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
823 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
825 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
826 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
828 if (!Subtarget.useCRBits())
829 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
830 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
833 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
834 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
835 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
836 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
838 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
840 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
841 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
843 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
844 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
845 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
846 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
847 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
848 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
849 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
850 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
851 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
852 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
853 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
855 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
856 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
858 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
859 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
861 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
863 setOperationAction(ISD::AND , MVT::v4i1, Legal);
864 setOperationAction(ISD::OR , MVT::v4i1, Legal);
865 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
867 if (!Subtarget.useCRBits())
868 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
869 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
871 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
872 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
874 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
876 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
877 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
878 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
879 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
880 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
882 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
883 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
885 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
887 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
888 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
889 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
890 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
892 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
893 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
894 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
895 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
897 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
898 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
900 // These need to set FE_INEXACT, and so cannot be vectorized here.
901 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
902 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
904 if (TM.Options.UnsafeFPMath) {
905 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
906 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
908 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
909 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
911 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
912 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
914 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
915 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
919 if (Subtarget.has64BitSupport())
920 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
922 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
925 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
926 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
929 setBooleanContents(ZeroOrOneBooleanContent);
931 if (Subtarget.hasAltivec()) {
932 // Altivec instructions set fields to all zeros or all ones.
933 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
937 // These libcalls are not available in 32-bit.
938 setLibcallName(RTLIB::SHL_I128, nullptr);
939 setLibcallName(RTLIB::SRL_I128, nullptr);
940 setLibcallName(RTLIB::SRA_I128, nullptr);
943 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
945 // We have target-specific dag combine patterns for the following nodes:
946 setTargetDAGCombine(ISD::SHL);
947 setTargetDAGCombine(ISD::SRA);
948 setTargetDAGCombine(ISD::SRL);
949 setTargetDAGCombine(ISD::SINT_TO_FP);
950 setTargetDAGCombine(ISD::BUILD_VECTOR);
951 if (Subtarget.hasFPCVT())
952 setTargetDAGCombine(ISD::UINT_TO_FP);
953 setTargetDAGCombine(ISD::LOAD);
954 setTargetDAGCombine(ISD::STORE);
955 setTargetDAGCombine(ISD::BR_CC);
956 if (Subtarget.useCRBits())
957 setTargetDAGCombine(ISD::BRCOND);
958 setTargetDAGCombine(ISD::BSWAP);
959 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
960 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
961 setTargetDAGCombine(ISD::INTRINSIC_VOID);
963 setTargetDAGCombine(ISD::SIGN_EXTEND);
964 setTargetDAGCombine(ISD::ZERO_EXTEND);
965 setTargetDAGCombine(ISD::ANY_EXTEND);
967 if (Subtarget.useCRBits()) {
968 setTargetDAGCombine(ISD::TRUNCATE);
969 setTargetDAGCombine(ISD::SETCC);
970 setTargetDAGCombine(ISD::SELECT_CC);
973 // Use reciprocal estimates.
974 if (TM.Options.UnsafeFPMath) {
975 setTargetDAGCombine(ISD::FDIV);
976 setTargetDAGCombine(ISD::FSQRT);
979 // Darwin long double math library functions have $LDBL128 appended.
980 if (Subtarget.isDarwin()) {
981 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
982 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
983 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
984 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
985 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
986 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
987 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
988 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
989 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
990 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
993 // With 32 condition bits, we don't need to sink (and duplicate) compares
994 // aggressively in CodeGenPrep.
995 if (Subtarget.useCRBits()) {
996 setHasMultipleConditionRegisters();
997 setJumpIsExpensive();
1000 setMinFunctionAlignment(2);
1001 if (Subtarget.isDarwin())
1002 setPrefFunctionAlignment(4);
1004 switch (Subtarget.getDarwinDirective()) {
1008 case PPC::DIR_E500mc:
1009 case PPC::DIR_E5500:
1012 case PPC::DIR_PWR5X:
1014 case PPC::DIR_PWR6X:
1018 setPrefFunctionAlignment(4);
1019 setPrefLoopAlignment(4);
1023 if (Subtarget.enableMachineScheduler())
1024 setSchedulingPreference(Sched::Source);
1026 setSchedulingPreference(Sched::Hybrid);
1028 computeRegisterProperties(STI.getRegisterInfo());
1030 // The Freescale cores do better with aggressive inlining of memcpy and
1031 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1032 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1033 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1034 MaxStoresPerMemset = 32;
1035 MaxStoresPerMemsetOptSize = 16;
1036 MaxStoresPerMemcpy = 32;
1037 MaxStoresPerMemcpyOptSize = 8;
1038 MaxStoresPerMemmove = 32;
1039 MaxStoresPerMemmoveOptSize = 8;
1040 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1041 // The A2 also benefits from (very) aggressive inlining of memcpy and
1042 // friends. The overhead of a the function call, even when warm, can be
1043 // over one hundred cycles.
1044 MaxStoresPerMemset = 128;
1045 MaxStoresPerMemcpy = 128;
1046 MaxStoresPerMemmove = 128;
1050 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1051 /// the desired ByVal argument alignment.
1052 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1053 unsigned MaxMaxAlign) {
1054 if (MaxAlign == MaxMaxAlign)
1056 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1057 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1059 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1061 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1062 unsigned EltAlign = 0;
1063 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1064 if (EltAlign > MaxAlign)
1065 MaxAlign = EltAlign;
1066 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1067 for (auto *EltTy : STy->elements()) {
1068 unsigned EltAlign = 0;
1069 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1070 if (EltAlign > MaxAlign)
1071 MaxAlign = EltAlign;
1072 if (MaxAlign == MaxMaxAlign)
1078 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1079 /// function arguments in the caller parameter area.
1080 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1081 const DataLayout &DL) const {
1082 // Darwin passes everything on 4 byte boundary.
1083 if (Subtarget.isDarwin())
1086 // 16byte and wider vectors are passed on 16byte boundary.
1087 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1088 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1089 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1090 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1094 bool PPCTargetLowering::useSoftFloat() const {
1095 return Subtarget.useSoftFloat();
1098 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1099 switch ((PPCISD::NodeType)Opcode) {
1100 case PPCISD::FIRST_NUMBER: break;
1101 case PPCISD::FSEL: return "PPCISD::FSEL";
1102 case PPCISD::FCFID: return "PPCISD::FCFID";
1103 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1104 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1105 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1106 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1107 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1108 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1109 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1110 case PPCISD::FRE: return "PPCISD::FRE";
1111 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1112 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1113 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1114 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1115 case PPCISD::VPERM: return "PPCISD::VPERM";
1116 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1117 case PPCISD::XXINSERT: return "PPCISD::XXINSERT";
1118 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1119 case PPCISD::CMPB: return "PPCISD::CMPB";
1120 case PPCISD::Hi: return "PPCISD::Hi";
1121 case PPCISD::Lo: return "PPCISD::Lo";
1122 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1123 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1124 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1125 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1126 case PPCISD::SRL: return "PPCISD::SRL";
1127 case PPCISD::SRA: return "PPCISD::SRA";
1128 case PPCISD::SHL: return "PPCISD::SHL";
1129 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1130 case PPCISD::CALL: return "PPCISD::CALL";
1131 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1132 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1133 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1134 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1135 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1136 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1137 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1138 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1139 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1140 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1141 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1142 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1143 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1144 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1145 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1146 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1147 case PPCISD::VCMP: return "PPCISD::VCMP";
1148 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1149 case PPCISD::LBRX: return "PPCISD::LBRX";
1150 case PPCISD::STBRX: return "PPCISD::STBRX";
1151 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1152 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1153 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1154 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1155 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1156 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1157 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1158 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1159 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1160 case PPCISD::BDZ: return "PPCISD::BDZ";
1161 case PPCISD::MFFS: return "PPCISD::MFFS";
1162 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1163 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1164 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1165 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1166 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1167 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1168 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1169 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1170 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1171 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1172 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1173 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1174 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1175 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1176 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1177 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1178 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1179 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1180 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1181 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1182 case PPCISD::SC: return "PPCISD::SC";
1183 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1184 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1185 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1186 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1187 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1188 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1189 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1190 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1191 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1192 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1193 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1198 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1201 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1203 if (Subtarget.hasQPX())
1204 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1206 return VT.changeVectorElementTypeToInteger();
1209 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1210 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1214 //===----------------------------------------------------------------------===//
1215 // Node matching predicates, for use by the tblgen matching code.
1216 //===----------------------------------------------------------------------===//
1218 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1219 static bool isFloatingPointZero(SDValue Op) {
1220 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1221 return CFP->getValueAPF().isZero();
1222 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1223 // Maybe this has already been legalized into the constant pool?
1224 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1225 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1226 return CFP->getValueAPF().isZero();
1231 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1232 /// true if Op is undef or if it matches the specified value.
1233 static bool isConstantOrUndef(int Op, int Val) {
1234 return Op < 0 || Op == Val;
1237 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1238 /// VPKUHUM instruction.
1239 /// The ShuffleKind distinguishes between big-endian operations with
1240 /// two different inputs (0), either-endian operations with two identical
1241 /// inputs (1), and little-endian operations with two different inputs (2).
1242 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1243 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1244 SelectionDAG &DAG) {
1245 bool IsLE = DAG.getDataLayout().isLittleEndian();
1246 if (ShuffleKind == 0) {
1249 for (unsigned i = 0; i != 16; ++i)
1250 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1252 } else if (ShuffleKind == 2) {
1255 for (unsigned i = 0; i != 16; ++i)
1256 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1258 } else if (ShuffleKind == 1) {
1259 unsigned j = IsLE ? 0 : 1;
1260 for (unsigned i = 0; i != 8; ++i)
1261 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1262 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1268 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1269 /// VPKUWUM instruction.
1270 /// The ShuffleKind distinguishes between big-endian operations with
1271 /// two different inputs (0), either-endian operations with two identical
1272 /// inputs (1), and little-endian operations with two different inputs (2).
1273 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1274 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1275 SelectionDAG &DAG) {
1276 bool IsLE = DAG.getDataLayout().isLittleEndian();
1277 if (ShuffleKind == 0) {
1280 for (unsigned i = 0; i != 16; i += 2)
1281 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1282 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1284 } else if (ShuffleKind == 2) {
1287 for (unsigned i = 0; i != 16; i += 2)
1288 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1289 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1291 } else if (ShuffleKind == 1) {
1292 unsigned j = IsLE ? 0 : 2;
1293 for (unsigned i = 0; i != 8; i += 2)
1294 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1295 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1296 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1297 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1303 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1304 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1305 /// current subtarget.
1307 /// The ShuffleKind distinguishes between big-endian operations with
1308 /// two different inputs (0), either-endian operations with two identical
1309 /// inputs (1), and little-endian operations with two different inputs (2).
1310 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1311 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1312 SelectionDAG &DAG) {
1313 const PPCSubtarget& Subtarget =
1314 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1315 if (!Subtarget.hasP8Vector())
1318 bool IsLE = DAG.getDataLayout().isLittleEndian();
1319 if (ShuffleKind == 0) {
1322 for (unsigned i = 0; i != 16; i += 4)
1323 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1324 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1325 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1326 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1328 } else if (ShuffleKind == 2) {
1331 for (unsigned i = 0; i != 16; i += 4)
1332 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1333 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1334 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1335 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1337 } else if (ShuffleKind == 1) {
1338 unsigned j = IsLE ? 0 : 4;
1339 for (unsigned i = 0; i != 8; i += 4)
1340 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1341 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1342 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1343 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1344 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1345 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1346 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1347 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1353 /// isVMerge - Common function, used to match vmrg* shuffles.
1355 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1356 unsigned LHSStart, unsigned RHSStart) {
1357 if (N->getValueType(0) != MVT::v16i8)
1359 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1360 "Unsupported merge size!");
1362 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1363 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1364 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1365 LHSStart+j+i*UnitSize) ||
1366 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1367 RHSStart+j+i*UnitSize))
1373 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1374 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1375 /// The ShuffleKind distinguishes between big-endian merges with two
1376 /// different inputs (0), either-endian merges with two identical inputs (1),
1377 /// and little-endian merges with two different inputs (2). For the latter,
1378 /// the input operands are swapped (see PPCInstrAltivec.td).
1379 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1380 unsigned ShuffleKind, SelectionDAG &DAG) {
1381 if (DAG.getDataLayout().isLittleEndian()) {
1382 if (ShuffleKind == 1) // unary
1383 return isVMerge(N, UnitSize, 0, 0);
1384 else if (ShuffleKind == 2) // swapped
1385 return isVMerge(N, UnitSize, 0, 16);
1389 if (ShuffleKind == 1) // unary
1390 return isVMerge(N, UnitSize, 8, 8);
1391 else if (ShuffleKind == 0) // normal
1392 return isVMerge(N, UnitSize, 8, 24);
1398 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1399 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1400 /// The ShuffleKind distinguishes between big-endian merges with two
1401 /// different inputs (0), either-endian merges with two identical inputs (1),
1402 /// and little-endian merges with two different inputs (2). For the latter,
1403 /// the input operands are swapped (see PPCInstrAltivec.td).
1404 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1405 unsigned ShuffleKind, SelectionDAG &DAG) {
1406 if (DAG.getDataLayout().isLittleEndian()) {
1407 if (ShuffleKind == 1) // unary
1408 return isVMerge(N, UnitSize, 8, 8);
1409 else if (ShuffleKind == 2) // swapped
1410 return isVMerge(N, UnitSize, 8, 24);
1414 if (ShuffleKind == 1) // unary
1415 return isVMerge(N, UnitSize, 0, 0);
1416 else if (ShuffleKind == 0) // normal
1417 return isVMerge(N, UnitSize, 0, 16);
1424 * \brief Common function used to match vmrgew and vmrgow shuffles
1426 * The indexOffset determines whether to look for even or odd words in
1427 * the shuffle mask. This is based on the of the endianness of the target
1430 * - Use offset of 0 to check for odd elements
1431 * - Use offset of 4 to check for even elements
1433 * - Use offset of 0 to check for even elements
1434 * - Use offset of 4 to check for odd elements
1435 * A detailed description of the vector element ordering for little endian and
1436 * big endian can be found at
1437 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1438 * Targeting your applications - what little endian and big endian IBM XL C/C++
1439 * compiler differences mean to you
1441 * The mask to the shuffle vector instruction specifies the indices of the
1442 * elements from the two input vectors to place in the result. The elements are
1443 * numbered in array-access order, starting with the first vector. These vectors
1444 * are always of type v16i8, thus each vector will contain 16 elements of size
1445 * 8. More info on the shuffle vector can be found in the
1446 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1447 * Language Reference.
1449 * The RHSStartValue indicates whether the same input vectors are used (unary)
1450 * or two different input vectors are used, based on the following:
1451 * - If the instruction uses the same vector for both inputs, the range of the
1452 * indices will be 0 to 15. In this case, the RHSStart value passed should
1454 * - If the instruction has two different vectors then the range of the
1455 * indices will be 0 to 31. In this case, the RHSStart value passed should
1456 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1457 * to 31 specify elements in the second vector).
1459 * \param[in] N The shuffle vector SD Node to analyze
1460 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1461 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1462 * vector to the shuffle_vector instruction
1463 * \return true iff this shuffle vector represents an even or odd word merge
1465 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1466 unsigned RHSStartValue) {
1467 if (N->getValueType(0) != MVT::v16i8)
1470 for (unsigned i = 0; i < 2; ++i)
1471 for (unsigned j = 0; j < 4; ++j)
1472 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1473 i*RHSStartValue+j+IndexOffset) ||
1474 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1475 i*RHSStartValue+j+IndexOffset+8))
1481 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1482 * vmrgow instructions.
1484 * \param[in] N The shuffle vector SD Node to analyze
1485 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1486 * \param[in] ShuffleKind Identify the type of merge:
1487 * - 0 = big-endian merge with two different inputs;
1488 * - 1 = either-endian merge with two identical inputs;
1489 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1490 * little-endian merges).
1491 * \param[in] DAG The current SelectionDAG
1492 * \return true iff this shuffle mask
1494 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1495 unsigned ShuffleKind, SelectionDAG &DAG) {
1496 if (DAG.getDataLayout().isLittleEndian()) {
1497 unsigned indexOffset = CheckEven ? 4 : 0;
1498 if (ShuffleKind == 1) // Unary
1499 return isVMerge(N, indexOffset, 0);
1500 else if (ShuffleKind == 2) // swapped
1501 return isVMerge(N, indexOffset, 16);
1506 unsigned indexOffset = CheckEven ? 0 : 4;
1507 if (ShuffleKind == 1) // Unary
1508 return isVMerge(N, indexOffset, 0);
1509 else if (ShuffleKind == 0) // Normal
1510 return isVMerge(N, indexOffset, 16);
1517 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1518 /// amount, otherwise return -1.
1519 /// The ShuffleKind distinguishes between big-endian operations with two
1520 /// different inputs (0), either-endian operations with two identical inputs
1521 /// (1), and little-endian operations with two different inputs (2). For the
1522 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1523 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1524 SelectionDAG &DAG) {
1525 if (N->getValueType(0) != MVT::v16i8)
1528 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1530 // Find the first non-undef value in the shuffle mask.
1532 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1535 if (i == 16) return -1; // all undef.
1537 // Otherwise, check to see if the rest of the elements are consecutively
1538 // numbered from this value.
1539 unsigned ShiftAmt = SVOp->getMaskElt(i);
1540 if (ShiftAmt < i) return -1;
1543 bool isLE = DAG.getDataLayout().isLittleEndian();
1545 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1546 // Check the rest of the elements to see if they are consecutive.
1547 for (++i; i != 16; ++i)
1548 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1550 } else if (ShuffleKind == 1) {
1551 // Check the rest of the elements to see if they are consecutive.
1552 for (++i; i != 16; ++i)
1553 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1559 ShiftAmt = 16 - ShiftAmt;
1564 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1565 /// specifies a splat of a single element that is suitable for input to
1566 /// VSPLTB/VSPLTH/VSPLTW.
1567 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1568 assert(N->getValueType(0) == MVT::v16i8 &&
1569 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1571 // The consecutive indices need to specify an element, not part of two
1572 // different elements. So abandon ship early if this isn't the case.
1573 if (N->getMaskElt(0) % EltSize != 0)
1576 // This is a splat operation if each element of the permute is the same, and
1577 // if the value doesn't reference the second vector.
1578 unsigned ElementBase = N->getMaskElt(0);
1580 // FIXME: Handle UNDEF elements too!
1581 if (ElementBase >= 16)
1584 // Check that the indices are consecutive, in the case of a multi-byte element
1585 // splatted with a v16i8 mask.
1586 for (unsigned i = 1; i != EltSize; ++i)
1587 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1590 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1591 if (N->getMaskElt(i) < 0) continue;
1592 for (unsigned j = 0; j != EltSize; ++j)
1593 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1599 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1600 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1601 // Check that the mask is shuffling words
1602 for (unsigned i = 0; i < 4; ++i) {
1603 unsigned B0 = N->getMaskElt(i*4);
1604 unsigned B1 = N->getMaskElt(i*4+1);
1605 unsigned B2 = N->getMaskElt(i*4+2);
1606 unsigned B3 = N->getMaskElt(i*4+3);
1609 if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1613 // Now we look at mask elements 0,4,8,12
1614 unsigned M0 = N->getMaskElt(0) / 4;
1615 unsigned M1 = N->getMaskElt(4) / 4;
1616 unsigned M2 = N->getMaskElt(8) / 4;
1617 unsigned M3 = N->getMaskElt(12) / 4;
1618 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1619 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1621 // Below, let H and L be arbitrary elements of the shuffle mask
1622 // where H is in the range [4,7] and L is in the range [0,3].
1623 // H, 1, 2, 3 or L, 5, 6, 7
1624 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1625 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1626 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1627 InsertAtByte = IsLE ? 12 : 0;
1631 // 0, H, 2, 3 or 4, L, 6, 7
1632 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1633 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1634 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1635 InsertAtByte = IsLE ? 8 : 4;
1639 // 0, 1, H, 3 or 4, 5, L, 7
1640 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1641 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1642 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1643 InsertAtByte = IsLE ? 4 : 8;
1647 // 0, 1, 2, H or 4, 5, 6, L
1648 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1649 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1650 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1651 InsertAtByte = IsLE ? 0 : 12;
1656 // If both vector operands for the shuffle are the same vector, the mask will
1657 // contain only elements from the first one and the second one will be undef.
1658 if (N->getOperand(1).isUndef()) {
1661 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1662 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1663 InsertAtByte = IsLE ? 12 : 0;
1666 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1667 InsertAtByte = IsLE ? 8 : 4;
1670 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1671 InsertAtByte = IsLE ? 4 : 8;
1674 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1675 InsertAtByte = IsLE ? 0 : 12;
1683 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1684 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1685 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1686 SelectionDAG &DAG) {
1687 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1688 assert(isSplatShuffleMask(SVOp, EltSize));
1689 if (DAG.getDataLayout().isLittleEndian())
1690 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1692 return SVOp->getMaskElt(0) / EltSize;
1695 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1696 /// by using a vspltis[bhw] instruction of the specified element size, return
1697 /// the constant being splatted. The ByteSize field indicates the number of
1698 /// bytes of each element [124] -> [bhw].
1699 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1700 SDValue OpVal(nullptr, 0);
1702 // If ByteSize of the splat is bigger than the element size of the
1703 // build_vector, then we have a case where we are checking for a splat where
1704 // multiple elements of the buildvector are folded together into a single
1705 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1706 unsigned EltSize = 16/N->getNumOperands();
1707 if (EltSize < ByteSize) {
1708 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1709 SDValue UniquedVals[4];
1710 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1712 // See if all of the elements in the buildvector agree across.
1713 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1714 if (N->getOperand(i).isUndef()) continue;
1715 // If the element isn't a constant, bail fully out.
1716 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1718 if (!UniquedVals[i&(Multiple-1)].getNode())
1719 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1720 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1721 return SDValue(); // no match.
1724 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1725 // either constant or undef values that are identical for each chunk. See
1726 // if these chunks can form into a larger vspltis*.
1728 // Check to see if all of the leading entries are either 0 or -1. If
1729 // neither, then this won't fit into the immediate field.
1730 bool LeadingZero = true;
1731 bool LeadingOnes = true;
1732 for (unsigned i = 0; i != Multiple-1; ++i) {
1733 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1735 LeadingZero &= isNullConstant(UniquedVals[i]);
1736 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1738 // Finally, check the least significant entry.
1740 if (!UniquedVals[Multiple-1].getNode())
1741 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1742 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1743 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1744 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1747 if (!UniquedVals[Multiple-1].getNode())
1748 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1749 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1750 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1751 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1757 // Check to see if this buildvec has a single non-undef value in its elements.
1758 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1759 if (N->getOperand(i).isUndef()) continue;
1760 if (!OpVal.getNode())
1761 OpVal = N->getOperand(i);
1762 else if (OpVal != N->getOperand(i))
1766 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1768 unsigned ValSizeInBytes = EltSize;
1770 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1771 Value = CN->getZExtValue();
1772 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1773 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1774 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1777 // If the splat value is larger than the element value, then we can never do
1778 // this splat. The only case that we could fit the replicated bits into our
1779 // immediate field for would be zero, and we prefer to use vxor for it.
1780 if (ValSizeInBytes < ByteSize) return SDValue();
1782 // If the element value is larger than the splat value, check if it consists
1783 // of a repeated bit pattern of size ByteSize.
1784 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1787 // Properly sign extend the value.
1788 int MaskVal = SignExtend32(Value, ByteSize * 8);
1790 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1791 if (MaskVal == 0) return SDValue();
1793 // Finally, if this value fits in a 5 bit sext field, return it
1794 if (SignExtend32<5>(MaskVal) == MaskVal)
1795 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1799 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1800 /// amount, otherwise return -1.
1801 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1802 EVT VT = N->getValueType(0);
1803 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1806 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1808 // Find the first non-undef value in the shuffle mask.
1810 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1813 if (i == 4) return -1; // all undef.
1815 // Otherwise, check to see if the rest of the elements are consecutively
1816 // numbered from this value.
1817 unsigned ShiftAmt = SVOp->getMaskElt(i);
1818 if (ShiftAmt < i) return -1;
1821 // Check the rest of the elements to see if they are consecutive.
1822 for (++i; i != 4; ++i)
1823 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1829 //===----------------------------------------------------------------------===//
1830 // Addressing Mode Selection
1831 //===----------------------------------------------------------------------===//
1833 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1834 /// or 64-bit immediate, and if the value can be accurately represented as a
1835 /// sign extension from a 16-bit value. If so, this returns true and the
1837 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1838 if (!isa<ConstantSDNode>(N))
1841 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1842 if (N->getValueType(0) == MVT::i32)
1843 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1845 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1847 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1848 return isIntS16Immediate(Op.getNode(), Imm);
1851 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1852 /// can be represented as an indexed [r+r] operation. Returns false if it
1853 /// can be more efficiently represented with [r+imm].
1854 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1856 SelectionDAG &DAG) const {
1858 if (N.getOpcode() == ISD::ADD) {
1859 if (isIntS16Immediate(N.getOperand(1), imm))
1860 return false; // r+i
1861 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1862 return false; // r+i
1864 Base = N.getOperand(0);
1865 Index = N.getOperand(1);
1867 } else if (N.getOpcode() == ISD::OR) {
1868 if (isIntS16Immediate(N.getOperand(1), imm))
1869 return false; // r+i can fold it if we can.
1871 // If this is an or of disjoint bitfields, we can codegen this as an add
1872 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1874 KnownBits LHSKnown, RHSKnown;
1875 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1877 if (LHSKnown.Zero.getBoolValue()) {
1878 DAG.computeKnownBits(N.getOperand(1), RHSKnown);
1879 // If all of the bits are known zero on the LHS or RHS, the add won't
1881 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
1882 Base = N.getOperand(0);
1883 Index = N.getOperand(1);
1892 // If we happen to be doing an i64 load or store into a stack slot that has
1893 // less than a 4-byte alignment, then the frame-index elimination may need to
1894 // use an indexed load or store instruction (because the offset may not be a
1895 // multiple of 4). The extra register needed to hold the offset comes from the
1896 // register scavenger, and it is possible that the scavenger will need to use
1897 // an emergency spill slot. As a result, we need to make sure that a spill slot
1898 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1900 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1901 // FIXME: This does not handle the LWA case.
1905 // NOTE: We'll exclude negative FIs here, which come from argument
1906 // lowering, because there are no known test cases triggering this problem
1907 // using packed structures (or similar). We can remove this exclusion if
1908 // we find such a test case. The reason why this is so test-case driven is
1909 // because this entire 'fixup' is only to prevent crashes (from the
1910 // register scavenger) on not-really-valid inputs. For example, if we have:
1912 // %b = bitcast i1* %a to i64*
1913 // store i64* a, i64 b
1914 // then the store should really be marked as 'align 1', but is not. If it
1915 // were marked as 'align 1' then the indexed form would have been
1916 // instruction-selected initially, and the problem this 'fixup' is preventing
1917 // won't happen regardless.
1921 MachineFunction &MF = DAG.getMachineFunction();
1922 MachineFrameInfo &MFI = MF.getFrameInfo();
1924 unsigned Align = MFI.getObjectAlignment(FrameIdx);
1928 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1929 FuncInfo->setHasNonRISpills();
1932 /// Returns true if the address N can be represented by a base register plus
1933 /// a signed 16-bit displacement [r+imm], and if it is not better
1934 /// represented as reg+reg. If Aligned is true, only accept displacements
1935 /// suitable for STD and friends, i.e. multiples of 4.
1936 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1939 bool Aligned) const {
1940 // FIXME dl should come from parent load or store, not from address
1942 // If this can be more profitably realized as r+r, fail.
1943 if (SelectAddressRegReg(N, Disp, Base, DAG))
1946 if (N.getOpcode() == ISD::ADD) {
1948 if (isIntS16Immediate(N.getOperand(1), imm) &&
1949 (!Aligned || (imm & 3) == 0)) {
1950 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1951 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1952 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1953 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1955 Base = N.getOperand(0);
1957 return true; // [r+i]
1958 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1959 // Match LOAD (ADD (X, Lo(G))).
1960 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1961 && "Cannot handle constant offsets yet!");
1962 Disp = N.getOperand(1).getOperand(0); // The global address.
1963 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1964 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1965 Disp.getOpcode() == ISD::TargetConstantPool ||
1966 Disp.getOpcode() == ISD::TargetJumpTable);
1967 Base = N.getOperand(0);
1968 return true; // [&g+r]
1970 } else if (N.getOpcode() == ISD::OR) {
1972 if (isIntS16Immediate(N.getOperand(1), imm) &&
1973 (!Aligned || (imm & 3) == 0)) {
1974 // If this is an or of disjoint bitfields, we can codegen this as an add
1975 // (for better address arithmetic) if the LHS and RHS of the OR are
1976 // provably disjoint.
1978 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1980 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1981 // If all of the bits are known zero on the LHS or RHS, the add won't
1983 if (FrameIndexSDNode *FI =
1984 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1985 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1986 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1988 Base = N.getOperand(0);
1990 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1994 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1995 // Loading from a constant address.
1997 // If this address fits entirely in a 16-bit sext immediate field, codegen
2000 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
2001 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2002 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2003 CN->getValueType(0));
2007 // Handle 32-bit sext immediates with LIS + addr mode.
2008 if ((CN->getValueType(0) == MVT::i32 ||
2009 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2010 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
2011 int Addr = (int)CN->getZExtValue();
2013 // Otherwise, break this down into an LIS + disp.
2014 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2016 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2018 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2019 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2024 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2025 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2026 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2027 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2030 return true; // [r+0]
2033 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2034 /// represented as an indexed [r+r] operation.
2035 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2037 SelectionDAG &DAG) const {
2038 // Check to see if we can easily represent this as an [r+r] address. This
2039 // will fail if it thinks that the address is more profitably represented as
2040 // reg+imm, e.g. where imm = 0.
2041 if (SelectAddressRegReg(N, Base, Index, DAG))
2044 // If the operand is an addition, always emit this as [r+r], since this is
2045 // better (for code size, and execution, as the memop does the add for free)
2046 // than emitting an explicit add.
2047 if (N.getOpcode() == ISD::ADD) {
2048 Base = N.getOperand(0);
2049 Index = N.getOperand(1);
2053 // Otherwise, do it the hard way, using R0 as the base register.
2054 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2060 /// getPreIndexedAddressParts - returns true by value, base pointer and
2061 /// offset pointer and addressing mode by reference if the node's address
2062 /// can be legally represented as pre-indexed load / store address.
2063 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2065 ISD::MemIndexedMode &AM,
2066 SelectionDAG &DAG) const {
2067 if (DisablePPCPreinc) return false;
2073 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2074 Ptr = LD->getBasePtr();
2075 VT = LD->getMemoryVT();
2076 Alignment = LD->getAlignment();
2077 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2078 Ptr = ST->getBasePtr();
2079 VT = ST->getMemoryVT();
2080 Alignment = ST->getAlignment();
2085 // PowerPC doesn't have preinc load/store instructions for vectors (except
2086 // for QPX, which does have preinc r+r forms).
2087 if (VT.isVector()) {
2088 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2090 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2096 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2097 // Common code will reject creating a pre-inc form if the base pointer
2098 // is a frame index, or if N is a store and the base pointer is either
2099 // the same as or a predecessor of the value being stored. Check for
2100 // those situations here, and try with swapped Base/Offset instead.
2103 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2106 SDValue Val = cast<StoreSDNode>(N)->getValue();
2107 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2112 std::swap(Base, Offset);
2118 // LDU/STU can only handle immediates that are a multiple of 4.
2119 if (VT != MVT::i64) {
2120 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2123 // LDU/STU need an address with at least 4-byte alignment.
2127 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2131 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2132 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2133 // sext i32 to i64 when addr mode is r+i.
2134 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2135 LD->getExtensionType() == ISD::SEXTLOAD &&
2136 isa<ConstantSDNode>(Offset))
2144 //===----------------------------------------------------------------------===//
2145 // LowerOperation implementation
2146 //===----------------------------------------------------------------------===//
2148 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2149 /// and LoOpFlags to the target MO flags.
2150 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2151 unsigned &HiOpFlags, unsigned &LoOpFlags,
2152 const GlobalValue *GV = nullptr) {
2153 HiOpFlags = PPCII::MO_HA;
2154 LoOpFlags = PPCII::MO_LO;
2156 // Don't use the pic base if not in PIC relocation model.
2158 HiOpFlags |= PPCII::MO_PIC_FLAG;
2159 LoOpFlags |= PPCII::MO_PIC_FLAG;
2162 // If this is a reference to a global value that requires a non-lazy-ptr, make
2163 // sure that instruction lowering adds it.
2164 if (GV && Subtarget.hasLazyResolverStub(GV)) {
2165 HiOpFlags |= PPCII::MO_NLP_FLAG;
2166 LoOpFlags |= PPCII::MO_NLP_FLAG;
2168 if (GV->hasHiddenVisibility()) {
2169 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2170 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2175 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2176 SelectionDAG &DAG) {
2178 EVT PtrVT = HiPart.getValueType();
2179 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2181 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2182 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2184 // With PIC, the first instruction is actually "GR+hi(&G)".
2186 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2187 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2189 // Generate non-pic code that has direct accesses to the constant pool.
2190 // The address of the global is just (hi(&g)+lo(&g)).
2191 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2194 static void setUsesTOCBasePtr(MachineFunction &MF) {
2195 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2196 FuncInfo->setUsesTOCBasePtr();
2199 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2200 setUsesTOCBasePtr(DAG.getMachineFunction());
2203 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2205 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2206 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2207 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2209 SDValue Ops[] = { GA, Reg };
2210 return DAG.getMemIntrinsicNode(
2211 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2212 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2216 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2217 SelectionDAG &DAG) const {
2218 EVT PtrVT = Op.getValueType();
2219 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2220 const Constant *C = CP->getConstVal();
2222 // 64-bit SVR4 ABI code is always position-independent.
2223 // The actual address of the GlobalValue is stored in the TOC.
2224 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2225 setUsesTOCBasePtr(DAG);
2226 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2227 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2230 unsigned MOHiFlag, MOLoFlag;
2231 bool IsPIC = isPositionIndependent();
2232 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2234 if (IsPIC && Subtarget.isSVR4ABI()) {
2235 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2236 PPCII::MO_PIC_FLAG);
2237 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2241 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2243 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2244 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2247 // For 64-bit PowerPC, prefer the more compact relative encodings.
2248 // This trades 32 bits per jump table entry for one or two instructions
2249 // on the jump site.
2250 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2251 if (isJumpTableRelative())
2252 return MachineJumpTableInfo::EK_LabelDifference32;
2254 return TargetLowering::getJumpTableEncoding();
2257 bool PPCTargetLowering::isJumpTableRelative() const {
2258 if (Subtarget.isPPC64())
2260 return TargetLowering::isJumpTableRelative();
2263 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2264 SelectionDAG &DAG) const {
2265 if (!Subtarget.isPPC64())
2266 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2268 switch (getTargetMachine().getCodeModel()) {
2269 case CodeModel::Default:
2270 case CodeModel::Small:
2271 case CodeModel::Medium:
2272 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2274 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2275 getPointerTy(DAG.getDataLayout()));
2280 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2282 MCContext &Ctx) const {
2283 if (!Subtarget.isPPC64())
2284 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2286 switch (getTargetMachine().getCodeModel()) {
2287 case CodeModel::Default:
2288 case CodeModel::Small:
2289 case CodeModel::Medium:
2290 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2292 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2296 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2297 EVT PtrVT = Op.getValueType();
2298 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2300 // 64-bit SVR4 ABI code is always position-independent.
2301 // The actual address of the GlobalValue is stored in the TOC.
2302 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2303 setUsesTOCBasePtr(DAG);
2304 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2305 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2308 unsigned MOHiFlag, MOLoFlag;
2309 bool IsPIC = isPositionIndependent();
2310 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2312 if (IsPIC && Subtarget.isSVR4ABI()) {
2313 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2314 PPCII::MO_PIC_FLAG);
2315 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2318 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2319 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2320 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2323 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2324 SelectionDAG &DAG) const {
2325 EVT PtrVT = Op.getValueType();
2326 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2327 const BlockAddress *BA = BASDN->getBlockAddress();
2329 // 64-bit SVR4 ABI code is always position-independent.
2330 // The actual BlockAddress is stored in the TOC.
2331 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2332 setUsesTOCBasePtr(DAG);
2333 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2334 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2337 unsigned MOHiFlag, MOLoFlag;
2338 bool IsPIC = isPositionIndependent();
2339 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2340 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2341 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2342 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2345 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2346 SelectionDAG &DAG) const {
2347 // FIXME: TLS addresses currently use medium model code sequences,
2348 // which is the most useful form. Eventually support for small and
2349 // large models could be added if users need it, at the cost of
2350 // additional complexity.
2351 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2352 if (DAG.getTarget().Options.EmulatedTLS)
2353 return LowerToTLSEmulatedModel(GA, DAG);
2356 const GlobalValue *GV = GA->getGlobal();
2357 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2358 bool is64bit = Subtarget.isPPC64();
2359 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2360 PICLevel::Level picLevel = M->getPICLevel();
2362 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2364 if (Model == TLSModel::LocalExec) {
2365 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2366 PPCII::MO_TPREL_HA);
2367 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2368 PPCII::MO_TPREL_LO);
2369 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2370 is64bit ? MVT::i64 : MVT::i32);
2371 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2372 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2375 if (Model == TLSModel::InitialExec) {
2376 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2377 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2381 setUsesTOCBasePtr(DAG);
2382 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2383 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2384 PtrVT, GOTReg, TGA);
2386 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2387 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2388 PtrVT, TGA, GOTPtr);
2389 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2392 if (Model == TLSModel::GeneralDynamic) {
2393 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2396 setUsesTOCBasePtr(DAG);
2397 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2398 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2401 if (picLevel == PICLevel::SmallPIC)
2402 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2404 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2406 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2410 if (Model == TLSModel::LocalDynamic) {
2411 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2414 setUsesTOCBasePtr(DAG);
2415 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2416 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2419 if (picLevel == PICLevel::SmallPIC)
2420 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2422 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2424 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2425 PtrVT, GOTPtr, TGA, TGA);
2426 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2427 PtrVT, TLSAddr, TGA);
2428 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2431 llvm_unreachable("Unknown TLS model!");
2434 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2435 SelectionDAG &DAG) const {
2436 EVT PtrVT = Op.getValueType();
2437 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2439 const GlobalValue *GV = GSDN->getGlobal();
2441 // 64-bit SVR4 ABI code is always position-independent.
2442 // The actual address of the GlobalValue is stored in the TOC.
2443 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2444 setUsesTOCBasePtr(DAG);
2445 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2446 return getTOCEntry(DAG, DL, true, GA);
2449 unsigned MOHiFlag, MOLoFlag;
2450 bool IsPIC = isPositionIndependent();
2451 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2453 if (IsPIC && Subtarget.isSVR4ABI()) {
2454 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2456 PPCII::MO_PIC_FLAG);
2457 return getTOCEntry(DAG, DL, false, GA);
2461 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2463 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2465 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2467 // If the global reference is actually to a non-lazy-pointer, we have to do an
2468 // extra load to get the address of the global.
2469 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2470 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2474 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2475 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2478 if (Op.getValueType() == MVT::v2i64) {
2479 // When the operands themselves are v2i64 values, we need to do something
2480 // special because VSX has no underlying comparison operations for these.
2481 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2482 // Equality can be handled by casting to the legal type for Altivec
2483 // comparisons, everything else needs to be expanded.
2484 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2485 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2486 DAG.getSetCC(dl, MVT::v4i32,
2487 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2488 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2495 // We handle most of these in the usual way.
2499 // If we're comparing for equality to zero, expose the fact that this is
2500 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2501 // fold the new nodes.
2502 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2505 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2506 // Leave comparisons against 0 and -1 alone for now, since they're usually
2507 // optimized. FIXME: revisit this when we can custom lower all setcc
2509 if (C->isAllOnesValue() || C->isNullValue())
2513 // If we have an integer seteq/setne, turn it into a compare against zero
2514 // by xor'ing the rhs with the lhs, which is faster than setting a
2515 // condition register, reading it back out, and masking the correct bit. The
2516 // normal approach here uses sub to do this instead of xor. Using xor exposes
2517 // the result to other bit-twiddling opportunities.
2518 EVT LHSVT = Op.getOperand(0).getValueType();
2519 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2520 EVT VT = Op.getValueType();
2521 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2523 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2528 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2529 SDNode *Node = Op.getNode();
2530 EVT VT = Node->getValueType(0);
2531 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2532 SDValue InChain = Node->getOperand(0);
2533 SDValue VAListPtr = Node->getOperand(1);
2534 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2537 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2540 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2541 VAListPtr, MachinePointerInfo(SV), MVT::i8);
2542 InChain = GprIndex.getValue(1);
2544 if (VT == MVT::i64) {
2545 // Check if GprIndex is even
2546 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2547 DAG.getConstant(1, dl, MVT::i32));
2548 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2549 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2550 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2551 DAG.getConstant(1, dl, MVT::i32));
2552 // Align GprIndex to be even if it isn't
2553 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2557 // fpr index is 1 byte after gpr
2558 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2559 DAG.getConstant(1, dl, MVT::i32));
2562 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2563 FprPtr, MachinePointerInfo(SV), MVT::i8);
2564 InChain = FprIndex.getValue(1);
2566 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2567 DAG.getConstant(8, dl, MVT::i32));
2569 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2570 DAG.getConstant(4, dl, MVT::i32));
2573 SDValue OverflowArea =
2574 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2575 InChain = OverflowArea.getValue(1);
2577 SDValue RegSaveArea =
2578 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2579 InChain = RegSaveArea.getValue(1);
2581 // select overflow_area if index > 8
2582 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2583 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2585 // adjustment constant gpr_index * 4/8
2586 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2587 VT.isInteger() ? GprIndex : FprIndex,
2588 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2591 // OurReg = RegSaveArea + RegConstant
2592 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2595 // Floating types are 32 bytes into RegSaveArea
2596 if (VT.isFloatingPoint())
2597 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2598 DAG.getConstant(32, dl, MVT::i32));
2600 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2601 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2602 VT.isInteger() ? GprIndex : FprIndex,
2603 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2606 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2607 VT.isInteger() ? VAListPtr : FprPtr,
2608 MachinePointerInfo(SV), MVT::i8);
2610 // determine if we should load from reg_save_area or overflow_area
2611 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2613 // increase overflow_area by 4/8 if gpr/fpr > 8
2614 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2615 DAG.getConstant(VT.isInteger() ? 4 : 8,
2618 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2621 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2622 MachinePointerInfo(), MVT::i32);
2624 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2627 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2628 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2630 // We have to copy the entire va_list struct:
2631 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2632 return DAG.getMemcpy(Op.getOperand(0), Op,
2633 Op.getOperand(1), Op.getOperand(2),
2634 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2635 false, MachinePointerInfo(), MachinePointerInfo());
2638 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2639 SelectionDAG &DAG) const {
2640 return Op.getOperand(0);
2643 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2644 SelectionDAG &DAG) const {
2645 SDValue Chain = Op.getOperand(0);
2646 SDValue Trmp = Op.getOperand(1); // trampoline
2647 SDValue FPtr = Op.getOperand(2); // nested function
2648 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2651 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2652 bool isPPC64 = (PtrVT == MVT::i64);
2653 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2655 TargetLowering::ArgListTy Args;
2656 TargetLowering::ArgListEntry Entry;
2658 Entry.Ty = IntPtrTy;
2659 Entry.Node = Trmp; Args.push_back(Entry);
2661 // TrampSize == (isPPC64 ? 48 : 40);
2662 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2663 isPPC64 ? MVT::i64 : MVT::i32);
2664 Args.push_back(Entry);
2666 Entry.Node = FPtr; Args.push_back(Entry);
2667 Entry.Node = Nest; Args.push_back(Entry);
2669 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2670 TargetLowering::CallLoweringInfo CLI(DAG);
2671 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2672 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2673 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2675 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2676 return CallResult.second;
2679 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2680 MachineFunction &MF = DAG.getMachineFunction();
2681 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2682 EVT PtrVT = getPointerTy(MF.getDataLayout());
2686 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2687 // vastart just stores the address of the VarArgsFrameIndex slot into the
2688 // memory location argument.
2689 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2690 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2691 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2692 MachinePointerInfo(SV));
2695 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2696 // We suppose the given va_list is already allocated.
2699 // char gpr; /* index into the array of 8 GPRs
2700 // * stored in the register save area
2701 // * gpr=0 corresponds to r3,
2702 // * gpr=1 to r4, etc.
2704 // char fpr; /* index into the array of 8 FPRs
2705 // * stored in the register save area
2706 // * fpr=0 corresponds to f1,
2707 // * fpr=1 to f2, etc.
2709 // char *overflow_arg_area;
2710 // /* location on stack that holds
2711 // * the next overflow argument
2713 // char *reg_save_area;
2714 // /* where r3:r10 and f1:f8 (if saved)
2719 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2720 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2721 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2723 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2726 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2727 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2729 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2730 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2732 uint64_t FPROffset = 1;
2733 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2735 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2737 // Store first byte : number of int regs
2738 SDValue firstStore =
2739 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2740 MachinePointerInfo(SV), MVT::i8);
2741 uint64_t nextOffset = FPROffset;
2742 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2745 // Store second byte : number of float regs
2746 SDValue secondStore =
2747 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2748 MachinePointerInfo(SV, nextOffset), MVT::i8);
2749 nextOffset += StackOffset;
2750 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2752 // Store second word : arguments given on stack
2753 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2754 MachinePointerInfo(SV, nextOffset));
2755 nextOffset += FrameOffset;
2756 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2758 // Store third word : arguments given in registers
2759 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2760 MachinePointerInfo(SV, nextOffset));
2763 #include "PPCGenCallingConv.inc"
2765 // Function whose sole purpose is to kill compiler warnings
2766 // stemming from unused functions included from PPCGenCallingConv.inc.
2767 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2768 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2771 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2772 CCValAssign::LocInfo &LocInfo,
2773 ISD::ArgFlagsTy &ArgFlags,
2778 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2780 CCValAssign::LocInfo &LocInfo,
2781 ISD::ArgFlagsTy &ArgFlags,
2783 static const MCPhysReg ArgRegs[] = {
2784 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2785 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2787 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2789 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2791 // Skip one register if the first unallocated register has an even register
2792 // number and there are still argument registers available which have not been
2793 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2794 // need to skip a register if RegNum is odd.
2795 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2796 State.AllocateReg(ArgRegs[RegNum]);
2799 // Always return false here, as this function only makes sure that the first
2800 // unallocated register has an odd register number and does not actually
2801 // allocate a register for the current argument.
2806 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2808 CCValAssign::LocInfo &LocInfo,
2809 ISD::ArgFlagsTy &ArgFlags,
2811 static const MCPhysReg ArgRegs[] = {
2812 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2813 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2815 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2817 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2818 int RegsLeft = NumArgRegs - RegNum;
2820 // Skip if there is not enough registers left for long double type (4 gpr regs
2821 // in soft float mode) and put long double argument on the stack.
2822 if (RegNum != NumArgRegs && RegsLeft < 4) {
2823 for (int i = 0; i < RegsLeft; i++) {
2824 State.AllocateReg(ArgRegs[RegNum + i]);
2831 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2833 CCValAssign::LocInfo &LocInfo,
2834 ISD::ArgFlagsTy &ArgFlags,
2836 static const MCPhysReg ArgRegs[] = {
2837 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2841 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2843 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2845 // If there is only one Floating-point register left we need to put both f64
2846 // values of a split ppc_fp128 value on the stack.
2847 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2848 State.AllocateReg(ArgRegs[RegNum]);
2851 // Always return false here, as this function only makes sure that the two f64
2852 // values a ppc_fp128 value is split into are both passed in registers or both
2853 // passed on the stack and does not actually allocate a register for the
2854 // current argument.
2858 /// FPR - The set of FP registers that should be allocated for arguments,
2860 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2861 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2862 PPC::F11, PPC::F12, PPC::F13};
2864 /// QFPR - The set of QPX registers that should be allocated for arguments.
2865 static const MCPhysReg QFPR[] = {
2866 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2867 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2869 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2871 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2872 unsigned PtrByteSize) {
2873 unsigned ArgSize = ArgVT.getStoreSize();
2874 if (Flags.isByVal())
2875 ArgSize = Flags.getByValSize();
2877 // Round up to multiples of the pointer size, except for array members,
2878 // which are always packed.
2879 if (!Flags.isInConsecutiveRegs())
2880 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2885 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2887 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2888 ISD::ArgFlagsTy Flags,
2889 unsigned PtrByteSize) {
2890 unsigned Align = PtrByteSize;
2892 // Altivec parameters are padded to a 16 byte boundary.
2893 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2894 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2895 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2896 ArgVT == MVT::v1i128)
2898 // QPX vector types stored in double-precision are padded to a 32 byte
2900 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2903 // ByVal parameters are aligned as requested.
2904 if (Flags.isByVal()) {
2905 unsigned BVAlign = Flags.getByValAlign();
2906 if (BVAlign > PtrByteSize) {
2907 if (BVAlign % PtrByteSize != 0)
2909 "ByVal alignment is not a multiple of the pointer size");
2915 // Array members are always packed to their original alignment.
2916 if (Flags.isInConsecutiveRegs()) {
2917 // If the array member was split into multiple registers, the first
2918 // needs to be aligned to the size of the full type. (Except for
2919 // ppcf128, which is only aligned as its f64 components.)
2920 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2921 Align = OrigVT.getStoreSize();
2923 Align = ArgVT.getStoreSize();
2929 /// CalculateStackSlotUsed - Return whether this argument will use its
2930 /// stack slot (instead of being passed in registers). ArgOffset,
2931 /// AvailableFPRs, and AvailableVRs must hold the current argument
2932 /// position, and will be updated to account for this argument.
2933 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2934 ISD::ArgFlagsTy Flags,
2935 unsigned PtrByteSize,
2936 unsigned LinkageSize,
2937 unsigned ParamAreaSize,
2938 unsigned &ArgOffset,
2939 unsigned &AvailableFPRs,
2940 unsigned &AvailableVRs, bool HasQPX) {
2941 bool UseMemory = false;
2943 // Respect alignment of argument on the stack.
2945 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2946 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2947 // If there's no space left in the argument save area, we must
2948 // use memory (this check also catches zero-sized arguments).
2949 if (ArgOffset >= LinkageSize + ParamAreaSize)
2952 // Allocate argument on the stack.
2953 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2954 if (Flags.isInConsecutiveRegsLast())
2955 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2956 // If we overran the argument save area, we must use memory
2957 // (this check catches arguments passed partially in memory)
2958 if (ArgOffset > LinkageSize + ParamAreaSize)
2961 // However, if the argument is actually passed in an FPR or a VR,
2962 // we don't use memory after all.
2963 if (!Flags.isByVal()) {
2964 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2965 // QPX registers overlap with the scalar FP registers.
2966 (HasQPX && (ArgVT == MVT::v4f32 ||
2967 ArgVT == MVT::v4f64 ||
2968 ArgVT == MVT::v4i1)))
2969 if (AvailableFPRs > 0) {
2973 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2974 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2975 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2976 ArgVT == MVT::v1i128)
2977 if (AvailableVRs > 0) {
2986 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2987 /// ensure minimum alignment required for target.
2988 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2989 unsigned NumBytes) {
2990 unsigned TargetAlign = Lowering->getStackAlignment();
2991 unsigned AlignMask = TargetAlign - 1;
2992 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2996 SDValue PPCTargetLowering::LowerFormalArguments(
2997 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2998 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2999 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3000 if (Subtarget.isSVR4ABI()) {
3001 if (Subtarget.isPPC64())
3002 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3005 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3008 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3013 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3014 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3015 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3016 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3018 // 32-bit SVR4 ABI Stack Frame Layout:
3019 // +-----------------------------------+
3020 // +--> | Back chain |
3021 // | +-----------------------------------+
3022 // | | Floating-point register save area |
3023 // | +-----------------------------------+
3024 // | | General register save area |
3025 // | +-----------------------------------+
3026 // | | CR save word |
3027 // | +-----------------------------------+
3028 // | | VRSAVE save word |
3029 // | +-----------------------------------+
3030 // | | Alignment padding |
3031 // | +-----------------------------------+
3032 // | | Vector register save area |
3033 // | +-----------------------------------+
3034 // | | Local variable space |
3035 // | +-----------------------------------+
3036 // | | Parameter list area |
3037 // | +-----------------------------------+
3038 // | | LR save word |
3039 // | +-----------------------------------+
3040 // SP--> +--- | Back chain |
3041 // +-----------------------------------+
3044 // System V Application Binary Interface PowerPC Processor Supplement
3045 // AltiVec Technology Programming Interface Manual
3047 MachineFunction &MF = DAG.getMachineFunction();
3048 MachineFrameInfo &MFI = MF.getFrameInfo();
3049 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3051 EVT PtrVT = getPointerTy(MF.getDataLayout());
3052 // Potential tail calls could cause overwriting of argument stack slots.
3053 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3054 (CallConv == CallingConv::Fast));
3055 unsigned PtrByteSize = 4;
3057 // Assign locations to all of the incoming arguments.
3058 SmallVector<CCValAssign, 16> ArgLocs;
3059 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3062 // Reserve space for the linkage area on the stack.
3063 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3064 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3066 CCInfo.PreAnalyzeFormalArguments(Ins);
3068 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3069 CCInfo.clearWasPPCF128();
3071 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3072 CCValAssign &VA = ArgLocs[i];
3074 // Arguments stored in registers.
3075 if (VA.isRegLoc()) {
3076 const TargetRegisterClass *RC;
3077 EVT ValVT = VA.getValVT();
3079 switch (ValVT.getSimpleVT().SimpleTy) {
3081 llvm_unreachable("ValVT not supported by formal arguments Lowering");
3084 RC = &PPC::GPRCRegClass;
3087 if (Subtarget.hasP8Vector())
3088 RC = &PPC::VSSRCRegClass;
3090 RC = &PPC::F4RCRegClass;
3093 if (Subtarget.hasVSX())
3094 RC = &PPC::VSFRCRegClass;
3096 RC = &PPC::F8RCRegClass;
3101 RC = &PPC::VRRCRegClass;
3104 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3108 RC = &PPC::VRRCRegClass;
3111 RC = &PPC::QFRCRegClass;
3114 RC = &PPC::QBRCRegClass;
3118 // Transform the arguments stored in physical registers into virtual ones.
3119 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3120 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3121 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3123 if (ValVT == MVT::i1)
3124 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3126 InVals.push_back(ArgValue);
3128 // Argument stored in memory.
3129 assert(VA.isMemLoc());
3131 unsigned ArgSize = VA.getLocVT().getStoreSize();
3132 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3135 // Create load nodes to retrieve arguments from the stack.
3136 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3138 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3142 // Assign locations to all of the incoming aggregate by value arguments.
3143 // Aggregates passed by value are stored in the local variable space of the
3144 // caller's stack frame, right above the parameter list area.
3145 SmallVector<CCValAssign, 16> ByValArgLocs;
3146 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3147 ByValArgLocs, *DAG.getContext());
3149 // Reserve stack space for the allocations in CCInfo.
3150 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3152 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3154 // Area that is at least reserved in the caller of this function.
3155 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3156 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3158 // Set the size that is at least reserved in caller of this function. Tail
3159 // call optimized function's reserved stack space needs to be aligned so that
3160 // taking the difference between two stack areas will result in an aligned
3163 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3164 FuncInfo->setMinReservedArea(MinReservedArea);
3166 SmallVector<SDValue, 8> MemOps;
3168 // If the function takes variable number of arguments, make a frame index for
3169 // the start of the first vararg value... for expansion of llvm.va_start.
3171 static const MCPhysReg GPArgRegs[] = {
3172 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3173 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3175 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3177 static const MCPhysReg FPArgRegs[] = {
3178 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3181 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3186 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3187 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3189 // Make room for NumGPArgRegs and NumFPArgRegs.
3190 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3191 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3193 FuncInfo->setVarArgsStackOffset(
3194 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3195 CCInfo.getNextStackOffset(), true));
3197 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3198 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3200 // The fixed integer arguments of a variadic function are stored to the
3201 // VarArgsFrameIndex on the stack so that they may be loaded by
3202 // dereferencing the result of va_next.
3203 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3204 // Get an existing live-in vreg, or add a new one.
3205 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3207 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3209 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3211 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3212 MemOps.push_back(Store);
3213 // Increment the address by four for the next argument to store
3214 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3215 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3218 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3220 // The double arguments are stored to the VarArgsFrameIndex
3222 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3223 // Get an existing live-in vreg, or add a new one.
3224 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3226 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3228 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3230 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3231 MemOps.push_back(Store);
3232 // Increment the address by eight for the next argument to store
3233 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3235 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3239 if (!MemOps.empty())
3240 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3245 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3246 // value to MVT::i64 and then truncate to the correct register size.
3247 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3248 EVT ObjectVT, SelectionDAG &DAG,
3250 const SDLoc &dl) const {
3252 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3253 DAG.getValueType(ObjectVT));
3254 else if (Flags.isZExt())
3255 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3256 DAG.getValueType(ObjectVT));
3258 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3261 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3262 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3263 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3264 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3265 // TODO: add description of PPC stack frame format, or at least some docs.
3267 bool isELFv2ABI = Subtarget.isELFv2ABI();
3268 bool isLittleEndian = Subtarget.isLittleEndian();
3269 MachineFunction &MF = DAG.getMachineFunction();
3270 MachineFrameInfo &MFI = MF.getFrameInfo();
3271 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3273 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3274 "fastcc not supported on varargs functions");
3276 EVT PtrVT = getPointerTy(MF.getDataLayout());
3277 // Potential tail calls could cause overwriting of argument stack slots.
3278 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3279 (CallConv == CallingConv::Fast));
3280 unsigned PtrByteSize = 8;
3281 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3283 static const MCPhysReg GPR[] = {
3284 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3285 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3287 static const MCPhysReg VR[] = {
3288 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3289 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3292 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3293 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3294 const unsigned Num_VR_Regs = array_lengthof(VR);
3295 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3297 // Do a first pass over the arguments to determine whether the ABI
3298 // guarantees that our caller has allocated the parameter save area
3299 // on its stack frame. In the ELFv1 ABI, this is always the case;
3300 // in the ELFv2 ABI, it is true if this is a vararg function or if
3301 // any parameter is located in a stack slot.
3303 bool HasParameterArea = !isELFv2ABI || isVarArg;
3304 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3305 unsigned NumBytes = LinkageSize;
3306 unsigned AvailableFPRs = Num_FPR_Regs;
3307 unsigned AvailableVRs = Num_VR_Regs;
3308 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3309 if (Ins[i].Flags.isNest())
3312 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3313 PtrByteSize, LinkageSize, ParamAreaSize,
3314 NumBytes, AvailableFPRs, AvailableVRs,
3315 Subtarget.hasQPX()))
3316 HasParameterArea = true;
3319 // Add DAG nodes to load the arguments or copy them out of registers. On
3320 // entry to a function on PPC, the arguments start after the linkage area,
3321 // although the first ones are often in registers.
3323 unsigned ArgOffset = LinkageSize;
3324 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3325 unsigned &QFPR_idx = FPR_idx;
3326 SmallVector<SDValue, 8> MemOps;
3327 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3328 unsigned CurArgIdx = 0;
3329 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3331 bool needsLoad = false;
3332 EVT ObjectVT = Ins[ArgNo].VT;
3333 EVT OrigVT = Ins[ArgNo].ArgVT;
3334 unsigned ObjSize = ObjectVT.getStoreSize();
3335 unsigned ArgSize = ObjSize;
3336 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3337 if (Ins[ArgNo].isOrigArg()) {
3338 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3339 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3341 // We re-align the argument offset for each argument, except when using the
3342 // fast calling convention, when we need to make sure we do that only when
3343 // we'll actually use a stack slot.
3344 unsigned CurArgOffset, Align;
3345 auto ComputeArgOffset = [&]() {
3346 /* Respect alignment of argument on the stack. */
3347 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3348 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3349 CurArgOffset = ArgOffset;
3352 if (CallConv != CallingConv::Fast) {
3355 /* Compute GPR index associated with argument offset. */
3356 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3357 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3360 // FIXME the codegen can be much improved in some cases.
3361 // We do not have to keep everything in memory.
3362 if (Flags.isByVal()) {
3363 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3365 if (CallConv == CallingConv::Fast)
3368 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3369 ObjSize = Flags.getByValSize();
3370 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3371 // Empty aggregate parameters do not take up registers. Examples:
3375 // etc. However, we have to provide a place-holder in InVals, so
3376 // pretend we have an 8-byte item at the current address for that
3379 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3380 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3381 InVals.push_back(FIN);
3385 // Create a stack object covering all stack doublewords occupied
3386 // by the argument. If the argument is (fully or partially) on
3387 // the stack, or if the argument is fully in registers but the
3388 // caller has allocated the parameter save anyway, we can refer
3389 // directly to the caller's stack frame. Otherwise, create a
3390 // local copy in our own frame.
3392 if (HasParameterArea ||
3393 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3394 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3396 FI = MFI.CreateStackObject(ArgSize, Align, false);
3397 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3399 // Handle aggregates smaller than 8 bytes.
3400 if (ObjSize < PtrByteSize) {
3401 // The value of the object is its address, which differs from the
3402 // address of the enclosing doubleword on big-endian systems.
3404 if (!isLittleEndian) {
3405 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3406 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3408 InVals.push_back(Arg);
3410 if (GPR_idx != Num_GPR_Regs) {
3411 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3412 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3415 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3416 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3417 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3418 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3419 MachinePointerInfo(&*FuncArg), ObjType);
3421 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3422 // store the whole register as-is to the parameter save area
3424 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3425 MachinePointerInfo(&*FuncArg));
3428 MemOps.push_back(Store);
3430 // Whether we copied from a register or not, advance the offset
3431 // into the parameter save area by a full doubleword.
3432 ArgOffset += PtrByteSize;
3436 // The value of the object is its address, which is the address of
3437 // its first stack doubleword.
3438 InVals.push_back(FIN);
3440 // Store whatever pieces of the object are in registers to memory.
3441 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3442 if (GPR_idx == Num_GPR_Regs)
3445 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3446 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3449 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3450 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3452 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3453 MachinePointerInfo(&*FuncArg, j));
3454 MemOps.push_back(Store);
3457 ArgOffset += ArgSize;
3461 switch (ObjectVT.getSimpleVT().SimpleTy) {
3462 default: llvm_unreachable("Unhandled argument type!");
3466 if (Flags.isNest()) {
3467 // The 'nest' parameter, if any, is passed in R11.
3468 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3469 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3471 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3472 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3477 // These can be scalar arguments or elements of an integer array type
3478 // passed directly. Clang may use those instead of "byval" aggregate
3479 // types to avoid forcing arguments to memory unnecessarily.
3480 if (GPR_idx != Num_GPR_Regs) {
3481 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3482 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3484 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3485 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3486 // value to MVT::i64 and then truncate to the correct register size.
3487 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3489 if (CallConv == CallingConv::Fast)
3493 ArgSize = PtrByteSize;
3495 if (CallConv != CallingConv::Fast || needsLoad)
3501 // These can be scalar arguments or elements of a float array type
3502 // passed directly. The latter are used to implement ELFv2 homogenous
3503 // float aggregates.
3504 if (FPR_idx != Num_FPR_Regs) {
3507 if (ObjectVT == MVT::f32)
3508 VReg = MF.addLiveIn(FPR[FPR_idx],
3509 Subtarget.hasP8Vector()
3510 ? &PPC::VSSRCRegClass
3511 : &PPC::F4RCRegClass);
3513 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3514 ? &PPC::VSFRCRegClass
3515 : &PPC::F8RCRegClass);
3517 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3519 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3520 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3521 // once we support fp <-> gpr moves.
3523 // This can only ever happen in the presence of f32 array types,
3524 // since otherwise we never run out of FPRs before running out
3526 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3527 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3529 if (ObjectVT == MVT::f32) {
3530 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3531 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3532 DAG.getConstant(32, dl, MVT::i32));
3533 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3536 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3538 if (CallConv == CallingConv::Fast)
3544 // When passing an array of floats, the array occupies consecutive
3545 // space in the argument area; only round up to the next doubleword
3546 // at the end of the array. Otherwise, each float takes 8 bytes.
3547 if (CallConv != CallingConv::Fast || needsLoad) {
3548 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3549 ArgOffset += ArgSize;
3550 if (Flags.isInConsecutiveRegsLast())
3551 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3561 if (!Subtarget.hasQPX()) {
3562 // These can be scalar arguments or elements of a vector array type
3563 // passed directly. The latter are used to implement ELFv2 homogenous
3564 // vector aggregates.
3565 if (VR_idx != Num_VR_Regs) {
3566 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3567 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3570 if (CallConv == CallingConv::Fast)
3575 if (CallConv != CallingConv::Fast || needsLoad)
3580 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3581 "Invalid QPX parameter type");
3586 // QPX vectors are treated like their scalar floating-point subregisters
3587 // (except that they're larger).
3588 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3589 if (QFPR_idx != Num_QFPR_Regs) {
3590 const TargetRegisterClass *RC;
3591 switch (ObjectVT.getSimpleVT().SimpleTy) {
3592 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3593 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3594 default: RC = &PPC::QBRCRegClass; break;
3597 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3598 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3601 if (CallConv == CallingConv::Fast)
3605 if (CallConv != CallingConv::Fast || needsLoad)
3610 // We need to load the argument to a virtual register if we determined
3611 // above that we ran out of physical registers of the appropriate type.
3613 if (ObjSize < ArgSize && !isLittleEndian)
3614 CurArgOffset += ArgSize - ObjSize;
3615 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3616 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3617 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3620 InVals.push_back(ArgVal);
3623 // Area that is at least reserved in the caller of this function.
3624 unsigned MinReservedArea;
3625 if (HasParameterArea)
3626 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3628 MinReservedArea = LinkageSize;
3630 // Set the size that is at least reserved in caller of this function. Tail
3631 // call optimized functions' reserved stack space needs to be aligned so that
3632 // taking the difference between two stack areas will result in an aligned
3635 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3636 FuncInfo->setMinReservedArea(MinReservedArea);
3638 // If the function takes variable number of arguments, make a frame index for
3639 // the start of the first vararg value... for expansion of llvm.va_start.
3641 int Depth = ArgOffset;
3643 FuncInfo->setVarArgsFrameIndex(
3644 MFI.CreateFixedObject(PtrByteSize, Depth, true));
3645 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3647 // If this function is vararg, store any remaining integer argument regs
3648 // to their spots on the stack so that they may be loaded by dereferencing
3649 // the result of va_next.
3650 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3651 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3652 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3653 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3655 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3656 MemOps.push_back(Store);
3657 // Increment the address by four for the next argument to store
3658 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3659 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3663 if (!MemOps.empty())
3664 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3669 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3670 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3671 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3672 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3673 // TODO: add description of PPC stack frame format, or at least some docs.
3675 MachineFunction &MF = DAG.getMachineFunction();
3676 MachineFrameInfo &MFI = MF.getFrameInfo();
3677 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3679 EVT PtrVT = getPointerTy(MF.getDataLayout());
3680 bool isPPC64 = PtrVT == MVT::i64;
3681 // Potential tail calls could cause overwriting of argument stack slots.
3682 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3683 (CallConv == CallingConv::Fast));
3684 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3685 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3686 unsigned ArgOffset = LinkageSize;
3687 // Area that is at least reserved in caller of this function.
3688 unsigned MinReservedArea = ArgOffset;
3690 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3691 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3692 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3694 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3695 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3696 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3698 static const MCPhysReg VR[] = {
3699 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3700 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3703 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3704 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3705 const unsigned Num_VR_Regs = array_lengthof( VR);
3707 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3709 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3711 // In 32-bit non-varargs functions, the stack space for vectors is after the
3712 // stack space for non-vectors. We do not use this space unless we have
3713 // too many vectors to fit in registers, something that only occurs in
3714 // constructed examples:), but we have to walk the arglist to figure
3715 // that out...for the pathological case, compute VecArgOffset as the
3716 // start of the vector parameter area. Computing VecArgOffset is the
3717 // entire point of the following loop.
3718 unsigned VecArgOffset = ArgOffset;
3719 if (!isVarArg && !isPPC64) {
3720 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3722 EVT ObjectVT = Ins[ArgNo].VT;
3723 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3725 if (Flags.isByVal()) {
3726 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3727 unsigned ObjSize = Flags.getByValSize();
3729 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3730 VecArgOffset += ArgSize;
3734 switch(ObjectVT.getSimpleVT().SimpleTy) {
3735 default: llvm_unreachable("Unhandled argument type!");
3741 case MVT::i64: // PPC64
3743 // FIXME: We are guaranteed to be !isPPC64 at this point.
3744 // Does MVT::i64 apply?
3751 // Nothing to do, we're only looking at Nonvector args here.
3756 // We've found where the vector parameter area in memory is. Skip the
3757 // first 12 parameters; these don't use that memory.
3758 VecArgOffset = ((VecArgOffset+15)/16)*16;
3759 VecArgOffset += 12*16;
3761 // Add DAG nodes to load the arguments or copy them out of registers. On
3762 // entry to a function on PPC, the arguments start after the linkage area,
3763 // although the first ones are often in registers.
3765 SmallVector<SDValue, 8> MemOps;
3766 unsigned nAltivecParamsAtEnd = 0;
3767 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3768 unsigned CurArgIdx = 0;
3769 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3771 bool needsLoad = false;
3772 EVT ObjectVT = Ins[ArgNo].VT;
3773 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3774 unsigned ArgSize = ObjSize;
3775 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3776 if (Ins[ArgNo].isOrigArg()) {
3777 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3778 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3780 unsigned CurArgOffset = ArgOffset;
3782 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3783 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3784 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3785 if (isVarArg || isPPC64) {
3786 MinReservedArea = ((MinReservedArea+15)/16)*16;
3787 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3790 } else nAltivecParamsAtEnd++;
3792 // Calculate min reserved area.
3793 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3797 // FIXME the codegen can be much improved in some cases.
3798 // We do not have to keep everything in memory.
3799 if (Flags.isByVal()) {
3800 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3802 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3803 ObjSize = Flags.getByValSize();
3804 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3805 // Objects of size 1 and 2 are right justified, everything else is
3806 // left justified. This means the memory address is adjusted forwards.
3807 if (ObjSize==1 || ObjSize==2) {
3808 CurArgOffset = CurArgOffset + (4 - ObjSize);
3810 // The value of the object is its address.
3811 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3812 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3813 InVals.push_back(FIN);
3814 if (ObjSize==1 || ObjSize==2) {
3815 if (GPR_idx != Num_GPR_Regs) {
3818 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3820 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3821 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3822 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3824 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3825 MachinePointerInfo(&*FuncArg), ObjType);
3826 MemOps.push_back(Store);
3830 ArgOffset += PtrByteSize;
3834 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3835 // Store whatever pieces of the object are in registers
3836 // to memory. ArgOffset will be the address of the beginning
3838 if (GPR_idx != Num_GPR_Regs) {
3841 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3843 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3844 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3845 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3846 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3847 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3848 MachinePointerInfo(&*FuncArg, j));
3849 MemOps.push_back(Store);
3851 ArgOffset += PtrByteSize;
3853 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3860 switch (ObjectVT.getSimpleVT().SimpleTy) {
3861 default: llvm_unreachable("Unhandled argument type!");
3865 if (GPR_idx != Num_GPR_Regs) {
3866 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3867 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3869 if (ObjectVT == MVT::i1)
3870 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3875 ArgSize = PtrByteSize;
3877 // All int arguments reserve stack space in the Darwin ABI.
3878 ArgOffset += PtrByteSize;
3882 case MVT::i64: // PPC64
3883 if (GPR_idx != Num_GPR_Regs) {
3884 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3885 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3887 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3888 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3889 // value to MVT::i64 and then truncate to the correct register size.
3890 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3895 ArgSize = PtrByteSize;
3897 // All int arguments reserve stack space in the Darwin ABI.
3903 // Every 4 bytes of argument space consumes one of the GPRs available for
3904 // argument passing.
3905 if (GPR_idx != Num_GPR_Regs) {
3907 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3910 if (FPR_idx != Num_FPR_Regs) {
3913 if (ObjectVT == MVT::f32)
3914 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3916 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3918 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3924 // All FP arguments reserve stack space in the Darwin ABI.
3925 ArgOffset += isPPC64 ? 8 : ObjSize;
3931 // Note that vector arguments in registers don't reserve stack space,
3932 // except in varargs functions.
3933 if (VR_idx != Num_VR_Regs) {
3934 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3935 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3937 while ((ArgOffset % 16) != 0) {
3938 ArgOffset += PtrByteSize;
3939 if (GPR_idx != Num_GPR_Regs)
3943 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3947 if (!isVarArg && !isPPC64) {
3948 // Vectors go after all the nonvectors.
3949 CurArgOffset = VecArgOffset;
3952 // Vectors are aligned.
3953 ArgOffset = ((ArgOffset+15)/16)*16;
3954 CurArgOffset = ArgOffset;
3962 // We need to load the argument to a virtual register if we determined above
3963 // that we ran out of physical registers of the appropriate type.
3965 int FI = MFI.CreateFixedObject(ObjSize,
3966 CurArgOffset + (ArgSize - ObjSize),
3968 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3969 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3972 InVals.push_back(ArgVal);
3975 // Allow for Altivec parameters at the end, if needed.
3976 if (nAltivecParamsAtEnd) {
3977 MinReservedArea = ((MinReservedArea+15)/16)*16;
3978 MinReservedArea += 16*nAltivecParamsAtEnd;
3981 // Area that is at least reserved in the caller of this function.
3982 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3984 // Set the size that is at least reserved in caller of this function. Tail
3985 // call optimized functions' reserved stack space needs to be aligned so that
3986 // taking the difference between two stack areas will result in an aligned
3989 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3990 FuncInfo->setMinReservedArea(MinReservedArea);
3992 // If the function takes variable number of arguments, make a frame index for
3993 // the start of the first vararg value... for expansion of llvm.va_start.
3995 int Depth = ArgOffset;
3997 FuncInfo->setVarArgsFrameIndex(
3998 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4000 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4002 // If this function is vararg, store any remaining integer argument regs
4003 // to their spots on the stack so that they may be loaded by dereferencing
4004 // the result of va_next.
4005 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4009 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4011 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4013 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4015 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4016 MemOps.push_back(Store);
4017 // Increment the address by four for the next argument to store
4018 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4019 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4023 if (!MemOps.empty())
4024 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4029 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4030 /// adjusted to accommodate the arguments for the tailcall.
4031 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4032 unsigned ParamSize) {
4034 if (!isTailCall) return 0;
4036 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4037 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4038 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4039 // Remember only if the new adjustement is bigger.
4040 if (SPDiff < FI->getTailCallSPDelta())
4041 FI->setTailCallSPDelta(SPDiff);
4046 static bool isFunctionGlobalAddress(SDValue Callee);
4049 resideInSameSection(const Function *Caller, SDValue Callee,
4050 const TargetMachine &TM) {
4051 // If !G, Callee can be an external symbol.
4052 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4056 const GlobalValue *GV = G->getGlobal();
4057 if (!GV->isStrongDefinitionForLinker())
4060 // Any explicitly-specified sections and section prefixes must also match.
4061 // Also, if we're using -ffunction-sections, then each function is always in
4062 // a different section (the same is true for COMDAT functions).
4063 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4064 GV->getSection() != Caller->getSection())
4066 if (const auto *F = dyn_cast<Function>(GV)) {
4067 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4071 // If the callee might be interposed, then we can't assume the ultimate call
4072 // target will be in the same section. Even in cases where we can assume that
4073 // interposition won't happen, in any case where the linker might insert a
4074 // stub to allow for interposition, we must generate code as though
4075 // interposition might occur. To understand why this matters, consider a
4076 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4077 // in the same section, but a is in a different module (i.e. has a different
4078 // TOC base pointer). If the linker allows for interposition between b and c,
4079 // then it will generate a stub for the call edge between b and c which will
4080 // save the TOC pointer into the designated stack slot allocated by b. If we
4081 // return true here, and therefore allow a tail call between b and c, that
4082 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4083 // pointer into the stack slot allocated by a (where the a -> b stub saved
4084 // a's TOC base pointer). If we're not considering a tail call, but rather,
4085 // whether a nop is needed after the call instruction in b, because the linker
4086 // will insert a stub, it might complain about a missing nop if we omit it
4087 // (although many don't complain in this case).
4088 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4095 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4096 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4097 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4099 const unsigned PtrByteSize = 8;
4100 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4102 static const MCPhysReg GPR[] = {
4103 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4104 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4106 static const MCPhysReg VR[] = {
4107 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4108 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4111 const unsigned NumGPRs = array_lengthof(GPR);
4112 const unsigned NumFPRs = 13;
4113 const unsigned NumVRs = array_lengthof(VR);
4114 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4116 unsigned NumBytes = LinkageSize;
4117 unsigned AvailableFPRs = NumFPRs;
4118 unsigned AvailableVRs = NumVRs;
4120 for (const ISD::OutputArg& Param : Outs) {
4121 if (Param.Flags.isNest()) continue;
4123 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4124 PtrByteSize, LinkageSize, ParamAreaSize,
4125 NumBytes, AvailableFPRs, AvailableVRs,
4126 Subtarget.hasQPX()))
4133 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4134 if (CS->arg_size() != CallerFn->arg_size())
4137 ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4138 ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4139 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4141 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4142 const Value* CalleeArg = *CalleeArgIter;
4143 const Value* CallerArg = &(*CallerArgIter);
4144 if (CalleeArg == CallerArg)
4147 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4148 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4150 // 1st argument of callee is undef and has the same type as caller.
4151 if (CalleeArg->getType() == CallerArg->getType() &&
4152 isa<UndefValue>(CalleeArg))
4162 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4164 CallingConv::ID CalleeCC,
4165 ImmutableCallSite *CS,
4167 const SmallVectorImpl<ISD::OutputArg> &Outs,
4168 const SmallVectorImpl<ISD::InputArg> &Ins,
4169 SelectionDAG& DAG) const {
4170 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4172 if (DisableSCO && !TailCallOpt) return false;
4174 // Variadic argument functions are not supported.
4175 if (isVarArg) return false;
4177 MachineFunction &MF = DAG.getMachineFunction();
4178 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4180 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4181 // the same calling convention
4182 if (CallerCC != CalleeCC) return false;
4184 // SCO support C calling convention
4185 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4188 // Caller contains any byval parameter is not supported.
4189 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4192 // Callee contains any byval parameter is not supported, too.
4193 // Note: This is a quick work around, because in some cases, e.g.
4194 // caller's stack size > callee's stack size, we are still able to apply
4195 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4196 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4199 // No TCO/SCO on indirect call because Caller have to restore its TOC
4200 if (!isFunctionGlobalAddress(Callee) &&
4201 !isa<ExternalSymbolSDNode>(Callee))
4204 // Check if Callee resides in the same section, because for now, PPC64 SVR4
4205 // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4207 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4208 if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4211 // TCO allows altering callee ABI, so we don't have to check further.
4212 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4215 if (DisableSCO) return false;
4217 // If callee use the same argument list that caller is using, then we can
4218 // apply SCO on this case. If it is not, then we need to check if callee needs
4219 // stack for passing arguments.
4220 if (!hasSameArgumentList(MF.getFunction(), CS) &&
4221 needStackSlotPassParameters(Subtarget, Outs)) {
4228 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4229 /// for tail call optimization. Targets which want to do tail call
4230 /// optimization should implement this function.
4232 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4233 CallingConv::ID CalleeCC,
4235 const SmallVectorImpl<ISD::InputArg> &Ins,
4236 SelectionDAG& DAG) const {
4237 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4240 // Variable argument functions are not supported.
4244 MachineFunction &MF = DAG.getMachineFunction();
4245 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4246 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4247 // Functions containing by val parameters are not supported.
4248 for (unsigned i = 0; i != Ins.size(); i++) {
4249 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4250 if (Flags.isByVal()) return false;
4253 // Non-PIC/GOT tail calls are supported.
4254 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4257 // At the moment we can only do local tail calls (in same module, hidden
4258 // or protected) if we are generating PIC.
4259 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4260 return G->getGlobal()->hasHiddenVisibility()
4261 || G->getGlobal()->hasProtectedVisibility();
4267 /// isCallCompatibleAddress - Return the immediate to use if the specified
4268 /// 32-bit value is representable in the immediate field of a BxA instruction.
4269 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4270 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4271 if (!C) return nullptr;
4273 int Addr = C->getZExtValue();
4274 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4275 SignExtend32<26>(Addr) != Addr)
4276 return nullptr; // Top 6 bits have to be sext of immediate.
4280 (int)C->getZExtValue() >> 2, SDLoc(Op),
4281 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4287 struct TailCallArgumentInfo {
4292 TailCallArgumentInfo() = default;
4295 } // end anonymous namespace
4297 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4298 static void StoreTailCallArgumentsToStackSlot(
4299 SelectionDAG &DAG, SDValue Chain,
4300 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4301 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4302 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4303 SDValue Arg = TailCallArgs[i].Arg;
4304 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4305 int FI = TailCallArgs[i].FrameIdx;
4306 // Store relative to framepointer.
4307 MemOpChains.push_back(DAG.getStore(
4308 Chain, dl, Arg, FIN,
4309 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4313 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4314 /// the appropriate stack slot for the tail call optimized function call.
4315 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4316 SDValue OldRetAddr, SDValue OldFP,
4317 int SPDiff, const SDLoc &dl) {
4319 // Calculate the new stack slot for the return address.
4320 MachineFunction &MF = DAG.getMachineFunction();
4321 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4322 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4323 bool isPPC64 = Subtarget.isPPC64();
4324 int SlotSize = isPPC64 ? 8 : 4;
4325 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4326 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4327 NewRetAddrLoc, true);
4328 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4329 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4330 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4331 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4333 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4334 // slot as the FP is never overwritten.
4335 if (Subtarget.isDarwinABI()) {
4336 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4337 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4339 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4340 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4341 MachinePointerInfo::getFixedStack(
4342 DAG.getMachineFunction(), NewFPIdx));
4348 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4349 /// the position of the argument.
4351 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4352 SDValue Arg, int SPDiff, unsigned ArgOffset,
4353 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4354 int Offset = ArgOffset + SPDiff;
4355 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4356 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4357 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4358 SDValue FIN = DAG.getFrameIndex(FI, VT);
4359 TailCallArgumentInfo Info;
4361 Info.FrameIdxOp = FIN;
4363 TailCallArguments.push_back(Info);
4366 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4367 /// stack slot. Returns the chain as result and the loaded frame pointers in
4368 /// LROpOut/FPOpout. Used when tail calling.
4369 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4370 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4371 SDValue &FPOpOut, const SDLoc &dl) const {
4373 // Load the LR and FP stack slot for later adjusting.
4374 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4375 LROpOut = getReturnAddrFrameIndex(DAG);
4376 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4377 Chain = SDValue(LROpOut.getNode(), 1);
4379 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4380 // slot as the FP is never overwritten.
4381 if (Subtarget.isDarwinABI()) {
4382 FPOpOut = getFramePointerFrameIndex(DAG);
4383 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4384 Chain = SDValue(FPOpOut.getNode(), 1);
4390 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4391 /// by "Src" to address "Dst" of size "Size". Alignment information is
4392 /// specified by the specific parameter attribute. The copy will be passed as
4393 /// a byval function parameter.
4394 /// Sometimes what we are copying is the end of a larger object, the part that
4395 /// does not fit in registers.
4396 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4397 SDValue Chain, ISD::ArgFlagsTy Flags,
4398 SelectionDAG &DAG, const SDLoc &dl) {
4399 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4400 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4401 false, false, false, MachinePointerInfo(),
4402 MachinePointerInfo());
4405 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4407 static void LowerMemOpCallTo(
4408 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4409 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4410 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4411 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4412 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4417 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4419 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4420 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4421 DAG.getConstant(ArgOffset, dl, PtrVT));
4423 MemOpChains.push_back(
4424 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4425 // Calculate and remember argument location.
4426 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4431 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4432 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4434 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4435 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4436 // might overwrite each other in case of tail call optimization.
4437 SmallVector<SDValue, 8> MemOpChains2;
4438 // Do not flag preceding copytoreg stuff together with the following stuff.
4440 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4442 if (!MemOpChains2.empty())
4443 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4445 // Store the return address to the appropriate stack slot.
4446 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4448 // Emit callseq_end just before tailcall node.
4449 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4450 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4451 InFlag = Chain.getValue(1);
4454 // Is this global address that of a function that can be called by name? (as
4455 // opposed to something that must hold a descriptor for an indirect call).
4456 static bool isFunctionGlobalAddress(SDValue Callee) {
4457 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4458 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4459 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4462 return G->getGlobal()->getValueType()->isFunctionTy();
4469 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4470 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4471 bool isPatchPoint, bool hasNest,
4472 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4473 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4474 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4475 bool isPPC64 = Subtarget.isPPC64();
4476 bool isSVR4ABI = Subtarget.isSVR4ABI();
4477 bool isELFv2ABI = Subtarget.isELFv2ABI();
4479 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4480 NodeTys.push_back(MVT::Other); // Returns a chain
4481 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4483 unsigned CallOpc = PPCISD::CALL;
4485 bool needIndirectCall = true;
4486 if (!isSVR4ABI || !isPPC64)
4487 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4488 // If this is an absolute destination address, use the munged value.
4489 Callee = SDValue(Dest, 0);
4490 needIndirectCall = false;
4493 // PC-relative references to external symbols should go through $stub, unless
4494 // we're building with the leopard linker or later, which automatically
4495 // synthesizes these stubs.
4496 const TargetMachine &TM = DAG.getTarget();
4497 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4498 const GlobalValue *GV = nullptr;
4499 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4500 GV = G->getGlobal();
4501 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4502 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4504 if (isFunctionGlobalAddress(Callee)) {
4505 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4506 // A call to a TLS address is actually an indirect call to a
4507 // thread-specific pointer.
4508 unsigned OpFlags = 0;
4510 OpFlags = PPCII::MO_PLT;
4512 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4513 // every direct call is) turn it into a TargetGlobalAddress /
4514 // TargetExternalSymbol node so that legalize doesn't hack it.
4515 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4516 Callee.getValueType(), 0, OpFlags);
4517 needIndirectCall = false;
4520 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4521 unsigned char OpFlags = 0;
4524 OpFlags = PPCII::MO_PLT;
4526 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4528 needIndirectCall = false;
4532 // We'll form an invalid direct call when lowering a patchpoint; the full
4533 // sequence for an indirect call is complicated, and many of the
4534 // instructions introduced might have side effects (and, thus, can't be
4535 // removed later). The call itself will be removed as soon as the
4536 // argument/return lowering is complete, so the fact that it has the wrong
4537 // kind of operands should not really matter.
4538 needIndirectCall = false;
4541 if (needIndirectCall) {
4542 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4543 // to do the call, we can't use PPCISD::CALL.
4544 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4546 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4547 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4548 // entry point, but to the function descriptor (the function entry point
4549 // address is part of the function descriptor though).
4550 // The function descriptor is a three doubleword structure with the
4551 // following fields: function entry point, TOC base address and
4552 // environment pointer.
4553 // Thus for a call through a function pointer, the following actions need
4555 // 1. Save the TOC of the caller in the TOC save area of its stack
4556 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4557 // 2. Load the address of the function entry point from the function
4559 // 3. Load the TOC of the callee from the function descriptor into r2.
4560 // 4. Load the environment pointer from the function descriptor into
4562 // 5. Branch to the function entry point address.
4563 // 6. On return of the callee, the TOC of the caller needs to be
4564 // restored (this is done in FinishCall()).
4566 // The loads are scheduled at the beginning of the call sequence, and the
4567 // register copies are flagged together to ensure that no other
4568 // operations can be scheduled in between. E.g. without flagging the
4569 // copies together, a TOC access in the caller could be scheduled between
4570 // the assignment of the callee TOC and the branch to the callee, which
4571 // results in the TOC access going through the TOC of the callee instead
4572 // of going through the TOC of the caller, which leads to incorrect code.
4574 // Load the address of the function entry point from the function
4576 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4577 if (LDChain.getValueType() == MVT::Glue)
4578 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4580 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4581 ? (MachineMemOperand::MODereferenceable |
4582 MachineMemOperand::MOInvariant)
4583 : MachineMemOperand::MONone;
4585 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4586 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4587 /* Alignment = */ 8, MMOFlags);
4589 // Load environment pointer into r11.
4590 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4591 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4592 SDValue LoadEnvPtr =
4593 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4594 /* Alignment = */ 8, MMOFlags);
4596 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4597 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4599 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4600 /* Alignment = */ 8, MMOFlags);
4602 setUsesTOCBasePtr(DAG);
4603 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4605 Chain = TOCVal.getValue(0);
4606 InFlag = TOCVal.getValue(1);
4608 // If the function call has an explicit 'nest' parameter, it takes the
4609 // place of the environment pointer.
4611 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4614 Chain = EnvVal.getValue(0);
4615 InFlag = EnvVal.getValue(1);
4618 MTCTROps[0] = Chain;
4619 MTCTROps[1] = LoadFuncPtr;
4620 MTCTROps[2] = InFlag;
4623 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4624 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4625 InFlag = Chain.getValue(1);
4628 NodeTys.push_back(MVT::Other);
4629 NodeTys.push_back(MVT::Glue);
4630 Ops.push_back(Chain);
4631 CallOpc = PPCISD::BCTRL;
4632 Callee.setNode(nullptr);
4633 // Add use of X11 (holding environment pointer)
4634 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4635 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4636 // Add CTR register as callee so a bctr can be emitted later.
4638 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4641 // If this is a direct call, pass the chain and the callee.
4642 if (Callee.getNode()) {
4643 Ops.push_back(Chain);
4644 Ops.push_back(Callee);
4646 // If this is a tail call add stack pointer delta.
4648 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4650 // Add argument registers to the end of the list so that they are known live
4652 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4653 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4654 RegsToPass[i].second.getValueType()));
4656 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4658 if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4659 setUsesTOCBasePtr(DAG);
4660 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4666 SDValue PPCTargetLowering::LowerCallResult(
4667 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4668 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4669 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4670 SmallVector<CCValAssign, 16> RVLocs;
4671 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4673 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4675 // Copy all of the result registers out of their specified physreg.
4676 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4677 CCValAssign &VA = RVLocs[i];
4678 assert(VA.isRegLoc() && "Can only return in registers!");
4680 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4681 VA.getLocReg(), VA.getLocVT(), InFlag);
4682 Chain = Val.getValue(1);
4683 InFlag = Val.getValue(2);
4685 switch (VA.getLocInfo()) {
4686 default: llvm_unreachable("Unknown loc info!");
4687 case CCValAssign::Full: break;
4688 case CCValAssign::AExt:
4689 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4691 case CCValAssign::ZExt:
4692 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4693 DAG.getValueType(VA.getValVT()));
4694 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4696 case CCValAssign::SExt:
4697 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4698 DAG.getValueType(VA.getValVT()));
4699 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4703 InVals.push_back(Val);
4709 SDValue PPCTargetLowering::FinishCall(
4710 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4711 bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4712 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4713 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4714 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4715 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4716 std::vector<EVT> NodeTys;
4717 SmallVector<SDValue, 8> Ops;
4718 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4719 SPDiff, isTailCall, isPatchPoint, hasNest,
4720 RegsToPass, Ops, NodeTys, CS, Subtarget);
4722 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4723 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4724 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4726 // When performing tail call optimization the callee pops its arguments off
4727 // the stack. Account for this here so these bytes can be pushed back on in
4728 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4729 int BytesCalleePops =
4730 (CallConv == CallingConv::Fast &&
4731 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4733 // Add a register mask operand representing the call-preserved registers.
4734 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4735 const uint32_t *Mask =
4736 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4737 assert(Mask && "Missing call preserved mask for calling convention");
4738 Ops.push_back(DAG.getRegisterMask(Mask));
4740 if (InFlag.getNode())
4741 Ops.push_back(InFlag);
4745 assert(((Callee.getOpcode() == ISD::Register &&
4746 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4747 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4748 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4749 isa<ConstantSDNode>(Callee)) &&
4750 "Expecting an global address, external symbol, absolute value or register");
4752 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4753 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4756 // Add a NOP immediately after the branch instruction when using the 64-bit
4757 // SVR4 ABI. At link time, if caller and callee are in a different module and
4758 // thus have a different TOC, the call will be replaced with a call to a stub
4759 // function which saves the current TOC, loads the TOC of the callee and
4760 // branches to the callee. The NOP will be replaced with a load instruction
4761 // which restores the TOC of the caller from the TOC save slot of the current
4762 // stack frame. If caller and callee belong to the same module (and have the
4763 // same TOC), the NOP will remain unchanged.
4765 MachineFunction &MF = DAG.getMachineFunction();
4766 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4768 if (CallOpc == PPCISD::BCTRL) {
4769 // This is a call through a function pointer.
4770 // Restore the caller TOC from the save area into R2.
4771 // See PrepareCall() for more information about calls through function
4772 // pointers in the 64-bit SVR4 ABI.
4773 // We are using a target-specific load with r2 hard coded, because the
4774 // result of a target-independent load would never go directly into r2,
4775 // since r2 is a reserved register (which prevents the register allocator
4776 // from allocating it), resulting in an additional register being
4777 // allocated and an unnecessary move instruction being generated.
4778 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4780 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4781 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4782 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4783 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4784 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4786 // The address needs to go after the chain input but before the flag (or
4787 // any other variadic arguments).
4788 Ops.insert(std::next(Ops.begin()), AddTOC);
4789 } else if (CallOpc == PPCISD::CALL &&
4790 !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4791 // Otherwise insert NOP for non-local calls.
4792 CallOpc = PPCISD::CALL_NOP;
4796 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4797 InFlag = Chain.getValue(1);
4799 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4800 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4803 InFlag = Chain.getValue(1);
4805 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4806 Ins, dl, DAG, InVals);
4810 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4811 SmallVectorImpl<SDValue> &InVals) const {
4812 SelectionDAG &DAG = CLI.DAG;
4814 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4815 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4816 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4817 SDValue Chain = CLI.Chain;
4818 SDValue Callee = CLI.Callee;
4819 bool &isTailCall = CLI.IsTailCall;
4820 CallingConv::ID CallConv = CLI.CallConv;
4821 bool isVarArg = CLI.IsVarArg;
4822 bool isPatchPoint = CLI.IsPatchPoint;
4823 ImmutableCallSite *CS = CLI.CS;
4826 if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4828 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4830 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4831 isVarArg, Outs, Ins, DAG);
4833 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4837 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4840 assert(isa<GlobalAddressSDNode>(Callee) &&
4841 "Callee should be an llvm::Function object.");
4843 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4844 const unsigned Width = 80 - strlen("TCO caller: ")
4845 - strlen(", callee linkage: 0, 0");
4846 dbgs() << "TCO caller: "
4847 << left_justify(DAG.getMachineFunction().getName(), Width)
4848 << ", callee linkage: "
4849 << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4854 if (!isTailCall && CS && CS->isMustTailCall())
4855 report_fatal_error("failed to perform tail call elimination on a call "
4856 "site marked musttail");
4858 // When long calls (i.e. indirect calls) are always used, calls are always
4859 // made via function pointer. If we have a function name, first translate it
4861 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4863 Callee = LowerGlobalAddress(Callee, DAG);
4865 if (Subtarget.isSVR4ABI()) {
4866 if (Subtarget.isPPC64())
4867 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4868 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4869 dl, DAG, InVals, CS);
4871 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4872 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4873 dl, DAG, InVals, CS);
4876 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4877 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4878 dl, DAG, InVals, CS);
4881 SDValue PPCTargetLowering::LowerCall_32SVR4(
4882 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4883 bool isTailCall, bool isPatchPoint,
4884 const SmallVectorImpl<ISD::OutputArg> &Outs,
4885 const SmallVectorImpl<SDValue> &OutVals,
4886 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4887 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4888 ImmutableCallSite *CS) const {
4889 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4890 // of the 32-bit SVR4 ABI stack frame layout.
4892 assert((CallConv == CallingConv::C ||
4893 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4895 unsigned PtrByteSize = 4;
4897 MachineFunction &MF = DAG.getMachineFunction();
4899 // Mark this function as potentially containing a function that contains a
4900 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4901 // and restoring the callers stack pointer in this functions epilog. This is
4902 // done because by tail calling the called function might overwrite the value
4903 // in this function's (MF) stack pointer stack slot 0(SP).
4904 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4905 CallConv == CallingConv::Fast)
4906 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4908 // Count how many bytes are to be pushed on the stack, including the linkage
4909 // area, parameter list area and the part of the local variable space which
4910 // contains copies of aggregates which are passed by value.
4912 // Assign locations to all of the outgoing arguments.
4913 SmallVector<CCValAssign, 16> ArgLocs;
4914 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4916 // Reserve space for the linkage area on the stack.
4917 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4920 CCInfo.PreAnalyzeCallOperands(Outs);
4923 // Handle fixed and variable vector arguments differently.
4924 // Fixed vector arguments go into registers as long as registers are
4925 // available. Variable vector arguments always go into memory.
4926 unsigned NumArgs = Outs.size();
4928 for (unsigned i = 0; i != NumArgs; ++i) {
4929 MVT ArgVT = Outs[i].VT;
4930 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4933 if (Outs[i].IsFixed) {
4934 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4937 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4943 errs() << "Call operand #" << i << " has unhandled type "
4944 << EVT(ArgVT).getEVTString() << "\n";
4946 llvm_unreachable(nullptr);
4950 // All arguments are treated the same.
4951 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4953 CCInfo.clearWasPPCF128();
4955 // Assign locations to all of the outgoing aggregate by value arguments.
4956 SmallVector<CCValAssign, 16> ByValArgLocs;
4957 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4959 // Reserve stack space for the allocations in CCInfo.
4960 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4962 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4964 // Size of the linkage area, parameter list area and the part of the local
4965 // space variable where copies of aggregates which are passed by value are
4967 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4969 // Calculate by how many bytes the stack has to be adjusted in case of tail
4970 // call optimization.
4971 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4973 // Adjust the stack pointer for the new arguments...
4974 // These operations are automatically eliminated by the prolog/epilog pass
4975 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
4976 SDValue CallSeqStart = Chain;
4978 // Load the return address and frame pointer so it can be moved somewhere else
4981 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4983 // Set up a copy of the stack pointer for use loading and storing any
4984 // arguments that may not fit in the registers available for argument
4986 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4988 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4989 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4990 SmallVector<SDValue, 8> MemOpChains;
4992 bool seenFloatArg = false;
4993 // Walk the register/memloc assignments, inserting copies/loads.
4994 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4997 CCValAssign &VA = ArgLocs[i];
4998 SDValue Arg = OutVals[i];
4999 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5001 if (Flags.isByVal()) {
5002 // Argument is an aggregate which is passed by value, thus we need to
5003 // create a copy of it in the local variable space of the current stack
5004 // frame (which is the stack frame of the caller) and pass the address of
5005 // this copy to the callee.
5006 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5007 CCValAssign &ByValVA = ByValArgLocs[j++];
5008 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5010 // Memory reserved in the local variable space of the callers stack frame.
5011 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5013 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5014 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5017 // Create a copy of the argument in the local area of the current
5019 SDValue MemcpyCall =
5020 CreateCopyOfByValArgument(Arg, PtrOff,
5021 CallSeqStart.getNode()->getOperand(0),
5024 // This must go outside the CALLSEQ_START..END.
5025 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5027 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5028 NewCallSeqStart.getNode());
5029 Chain = CallSeqStart = NewCallSeqStart;
5031 // Pass the address of the aggregate copy on the stack either in a
5032 // physical register or in the parameter list area of the current stack
5033 // frame to the callee.
5037 if (VA.isRegLoc()) {
5038 if (Arg.getValueType() == MVT::i1)
5039 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5041 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5042 // Put argument in a physical register.
5043 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5045 // Put argument in the parameter list area of the current stack frame.
5046 assert(VA.isMemLoc());
5047 unsigned LocMemOffset = VA.getLocMemOffset();
5050 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5051 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5054 MemOpChains.push_back(
5055 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5057 // Calculate and remember argument location.
5058 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5064 if (!MemOpChains.empty())
5065 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5067 // Build a sequence of copy-to-reg nodes chained together with token chain
5068 // and flag operands which copy the outgoing args into the appropriate regs.
5070 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5071 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5072 RegsToPass[i].second, InFlag);
5073 InFlag = Chain.getValue(1);
5076 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5079 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5080 SDValue Ops[] = { Chain, InFlag };
5082 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5083 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5085 InFlag = Chain.getValue(1);
5089 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5092 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5093 /* unused except on PPC64 ELFv1 */ false, DAG,
5094 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5095 NumBytes, Ins, InVals, CS);
5098 // Copy an argument into memory, being careful to do this outside the
5099 // call sequence for the call to which the argument belongs.
5100 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5101 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5102 SelectionDAG &DAG, const SDLoc &dl) const {
5103 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5104 CallSeqStart.getNode()->getOperand(0),
5106 // The MEMCPY must go outside the CALLSEQ_START..END.
5107 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5108 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5110 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5111 NewCallSeqStart.getNode());
5112 return NewCallSeqStart;
5115 SDValue PPCTargetLowering::LowerCall_64SVR4(
5116 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5117 bool isTailCall, bool isPatchPoint,
5118 const SmallVectorImpl<ISD::OutputArg> &Outs,
5119 const SmallVectorImpl<SDValue> &OutVals,
5120 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5121 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5122 ImmutableCallSite *CS) const {
5123 bool isELFv2ABI = Subtarget.isELFv2ABI();
5124 bool isLittleEndian = Subtarget.isLittleEndian();
5125 unsigned NumOps = Outs.size();
5126 bool hasNest = false;
5127 bool IsSibCall = false;
5129 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5130 unsigned PtrByteSize = 8;
5132 MachineFunction &MF = DAG.getMachineFunction();
5134 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5137 // Mark this function as potentially containing a function that contains a
5138 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5139 // and restoring the callers stack pointer in this functions epilog. This is
5140 // done because by tail calling the called function might overwrite the value
5141 // in this function's (MF) stack pointer stack slot 0(SP).
5142 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5143 CallConv == CallingConv::Fast)
5144 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5146 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5147 "fastcc not supported on varargs functions");
5149 // Count how many bytes are to be pushed on the stack, including the linkage
5150 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5151 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5152 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5153 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5154 unsigned NumBytes = LinkageSize;
5155 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5156 unsigned &QFPR_idx = FPR_idx;
5158 static const MCPhysReg GPR[] = {
5159 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5160 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5162 static const MCPhysReg VR[] = {
5163 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5164 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5167 const unsigned NumGPRs = array_lengthof(GPR);
5168 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5169 const unsigned NumVRs = array_lengthof(VR);
5170 const unsigned NumQFPRs = NumFPRs;
5172 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5173 // can be passed to the callee in registers.
5174 // For the fast calling convention, there is another check below.
5175 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5176 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5177 if (!HasParameterArea) {
5178 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5179 unsigned AvailableFPRs = NumFPRs;
5180 unsigned AvailableVRs = NumVRs;
5181 unsigned NumBytesTmp = NumBytes;
5182 for (unsigned i = 0; i != NumOps; ++i) {
5183 if (Outs[i].Flags.isNest()) continue;
5184 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5185 PtrByteSize, LinkageSize, ParamAreaSize,
5186 NumBytesTmp, AvailableFPRs, AvailableVRs,
5187 Subtarget.hasQPX()))
5188 HasParameterArea = true;
5192 // When using the fast calling convention, we don't provide backing for
5193 // arguments that will be in registers.
5194 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5196 // Add up all the space actually used.
5197 for (unsigned i = 0; i != NumOps; ++i) {
5198 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5199 EVT ArgVT = Outs[i].VT;
5200 EVT OrigVT = Outs[i].ArgVT;
5205 if (CallConv == CallingConv::Fast) {
5206 if (Flags.isByVal())
5207 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5209 switch (ArgVT.getSimpleVT().SimpleTy) {
5210 default: llvm_unreachable("Unexpected ValueType for argument!");
5214 if (++NumGPRsUsed <= NumGPRs)
5223 if (++NumVRsUsed <= NumVRs)
5227 // When using QPX, this is handled like a FP register, otherwise, it
5228 // is an Altivec register.
5229 if (Subtarget.hasQPX()) {
5230 if (++NumFPRsUsed <= NumFPRs)
5233 if (++NumVRsUsed <= NumVRs)
5239 case MVT::v4f64: // QPX
5240 case MVT::v4i1: // QPX
5241 if (++NumFPRsUsed <= NumFPRs)
5247 /* Respect alignment of argument on the stack. */
5249 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5250 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5252 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5253 if (Flags.isInConsecutiveRegsLast())
5254 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5257 unsigned NumBytesActuallyUsed = NumBytes;
5259 // In the old ELFv1 ABI,
5260 // the prolog code of the callee may store up to 8 GPR argument registers to
5261 // the stack, allowing va_start to index over them in memory if its varargs.
5262 // Because we cannot tell if this is needed on the caller side, we have to
5263 // conservatively assume that it is needed. As such, make sure we have at
5264 // least enough stack space for the caller to store the 8 GPRs.
5265 // In the ELFv2 ABI, we allocate the parameter area iff a callee
5266 // really requires memory operands, e.g. a vararg function.
5267 if (HasParameterArea)
5268 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5270 NumBytes = LinkageSize;
5272 // Tail call needs the stack to be aligned.
5273 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5274 CallConv == CallingConv::Fast)
5275 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5279 // Calculate by how many bytes the stack has to be adjusted in case of tail
5280 // call optimization.
5282 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5284 // To protect arguments on the stack from being clobbered in a tail call,
5285 // force all the loads to happen before doing any other lowering.
5287 Chain = DAG.getStackArgumentTokenFactor(Chain);
5289 // Adjust the stack pointer for the new arguments...
5290 // These operations are automatically eliminated by the prolog/epilog pass
5292 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5293 SDValue CallSeqStart = Chain;
5295 // Load the return address and frame pointer so it can be move somewhere else
5298 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5300 // Set up a copy of the stack pointer for use loading and storing any
5301 // arguments that may not fit in the registers available for argument
5303 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5305 // Figure out which arguments are going to go in registers, and which in
5306 // memory. Also, if this is a vararg function, floating point operations
5307 // must be stored to our stack, and loaded into integer regs as well, if
5308 // any integer regs are available for argument passing.
5309 unsigned ArgOffset = LinkageSize;
5311 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5312 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5314 SmallVector<SDValue, 8> MemOpChains;
5315 for (unsigned i = 0; i != NumOps; ++i) {
5316 SDValue Arg = OutVals[i];
5317 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5318 EVT ArgVT = Outs[i].VT;
5319 EVT OrigVT = Outs[i].ArgVT;
5321 // PtrOff will be used to store the current argument to the stack if a
5322 // register cannot be found for it.
5325 // We re-align the argument offset for each argument, except when using the
5326 // fast calling convention, when we need to make sure we do that only when
5327 // we'll actually use a stack slot.
5328 auto ComputePtrOff = [&]() {
5329 /* Respect alignment of argument on the stack. */
5331 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5332 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5334 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5336 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5339 if (CallConv != CallingConv::Fast) {
5342 /* Compute GPR index associated with argument offset. */
5343 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5344 GPR_idx = std::min(GPR_idx, NumGPRs);
5347 // Promote integers to 64-bit values.
5348 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5349 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5350 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5351 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5354 // FIXME memcpy is used way more than necessary. Correctness first.
5355 // Note: "by value" is code for passing a structure by value, not
5357 if (Flags.isByVal()) {
5358 // Note: Size includes alignment padding, so
5359 // struct x { short a; char b; }
5360 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
5361 // These are the proper values we need for right-justifying the
5362 // aggregate in a parameter register.
5363 unsigned Size = Flags.getByValSize();
5365 // An empty aggregate parameter takes up no storage and no
5370 if (CallConv == CallingConv::Fast)
5373 // All aggregates smaller than 8 bytes must be passed right-justified.
5374 if (Size==1 || Size==2 || Size==4) {
5375 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5376 if (GPR_idx != NumGPRs) {
5377 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5378 MachinePointerInfo(), VT);
5379 MemOpChains.push_back(Load.getValue(1));
5380 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5382 ArgOffset += PtrByteSize;
5387 if (GPR_idx == NumGPRs && Size < 8) {
5388 SDValue AddPtr = PtrOff;
5389 if (!isLittleEndian) {
5390 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5391 PtrOff.getValueType());
5392 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5394 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5397 ArgOffset += PtrByteSize;
5400 // Copy entire object into memory. There are cases where gcc-generated
5401 // code assumes it is there, even if it could be put entirely into
5402 // registers. (This is not what the doc says.)
5404 // FIXME: The above statement is likely due to a misunderstanding of the
5405 // documents. All arguments must be copied into the parameter area BY
5406 // THE CALLEE in the event that the callee takes the address of any
5407 // formal argument. That has not yet been implemented. However, it is
5408 // reasonable to use the stack area as a staging area for the register
5411 // Skip this for small aggregates, as we will use the same slot for a
5412 // right-justified copy, below.
5414 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5418 // When a register is available, pass a small aggregate right-justified.
5419 if (Size < 8 && GPR_idx != NumGPRs) {
5420 // The easiest way to get this right-justified in a register
5421 // is to copy the structure into the rightmost portion of a
5422 // local variable slot, then load the whole slot into the
5424 // FIXME: The memcpy seems to produce pretty awful code for
5425 // small aggregates, particularly for packed ones.
5426 // FIXME: It would be preferable to use the slot in the
5427 // parameter save area instead of a new local variable.
5428 SDValue AddPtr = PtrOff;
5429 if (!isLittleEndian) {
5430 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5431 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5433 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5437 // Load the slot into the register.
5439 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5440 MemOpChains.push_back(Load.getValue(1));
5441 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5443 // Done with this argument.
5444 ArgOffset += PtrByteSize;
5448 // For aggregates larger than PtrByteSize, copy the pieces of the
5449 // object that fit into registers from the parameter save area.
5450 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5451 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5452 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5453 if (GPR_idx != NumGPRs) {
5455 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5456 MemOpChains.push_back(Load.getValue(1));
5457 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5458 ArgOffset += PtrByteSize;
5460 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5467 switch (Arg.getSimpleValueType().SimpleTy) {
5468 default: llvm_unreachable("Unexpected ValueType for argument!");
5472 if (Flags.isNest()) {
5473 // The 'nest' parameter, if any, is passed in R11.
5474 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5479 // These can be scalar arguments or elements of an integer array type
5480 // passed directly. Clang may use those instead of "byval" aggregate
5481 // types to avoid forcing arguments to memory unnecessarily.
5482 if (GPR_idx != NumGPRs) {
5483 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5485 if (CallConv == CallingConv::Fast)
5488 assert(HasParameterArea &&
5489 "Parameter area must exist to pass an argument in memory.");
5490 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5491 true, isTailCall, false, MemOpChains,
5492 TailCallArguments, dl);
5493 if (CallConv == CallingConv::Fast)
5494 ArgOffset += PtrByteSize;
5496 if (CallConv != CallingConv::Fast)
5497 ArgOffset += PtrByteSize;
5501 // These can be scalar arguments or elements of a float array type
5502 // passed directly. The latter are used to implement ELFv2 homogenous
5503 // float aggregates.
5505 // Named arguments go into FPRs first, and once they overflow, the
5506 // remaining arguments go into GPRs and then the parameter save area.
5507 // Unnamed arguments for vararg functions always go to GPRs and
5508 // then the parameter save area. For now, put all arguments to vararg
5509 // routines always in both locations (FPR *and* GPR or stack slot).
5510 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5511 bool NeededLoad = false;
5513 // First load the argument into the next available FPR.
5514 if (FPR_idx != NumFPRs)
5515 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5517 // Next, load the argument into GPR or stack slot if needed.
5518 if (!NeedGPROrStack)
5520 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5521 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5522 // once we support fp <-> gpr moves.
5524 // In the non-vararg case, this can only ever happen in the
5525 // presence of f32 array types, since otherwise we never run
5526 // out of FPRs before running out of GPRs.
5529 // Double values are always passed in a single GPR.
5530 if (Arg.getValueType() != MVT::f32) {
5531 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5533 // Non-array float values are extended and passed in a GPR.
5534 } else if (!Flags.isInConsecutiveRegs()) {
5535 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5536 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5538 // If we have an array of floats, we collect every odd element
5539 // together with its predecessor into one GPR.
5540 } else if (ArgOffset % PtrByteSize != 0) {
5542 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5543 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5544 if (!isLittleEndian)
5546 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5548 // The final element, if even, goes into the first half of a GPR.
5549 } else if (Flags.isInConsecutiveRegsLast()) {
5550 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5551 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5552 if (!isLittleEndian)
5553 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5554 DAG.getConstant(32, dl, MVT::i32));
5556 // Non-final even elements are skipped; they will be handled
5557 // together the with subsequent argument on the next go-around.
5561 if (ArgVal.getNode())
5562 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5564 if (CallConv == CallingConv::Fast)
5567 // Single-precision floating-point values are mapped to the
5568 // second (rightmost) word of the stack doubleword.
5569 if (Arg.getValueType() == MVT::f32 &&
5570 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5571 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5572 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5575 assert(HasParameterArea &&
5576 "Parameter area must exist to pass an argument in memory.");
5577 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5578 true, isTailCall, false, MemOpChains,
5579 TailCallArguments, dl);
5583 // When passing an array of floats, the array occupies consecutive
5584 // space in the argument area; only round up to the next doubleword
5585 // at the end of the array. Otherwise, each float takes 8 bytes.
5586 if (CallConv != CallingConv::Fast || NeededLoad) {
5587 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5588 Flags.isInConsecutiveRegs()) ? 4 : 8;
5589 if (Flags.isInConsecutiveRegsLast())
5590 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5601 if (!Subtarget.hasQPX()) {
5602 // These can be scalar arguments or elements of a vector array type
5603 // passed directly. The latter are used to implement ELFv2 homogenous
5604 // vector aggregates.
5606 // For a varargs call, named arguments go into VRs or on the stack as
5607 // usual; unnamed arguments always go to the stack or the corresponding
5608 // GPRs when within range. For now, we always put the value in both
5609 // locations (or even all three).
5611 assert(HasParameterArea &&
5612 "Parameter area must exist if we have a varargs call.");
5613 // We could elide this store in the case where the object fits
5614 // entirely in R registers. Maybe later.
5616 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5617 MemOpChains.push_back(Store);
5618 if (VR_idx != NumVRs) {
5620 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5621 MemOpChains.push_back(Load.getValue(1));
5622 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5625 for (unsigned i=0; i<16; i+=PtrByteSize) {
5626 if (GPR_idx == NumGPRs)
5628 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5629 DAG.getConstant(i, dl, PtrVT));
5631 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5632 MemOpChains.push_back(Load.getValue(1));
5633 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5638 // Non-varargs Altivec params go into VRs or on the stack.
5639 if (VR_idx != NumVRs) {
5640 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5642 if (CallConv == CallingConv::Fast)
5645 assert(HasParameterArea &&
5646 "Parameter area must exist to pass an argument in memory.");
5647 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5648 true, isTailCall, true, MemOpChains,
5649 TailCallArguments, dl);
5650 if (CallConv == CallingConv::Fast)
5654 if (CallConv != CallingConv::Fast)
5659 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5660 "Invalid QPX parameter type");
5665 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5667 assert(HasParameterArea &&
5668 "Parameter area must exist if we have a varargs call.");
5669 // We could elide this store in the case where the object fits
5670 // entirely in R registers. Maybe later.
5672 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5673 MemOpChains.push_back(Store);
5674 if (QFPR_idx != NumQFPRs) {
5675 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5676 PtrOff, MachinePointerInfo());
5677 MemOpChains.push_back(Load.getValue(1));
5678 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5680 ArgOffset += (IsF32 ? 16 : 32);
5681 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5682 if (GPR_idx == NumGPRs)
5684 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5685 DAG.getConstant(i, dl, PtrVT));
5687 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5688 MemOpChains.push_back(Load.getValue(1));
5689 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5694 // Non-varargs QPX params go into registers or on the stack.
5695 if (QFPR_idx != NumQFPRs) {
5696 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5698 if (CallConv == CallingConv::Fast)
5701 assert(HasParameterArea &&
5702 "Parameter area must exist to pass an argument in memory.");
5703 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5704 true, isTailCall, true, MemOpChains,
5705 TailCallArguments, dl);
5706 if (CallConv == CallingConv::Fast)
5707 ArgOffset += (IsF32 ? 16 : 32);
5710 if (CallConv != CallingConv::Fast)
5711 ArgOffset += (IsF32 ? 16 : 32);
5717 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5718 "mismatch in size of parameter area");
5719 (void)NumBytesActuallyUsed;
5721 if (!MemOpChains.empty())
5722 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5724 // Check if this is an indirect call (MTCTR/BCTRL).
5725 // See PrepareCall() for more information about calls through function
5726 // pointers in the 64-bit SVR4 ABI.
5727 if (!isTailCall && !isPatchPoint &&
5728 !isFunctionGlobalAddress(Callee) &&
5729 !isa<ExternalSymbolSDNode>(Callee)) {
5730 // Load r2 into a virtual register and store it to the TOC save area.
5731 setUsesTOCBasePtr(DAG);
5732 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5733 // TOC save area offset.
5734 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5735 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5736 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5737 Chain = DAG.getStore(
5738 Val.getValue(1), dl, Val, AddPtr,
5739 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5740 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5741 // This does not mean the MTCTR instruction must use R12; it's easier
5742 // to model this as an extra parameter, so do that.
5743 if (isELFv2ABI && !isPatchPoint)
5744 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5747 // Build a sequence of copy-to-reg nodes chained together with token chain
5748 // and flag operands which copy the outgoing args into the appropriate regs.
5750 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5751 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5752 RegsToPass[i].second, InFlag);
5753 InFlag = Chain.getValue(1);
5756 if (isTailCall && !IsSibCall)
5757 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5760 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5761 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5762 SPDiff, NumBytes, Ins, InVals, CS);
5765 SDValue PPCTargetLowering::LowerCall_Darwin(
5766 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5767 bool isTailCall, bool isPatchPoint,
5768 const SmallVectorImpl<ISD::OutputArg> &Outs,
5769 const SmallVectorImpl<SDValue> &OutVals,
5770 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5771 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5772 ImmutableCallSite *CS) const {
5773 unsigned NumOps = Outs.size();
5775 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5776 bool isPPC64 = PtrVT == MVT::i64;
5777 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5779 MachineFunction &MF = DAG.getMachineFunction();
5781 // Mark this function as potentially containing a function that contains a
5782 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5783 // and restoring the callers stack pointer in this functions epilog. This is
5784 // done because by tail calling the called function might overwrite the value
5785 // in this function's (MF) stack pointer stack slot 0(SP).
5786 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5787 CallConv == CallingConv::Fast)
5788 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5790 // Count how many bytes are to be pushed on the stack, including the linkage
5791 // area, and parameter passing area. We start with 24/48 bytes, which is
5792 // prereserved space for [SP][CR][LR][3 x unused].
5793 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5794 unsigned NumBytes = LinkageSize;
5796 // Add up all the space actually used.
5797 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5798 // they all go in registers, but we must reserve stack space for them for
5799 // possible use by the caller. In varargs or 64-bit calls, parameters are
5800 // assigned stack space in order, with padding so Altivec parameters are
5802 unsigned nAltivecParamsAtEnd = 0;
5803 for (unsigned i = 0; i != NumOps; ++i) {
5804 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5805 EVT ArgVT = Outs[i].VT;
5806 // Varargs Altivec parameters are padded to a 16 byte boundary.
5807 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5808 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5809 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5810 if (!isVarArg && !isPPC64) {
5811 // Non-varargs Altivec parameters go after all the non-Altivec
5812 // parameters; handle those later so we know how much padding we need.
5813 nAltivecParamsAtEnd++;
5816 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5817 NumBytes = ((NumBytes+15)/16)*16;
5819 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5822 // Allow for Altivec parameters at the end, if needed.
5823 if (nAltivecParamsAtEnd) {
5824 NumBytes = ((NumBytes+15)/16)*16;
5825 NumBytes += 16*nAltivecParamsAtEnd;
5828 // The prolog code of the callee may store up to 8 GPR argument registers to
5829 // the stack, allowing va_start to index over them in memory if its varargs.
5830 // Because we cannot tell if this is needed on the caller side, we have to
5831 // conservatively assume that it is needed. As such, make sure we have at
5832 // least enough stack space for the caller to store the 8 GPRs.
5833 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5835 // Tail call needs the stack to be aligned.
5836 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5837 CallConv == CallingConv::Fast)
5838 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5840 // Calculate by how many bytes the stack has to be adjusted in case of tail
5841 // call optimization.
5842 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5844 // To protect arguments on the stack from being clobbered in a tail call,
5845 // force all the loads to happen before doing any other lowering.
5847 Chain = DAG.getStackArgumentTokenFactor(Chain);
5849 // Adjust the stack pointer for the new arguments...
5850 // These operations are automatically eliminated by the prolog/epilog pass
5851 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5852 SDValue CallSeqStart = Chain;
5854 // Load the return address and frame pointer so it can be move somewhere else
5857 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5859 // Set up a copy of the stack pointer for use loading and storing any
5860 // arguments that may not fit in the registers available for argument
5864 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5866 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5868 // Figure out which arguments are going to go in registers, and which in
5869 // memory. Also, if this is a vararg function, floating point operations
5870 // must be stored to our stack, and loaded into integer regs as well, if
5871 // any integer regs are available for argument passing.
5872 unsigned ArgOffset = LinkageSize;
5873 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5875 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5876 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5877 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5879 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5880 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5881 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5883 static const MCPhysReg VR[] = {
5884 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5885 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5887 const unsigned NumGPRs = array_lengthof(GPR_32);
5888 const unsigned NumFPRs = 13;
5889 const unsigned NumVRs = array_lengthof(VR);
5891 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5893 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5894 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5896 SmallVector<SDValue, 8> MemOpChains;
5897 for (unsigned i = 0; i != NumOps; ++i) {
5898 SDValue Arg = OutVals[i];
5899 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5901 // PtrOff will be used to store the current argument to the stack if a
5902 // register cannot be found for it.
5905 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5907 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5909 // On PPC64, promote integers to 64-bit values.
5910 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5911 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5912 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5913 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5916 // FIXME memcpy is used way more than necessary. Correctness first.
5917 // Note: "by value" is code for passing a structure by value, not
5919 if (Flags.isByVal()) {
5920 unsigned Size = Flags.getByValSize();
5921 // Very small objects are passed right-justified. Everything else is
5922 // passed left-justified.
5923 if (Size==1 || Size==2) {
5924 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5925 if (GPR_idx != NumGPRs) {
5926 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5927 MachinePointerInfo(), VT);
5928 MemOpChains.push_back(Load.getValue(1));
5929 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5931 ArgOffset += PtrByteSize;
5933 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5934 PtrOff.getValueType());
5935 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5936 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5939 ArgOffset += PtrByteSize;
5943 // Copy entire object into memory. There are cases where gcc-generated
5944 // code assumes it is there, even if it could be put entirely into
5945 // registers. (This is not what the doc says.)
5946 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5950 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5951 // copy the pieces of the object that fit into registers from the
5952 // parameter save area.
5953 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5954 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5955 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5956 if (GPR_idx != NumGPRs) {
5958 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5959 MemOpChains.push_back(Load.getValue(1));
5960 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5961 ArgOffset += PtrByteSize;
5963 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5970 switch (Arg.getSimpleValueType().SimpleTy) {
5971 default: llvm_unreachable("Unexpected ValueType for argument!");
5975 if (GPR_idx != NumGPRs) {
5976 if (Arg.getValueType() == MVT::i1)
5977 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5979 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5981 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5982 isPPC64, isTailCall, false, MemOpChains,
5983 TailCallArguments, dl);
5985 ArgOffset += PtrByteSize;
5989 if (FPR_idx != NumFPRs) {
5990 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5994 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5995 MemOpChains.push_back(Store);
5997 // Float varargs are always shadowed in available integer registers
5998 if (GPR_idx != NumGPRs) {
6000 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6001 MemOpChains.push_back(Load.getValue(1));
6002 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6004 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6005 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6006 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6008 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6009 MemOpChains.push_back(Load.getValue(1));
6010 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6013 // If we have any FPRs remaining, we may also have GPRs remaining.
6014 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6016 if (GPR_idx != NumGPRs)
6018 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6019 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
6023 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6024 isPPC64, isTailCall, false, MemOpChains,
6025 TailCallArguments, dl);
6029 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6036 // These go aligned on the stack, or in the corresponding R registers
6037 // when within range. The Darwin PPC ABI doc claims they also go in
6038 // V registers; in fact gcc does this only for arguments that are
6039 // prototyped, not for those that match the ... We do it for all
6040 // arguments, seems to work.
6041 while (ArgOffset % 16 !=0) {
6042 ArgOffset += PtrByteSize;
6043 if (GPR_idx != NumGPRs)
6046 // We could elide this store in the case where the object fits
6047 // entirely in R registers. Maybe later.
6048 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6049 DAG.getConstant(ArgOffset, dl, PtrVT));
6051 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6052 MemOpChains.push_back(Store);
6053 if (VR_idx != NumVRs) {
6055 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6056 MemOpChains.push_back(Load.getValue(1));
6057 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6060 for (unsigned i=0; i<16; i+=PtrByteSize) {
6061 if (GPR_idx == NumGPRs)
6063 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6064 DAG.getConstant(i, dl, PtrVT));
6066 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6067 MemOpChains.push_back(Load.getValue(1));
6068 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6073 // Non-varargs Altivec params generally go in registers, but have
6074 // stack space allocated at the end.
6075 if (VR_idx != NumVRs) {
6076 // Doesn't have GPR space allocated.
6077 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6078 } else if (nAltivecParamsAtEnd==0) {
6079 // We are emitting Altivec params in order.
6080 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6081 isPPC64, isTailCall, true, MemOpChains,
6082 TailCallArguments, dl);
6088 // If all Altivec parameters fit in registers, as they usually do,
6089 // they get stack space following the non-Altivec parameters. We
6090 // don't track this here because nobody below needs it.
6091 // If there are more Altivec parameters than fit in registers emit
6093 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6095 // Offset is aligned; skip 1st 12 params which go in V registers.
6096 ArgOffset = ((ArgOffset+15)/16)*16;
6098 for (unsigned i = 0; i != NumOps; ++i) {
6099 SDValue Arg = OutVals[i];
6100 EVT ArgType = Outs[i].VT;
6101 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6102 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6105 // We are emitting Altivec params in order.
6106 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6107 isPPC64, isTailCall, true, MemOpChains,
6108 TailCallArguments, dl);
6115 if (!MemOpChains.empty())
6116 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6118 // On Darwin, R12 must contain the address of an indirect callee. This does
6119 // not mean the MTCTR instruction must use R12; it's easier to model this as
6120 // an extra parameter, so do that.
6122 !isFunctionGlobalAddress(Callee) &&
6123 !isa<ExternalSymbolSDNode>(Callee) &&
6124 !isBLACompatibleAddress(Callee, DAG))
6125 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6126 PPC::R12), Callee));
6128 // Build a sequence of copy-to-reg nodes chained together with token chain
6129 // and flag operands which copy the outgoing args into the appropriate regs.
6131 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6132 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6133 RegsToPass[i].second, InFlag);
6134 InFlag = Chain.getValue(1);
6138 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6141 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6142 /* unused except on PPC64 ELFv1 */ false, DAG,
6143 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6144 NumBytes, Ins, InVals, CS);
6148 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6149 MachineFunction &MF, bool isVarArg,
6150 const SmallVectorImpl<ISD::OutputArg> &Outs,
6151 LLVMContext &Context) const {
6152 SmallVector<CCValAssign, 16> RVLocs;
6153 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6154 return CCInfo.CheckReturn(Outs, RetCC_PPC);
6158 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6160 const SmallVectorImpl<ISD::OutputArg> &Outs,
6161 const SmallVectorImpl<SDValue> &OutVals,
6162 const SDLoc &dl, SelectionDAG &DAG) const {
6163 SmallVector<CCValAssign, 16> RVLocs;
6164 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6166 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6169 SmallVector<SDValue, 4> RetOps(1, Chain);
6171 // Copy the result values into the output registers.
6172 for (unsigned i = 0; i != RVLocs.size(); ++i) {
6173 CCValAssign &VA = RVLocs[i];
6174 assert(VA.isRegLoc() && "Can only return in registers!");
6176 SDValue Arg = OutVals[i];
6178 switch (VA.getLocInfo()) {
6179 default: llvm_unreachable("Unknown loc info!");
6180 case CCValAssign::Full: break;
6181 case CCValAssign::AExt:
6182 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6184 case CCValAssign::ZExt:
6185 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6187 case CCValAssign::SExt:
6188 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6192 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6193 Flag = Chain.getValue(1);
6194 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6197 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6198 const MCPhysReg *I =
6199 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6203 if (PPC::G8RCRegClass.contains(*I))
6204 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6205 else if (PPC::F8RCRegClass.contains(*I))
6206 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6207 else if (PPC::CRRCRegClass.contains(*I))
6208 RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6209 else if (PPC::VRRCRegClass.contains(*I))
6210 RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6212 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6216 RetOps[0] = Chain; // Update chain.
6218 // Add the flag if we have it.
6220 RetOps.push_back(Flag);
6222 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6226 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6227 SelectionDAG &DAG) const {
6230 // Get the corect type for integers.
6231 EVT IntVT = Op.getValueType();
6234 SDValue Chain = Op.getOperand(0);
6235 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6236 // Build a DYNAREAOFFSET node.
6237 SDValue Ops[2] = {Chain, FPSIdx};
6238 SDVTList VTs = DAG.getVTList(IntVT);
6239 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6242 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6243 SelectionDAG &DAG) const {
6244 // When we pop the dynamic allocation we need to restore the SP link.
6247 // Get the corect type for pointers.
6248 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6250 // Construct the stack pointer operand.
6251 bool isPPC64 = Subtarget.isPPC64();
6252 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6253 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6255 // Get the operands for the STACKRESTORE.
6256 SDValue Chain = Op.getOperand(0);
6257 SDValue SaveSP = Op.getOperand(1);
6259 // Load the old link SP.
6260 SDValue LoadLinkSP =
6261 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6263 // Restore the stack pointer.
6264 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6266 // Store the old link SP.
6267 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6270 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6271 MachineFunction &MF = DAG.getMachineFunction();
6272 bool isPPC64 = Subtarget.isPPC64();
6273 EVT PtrVT = getPointerTy(MF.getDataLayout());
6275 // Get current frame pointer save index. The users of this index will be
6276 // primarily DYNALLOC instructions.
6277 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6278 int RASI = FI->getReturnAddrSaveIndex();
6280 // If the frame pointer save index hasn't been defined yet.
6282 // Find out what the fix offset of the frame pointer save area.
6283 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6284 // Allocate the frame index for frame pointer save area.
6285 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6287 FI->setReturnAddrSaveIndex(RASI);
6289 return DAG.getFrameIndex(RASI, PtrVT);
6293 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6294 MachineFunction &MF = DAG.getMachineFunction();
6295 bool isPPC64 = Subtarget.isPPC64();
6296 EVT PtrVT = getPointerTy(MF.getDataLayout());
6298 // Get current frame pointer save index. The users of this index will be
6299 // primarily DYNALLOC instructions.
6300 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6301 int FPSI = FI->getFramePointerSaveIndex();
6303 // If the frame pointer save index hasn't been defined yet.
6305 // Find out what the fix offset of the frame pointer save area.
6306 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6307 // Allocate the frame index for frame pointer save area.
6308 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6310 FI->setFramePointerSaveIndex(FPSI);
6312 return DAG.getFrameIndex(FPSI, PtrVT);
6315 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6316 SelectionDAG &DAG) const {
6318 SDValue Chain = Op.getOperand(0);
6319 SDValue Size = Op.getOperand(1);
6322 // Get the corect type for pointers.
6323 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6325 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6326 DAG.getConstant(0, dl, PtrVT), Size);
6327 // Construct a node for the frame pointer save index.
6328 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6329 // Build a DYNALLOC node.
6330 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6331 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6332 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6335 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6336 SelectionDAG &DAG) const {
6337 MachineFunction &MF = DAG.getMachineFunction();
6339 bool isPPC64 = Subtarget.isPPC64();
6340 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6342 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6343 return DAG.getFrameIndex(FI, PtrVT);
6346 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6347 SelectionDAG &DAG) const {
6349 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6350 DAG.getVTList(MVT::i32, MVT::Other),
6351 Op.getOperand(0), Op.getOperand(1));
6354 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6355 SelectionDAG &DAG) const {
6357 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6358 Op.getOperand(0), Op.getOperand(1));
6361 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6362 if (Op.getValueType().isVector())
6363 return LowerVectorLoad(Op, DAG);
6365 assert(Op.getValueType() == MVT::i1 &&
6366 "Custom lowering only for i1 loads");
6368 // First, load 8 bits into 32 bits, then truncate to 1 bit.
6371 LoadSDNode *LD = cast<LoadSDNode>(Op);
6373 SDValue Chain = LD->getChain();
6374 SDValue BasePtr = LD->getBasePtr();
6375 MachineMemOperand *MMO = LD->getMemOperand();
6378 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6379 BasePtr, MVT::i8, MMO);
6380 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6382 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6383 return DAG.getMergeValues(Ops, dl);
6386 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6387 if (Op.getOperand(1).getValueType().isVector())
6388 return LowerVectorStore(Op, DAG);
6390 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6391 "Custom lowering only for i1 stores");
6393 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6396 StoreSDNode *ST = cast<StoreSDNode>(Op);
6398 SDValue Chain = ST->getChain();
6399 SDValue BasePtr = ST->getBasePtr();
6400 SDValue Value = ST->getValue();
6401 MachineMemOperand *MMO = ST->getMemOperand();
6403 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6405 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6408 // FIXME: Remove this once the ANDI glue bug is fixed:
6409 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6410 assert(Op.getValueType() == MVT::i1 &&
6411 "Custom lowering only for i1 results");
6414 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6418 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6420 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6421 // Not FP? Not a fsel.
6422 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6423 !Op.getOperand(2).getValueType().isFloatingPoint())
6426 // We might be able to do better than this under some circumstances, but in
6427 // general, fsel-based lowering of select is a finite-math-only optimization.
6428 // For more information, see section F.3 of the 2.06 ISA specification.
6429 if (!DAG.getTarget().Options.NoInfsFPMath ||
6430 !DAG.getTarget().Options.NoNaNsFPMath)
6432 // TODO: Propagate flags from the select rather than global settings.
6434 Flags.setNoInfs(true);
6435 Flags.setNoNaNs(true);
6437 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6439 EVT ResVT = Op.getValueType();
6440 EVT CmpVT = Op.getOperand(0).getValueType();
6441 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6442 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
6445 // If the RHS of the comparison is a 0.0, we don't need to do the
6446 // subtraction at all.
6448 if (isFloatingPointZero(RHS))
6450 default: break; // SETUO etc aren't handled by fsel.
6454 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6455 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6456 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6457 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6458 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6459 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6460 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6463 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6466 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6467 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6468 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6471 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6474 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6475 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6476 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6477 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6482 default: break; // SETUO etc aren't handled by fsel.
6486 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6487 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6488 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6489 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6490 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6491 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6492 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6493 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6496 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6497 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6498 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6499 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6502 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6503 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6504 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6505 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6508 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6509 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6510 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6511 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6514 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6515 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6516 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6517 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6522 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6524 const SDLoc &dl) const {
6525 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6526 SDValue Src = Op.getOperand(0);
6527 if (Src.getValueType() == MVT::f32)
6528 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6531 switch (Op.getSimpleValueType().SimpleTy) {
6532 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6535 Op.getOpcode() == ISD::FP_TO_SINT
6537 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6541 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6542 "i64 FP_TO_UINT is supported only with FPCVT");
6543 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6549 // Convert the FP value to an int value through memory.
6550 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6551 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6552 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6553 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6554 MachinePointerInfo MPI =
6555 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6557 // Emit a store to the stack slot.
6560 MachineFunction &MF = DAG.getMachineFunction();
6561 MachineMemOperand *MMO =
6562 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6563 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6564 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6565 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6567 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6569 // Result is a load from the stack slot. If loading 4 bytes, make sure to
6570 // add in a bias on big endian.
6571 if (Op.getValueType() == MVT::i32 && !i32Stack) {
6572 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6573 DAG.getConstant(4, dl, FIPtr.getValueType()));
6574 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6582 /// \brief Custom lowers floating point to integer conversions to use
6583 /// the direct move instructions available in ISA 2.07 to avoid the
6584 /// need for load/store combinations.
6585 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6587 const SDLoc &dl) const {
6588 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6589 SDValue Src = Op.getOperand(0);
6591 if (Src.getValueType() == MVT::f32)
6592 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6595 switch (Op.getSimpleValueType().SimpleTy) {
6596 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6599 Op.getOpcode() == ISD::FP_TO_SINT
6601 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6603 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6606 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6607 "i64 FP_TO_UINT is supported only with FPCVT");
6608 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6611 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6617 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6618 const SDLoc &dl) const {
6619 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6620 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6623 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6625 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6626 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6629 // We're trying to insert a regular store, S, and then a load, L. If the
6630 // incoming value, O, is a load, we might just be able to have our load use the
6631 // address used by O. However, we don't know if anything else will store to
6632 // that address before we can load from it. To prevent this situation, we need
6633 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6634 // the same chain operand as O, we create a token factor from the chain results
6635 // of O and L, and we replace all uses of O's chain result with that token
6636 // factor (see spliceIntoChain below for this last part).
6637 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6640 ISD::LoadExtType ET) const {
6642 if (ET == ISD::NON_EXTLOAD &&
6643 (Op.getOpcode() == ISD::FP_TO_UINT ||
6644 Op.getOpcode() == ISD::FP_TO_SINT) &&
6645 isOperationLegalOrCustom(Op.getOpcode(),
6646 Op.getOperand(0).getValueType())) {
6648 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6652 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6653 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6654 LD->isNonTemporal())
6656 if (LD->getMemoryVT() != MemVT)
6659 RLI.Ptr = LD->getBasePtr();
6660 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6661 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6662 "Non-pre-inc AM on PPC?");
6663 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6667 RLI.Chain = LD->getChain();
6668 RLI.MPI = LD->getPointerInfo();
6669 RLI.IsDereferenceable = LD->isDereferenceable();
6670 RLI.IsInvariant = LD->isInvariant();
6671 RLI.Alignment = LD->getAlignment();
6672 RLI.AAInfo = LD->getAAInfo();
6673 RLI.Ranges = LD->getRanges();
6675 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6679 // Given the head of the old chain, ResChain, insert a token factor containing
6680 // it and NewResChain, and make users of ResChain now be users of that token
6682 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6683 SDValue NewResChain,
6684 SelectionDAG &DAG) const {
6688 SDLoc dl(NewResChain);
6690 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6691 NewResChain, DAG.getUNDEF(MVT::Other));
6692 assert(TF.getNode() != NewResChain.getNode() &&
6693 "A new TF really is required here");
6695 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6696 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6699 /// \brief Analyze profitability of direct move
6700 /// prefer float load to int load plus direct move
6701 /// when there is no integer use of int load
6702 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6703 SDNode *Origin = Op.getOperand(0).getNode();
6704 if (Origin->getOpcode() != ISD::LOAD)
6707 // If there is no LXSIBZX/LXSIHZX, like Power8,
6708 // prefer direct move if the memory size is 1 or 2 bytes.
6709 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6710 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6713 for (SDNode::use_iterator UI = Origin->use_begin(),
6714 UE = Origin->use_end();
6717 // Only look at the users of the loaded value.
6718 if (UI.getUse().get().getResNo() != 0)
6721 if (UI->getOpcode() != ISD::SINT_TO_FP &&
6722 UI->getOpcode() != ISD::UINT_TO_FP)
6729 /// \brief Custom lowers integer to floating point conversions to use
6730 /// the direct move instructions available in ISA 2.07 to avoid the
6731 /// need for load/store combinations.
6732 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6734 const SDLoc &dl) const {
6735 assert((Op.getValueType() == MVT::f32 ||
6736 Op.getValueType() == MVT::f64) &&
6737 "Invalid floating point type as target of conversion");
6738 assert(Subtarget.hasFPCVT() &&
6739 "Int to FP conversions with direct moves require FPCVT");
6741 SDValue Src = Op.getOperand(0);
6742 bool SinglePrec = Op.getValueType() == MVT::f32;
6743 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6744 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6745 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6746 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6749 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6751 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6754 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6755 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6761 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6762 SelectionDAG &DAG) const {
6765 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6766 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6769 SDValue Value = Op.getOperand(0);
6770 // The values are now known to be -1 (false) or 1 (true). To convert this
6771 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6772 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6773 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6775 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6777 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6779 if (Op.getValueType() != MVT::v4f64)
6780 Value = DAG.getNode(ISD::FP_ROUND, dl,
6781 Op.getValueType(), Value,
6782 DAG.getIntPtrConstant(1, dl));
6786 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6787 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6790 if (Op.getOperand(0).getValueType() == MVT::i1)
6791 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6792 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6793 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6795 // If we have direct moves, we can do all the conversion, skip the store/load
6796 // however, without FPCVT we can't do most conversions.
6797 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6798 Subtarget.isPPC64() && Subtarget.hasFPCVT())
6799 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6801 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6802 "UINT_TO_FP is supported only with FPCVT");
6804 // If we have FCFIDS, then use it when converting to single-precision.
6805 // Otherwise, convert to double-precision and then round.
6806 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6807 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6809 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6811 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6815 if (Op.getOperand(0).getValueType() == MVT::i64) {
6816 SDValue SINT = Op.getOperand(0);
6817 // When converting to single-precision, we actually need to convert
6818 // to double-precision first and then round to single-precision.
6819 // To avoid double-rounding effects during that operation, we have
6820 // to prepare the input operand. Bits that might be truncated when
6821 // converting to double-precision are replaced by a bit that won't
6822 // be lost at this stage, but is below the single-precision rounding
6825 // However, if -enable-unsafe-fp-math is in effect, accept double
6826 // rounding to avoid the extra overhead.
6827 if (Op.getValueType() == MVT::f32 &&
6828 !Subtarget.hasFPCVT() &&
6829 !DAG.getTarget().Options.UnsafeFPMath) {
6831 // Twiddle input to make sure the low 11 bits are zero. (If this
6832 // is the case, we are guaranteed the value will fit into the 53 bit
6833 // mantissa of an IEEE double-precision value without rounding.)
6834 // If any of those low 11 bits were not zero originally, make sure
6835 // bit 12 (value 2048) is set instead, so that the final rounding
6836 // to single-precision gets the correct result.
6837 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6838 SINT, DAG.getConstant(2047, dl, MVT::i64));
6839 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6840 Round, DAG.getConstant(2047, dl, MVT::i64));
6841 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6842 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6843 Round, DAG.getConstant(-2048, dl, MVT::i64));
6845 // However, we cannot use that value unconditionally: if the magnitude
6846 // of the input value is small, the bit-twiddling we did above might
6847 // end up visibly changing the output. Fortunately, in that case, we
6848 // don't need to twiddle bits since the original input will convert
6849 // exactly to double-precision floating-point already. Therefore,
6850 // construct a conditional to use the original value if the top 11
6851 // bits are all sign-bit copies, and use the rounded value computed
6853 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6854 SINT, DAG.getConstant(53, dl, MVT::i32));
6855 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6856 Cond, DAG.getConstant(1, dl, MVT::i64));
6857 Cond = DAG.getSetCC(dl, MVT::i32,
6858 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6860 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6866 MachineFunction &MF = DAG.getMachineFunction();
6867 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6868 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6869 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6870 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6871 } else if (Subtarget.hasLFIWAX() &&
6872 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6873 MachineMemOperand *MMO =
6874 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6875 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6876 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6877 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6878 DAG.getVTList(MVT::f64, MVT::Other),
6879 Ops, MVT::i32, MMO);
6880 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6881 } else if (Subtarget.hasFPCVT() &&
6882 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6883 MachineMemOperand *MMO =
6884 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6885 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6886 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6887 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6888 DAG.getVTList(MVT::f64, MVT::Other),
6889 Ops, MVT::i32, MMO);
6890 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6891 } else if (((Subtarget.hasLFIWAX() &&
6892 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6893 (Subtarget.hasFPCVT() &&
6894 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6895 SINT.getOperand(0).getValueType() == MVT::i32) {
6896 MachineFrameInfo &MFI = MF.getFrameInfo();
6897 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6899 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6900 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6903 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6904 MachinePointerInfo::getFixedStack(
6905 DAG.getMachineFunction(), FrameIdx));
6907 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6908 "Expected an i32 store");
6913 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6916 MachineMemOperand *MMO =
6917 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6918 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6919 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6920 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6921 PPCISD::LFIWZX : PPCISD::LFIWAX,
6922 dl, DAG.getVTList(MVT::f64, MVT::Other),
6923 Ops, MVT::i32, MMO);
6925 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6927 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6929 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6930 FP = DAG.getNode(ISD::FP_ROUND, dl,
6931 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6935 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6936 "Unhandled INT_TO_FP type in custom expander!");
6937 // Since we only generate this in 64-bit mode, we can take advantage of
6938 // 64-bit registers. In particular, sign extend the input value into the
6939 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6940 // then lfd it and fcfid it.
6941 MachineFunction &MF = DAG.getMachineFunction();
6942 MachineFrameInfo &MFI = MF.getFrameInfo();
6943 EVT PtrVT = getPointerTy(MF.getDataLayout());
6946 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6949 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6951 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6952 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6955 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6956 MachinePointerInfo::getFixedStack(
6957 DAG.getMachineFunction(), FrameIdx));
6959 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6960 "Expected an i32 store");
6965 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6969 MachineMemOperand *MMO =
6970 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6971 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6972 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6973 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6974 PPCISD::LFIWZX : PPCISD::LFIWAX,
6975 dl, DAG.getVTList(MVT::f64, MVT::Other),
6976 Ops, MVT::i32, MMO);
6978 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6980 assert(Subtarget.isPPC64() &&
6981 "i32->FP without LFIWAX supported only on PPC64");
6983 int FrameIdx = MFI.CreateStackObject(8, 8, false);
6984 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6986 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6989 // STD the extended value into the stack slot.
6990 SDValue Store = DAG.getStore(
6991 DAG.getEntryNode(), dl, Ext64, FIdx,
6992 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6994 // Load the value as a double.
6996 MVT::f64, dl, Store, FIdx,
6997 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7000 // FCFID it and return it.
7001 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7002 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7003 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7004 DAG.getIntPtrConstant(0, dl));
7008 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7009 SelectionDAG &DAG) const {
7012 The rounding mode is in bits 30:31 of FPSR, and has the following
7019 FLT_ROUNDS, on the other hand, expects the following:
7026 To perform the conversion, we do:
7027 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7030 MachineFunction &MF = DAG.getMachineFunction();
7031 EVT VT = Op.getValueType();
7032 EVT PtrVT = getPointerTy(MF.getDataLayout());
7034 // Save FP Control Word to register
7036 MVT::f64, // return register
7037 MVT::Glue // unused in this context
7039 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7041 // Save FP register to stack slot
7042 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7043 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7044 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7045 MachinePointerInfo());
7047 // Load FP Control Word from low 32 bits of stack slot.
7048 SDValue Four = DAG.getConstant(4, dl, PtrVT);
7049 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7050 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7052 // Transform as necessary
7054 DAG.getNode(ISD::AND, dl, MVT::i32,
7055 CWD, DAG.getConstant(3, dl, MVT::i32));
7057 DAG.getNode(ISD::SRL, dl, MVT::i32,
7058 DAG.getNode(ISD::AND, dl, MVT::i32,
7059 DAG.getNode(ISD::XOR, dl, MVT::i32,
7060 CWD, DAG.getConstant(3, dl, MVT::i32)),
7061 DAG.getConstant(3, dl, MVT::i32)),
7062 DAG.getConstant(1, dl, MVT::i32));
7065 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7067 return DAG.getNode((VT.getSizeInBits() < 16 ?
7068 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7071 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7072 EVT VT = Op.getValueType();
7073 unsigned BitWidth = VT.getSizeInBits();
7075 assert(Op.getNumOperands() == 3 &&
7076 VT == Op.getOperand(1).getValueType() &&
7079 // Expand into a bunch of logical ops. Note that these ops
7080 // depend on the PPC behavior for oversized shift amounts.
7081 SDValue Lo = Op.getOperand(0);
7082 SDValue Hi = Op.getOperand(1);
7083 SDValue Amt = Op.getOperand(2);
7084 EVT AmtVT = Amt.getValueType();
7086 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7087 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7088 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7089 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7090 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7091 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7092 DAG.getConstant(-BitWidth, dl, AmtVT));
7093 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7094 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7095 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7096 SDValue OutOps[] = { OutLo, OutHi };
7097 return DAG.getMergeValues(OutOps, dl);
7100 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7101 EVT VT = Op.getValueType();
7103 unsigned BitWidth = VT.getSizeInBits();
7104 assert(Op.getNumOperands() == 3 &&
7105 VT == Op.getOperand(1).getValueType() &&
7108 // Expand into a bunch of logical ops. Note that these ops
7109 // depend on the PPC behavior for oversized shift amounts.
7110 SDValue Lo = Op.getOperand(0);
7111 SDValue Hi = Op.getOperand(1);
7112 SDValue Amt = Op.getOperand(2);
7113 EVT AmtVT = Amt.getValueType();
7115 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7116 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7117 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7118 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7119 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7120 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7121 DAG.getConstant(-BitWidth, dl, AmtVT));
7122 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7123 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7124 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7125 SDValue OutOps[] = { OutLo, OutHi };
7126 return DAG.getMergeValues(OutOps, dl);
7129 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7131 EVT VT = Op.getValueType();
7132 unsigned BitWidth = VT.getSizeInBits();
7133 assert(Op.getNumOperands() == 3 &&
7134 VT == Op.getOperand(1).getValueType() &&
7137 // Expand into a bunch of logical ops, followed by a select_cc.
7138 SDValue Lo = Op.getOperand(0);
7139 SDValue Hi = Op.getOperand(1);
7140 SDValue Amt = Op.getOperand(2);
7141 EVT AmtVT = Amt.getValueType();
7143 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7144 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7145 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7146 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7147 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7148 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7149 DAG.getConstant(-BitWidth, dl, AmtVT));
7150 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7151 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7152 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7153 Tmp4, Tmp6, ISD::SETLE);
7154 SDValue OutOps[] = { OutLo, OutHi };
7155 return DAG.getMergeValues(OutOps, dl);
7158 //===----------------------------------------------------------------------===//
7159 // Vector related lowering.
7162 /// BuildSplatI - Build a canonical splati of Val with an element size of
7163 /// SplatSize. Cast the result to VT.
7164 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7165 SelectionDAG &DAG, const SDLoc &dl) {
7166 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7168 static const MVT VTys[] = { // canonical VT to use for each size.
7169 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7172 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7174 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7178 EVT CanonicalVT = VTys[SplatSize-1];
7180 // Build a canonical splat for this value.
7181 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7184 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7185 /// specified intrinsic ID.
7186 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7187 const SDLoc &dl, EVT DestVT = MVT::Other) {
7188 if (DestVT == MVT::Other) DestVT = Op.getValueType();
7189 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7190 DAG.getConstant(IID, dl, MVT::i32), Op);
7193 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7194 /// specified intrinsic ID.
7195 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7196 SelectionDAG &DAG, const SDLoc &dl,
7197 EVT DestVT = MVT::Other) {
7198 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7199 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7200 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7203 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7204 /// specified intrinsic ID.
7205 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7206 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7207 EVT DestVT = MVT::Other) {
7208 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7209 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7210 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7213 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7214 /// amount. The result has the specified value type.
7215 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7216 SelectionDAG &DAG, const SDLoc &dl) {
7217 // Force LHS/RHS to be the right type.
7218 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7219 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7222 for (unsigned i = 0; i != 16; ++i)
7224 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7225 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7228 /// Do we have an efficient pattern in a .td file for this node?
7230 /// \param V - pointer to the BuildVectorSDNode being matched
7231 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7233 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7234 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7235 /// the opposite is true (expansion is beneficial) are:
7236 /// - The node builds a vector out of integers that are not 32 or 64-bits
7237 /// - The node builds a vector out of constants
7238 /// - The node is a "load-and-splat"
7239 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7240 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7241 bool HasDirectMove) {
7242 EVT VecVT = V->getValueType(0);
7243 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7244 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7248 bool IsSplat = true;
7249 bool IsLoad = false;
7250 SDValue Op0 = V->getOperand(0);
7252 // This function is called in a block that confirms the node is not a constant
7253 // splat. So a constant BUILD_VECTOR here means the vector is built out of
7254 // different constants.
7255 if (V->isConstant())
7257 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7258 if (V->getOperand(i).isUndef())
7260 // We want to expand nodes that represent load-and-splat even if the
7261 // loaded value is a floating point truncation or conversion to int.
7262 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7263 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7264 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7265 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7266 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7267 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7268 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7270 // If the operands are different or the input is not a load and has more
7271 // uses than just this BV node, then it isn't a splat.
7272 if (V->getOperand(i) != Op0 ||
7273 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7276 return !(IsSplat && IsLoad);
7279 // If this is a case we can't handle, return null and let the default
7280 // expansion code take care of it. If we CAN select this case, and if it
7281 // selects to a single instruction, return Op. Otherwise, if we can codegen
7282 // this case more efficiently than a constant pool load, lower it to the
7283 // sequence of ops that should be used.
7284 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7285 SelectionDAG &DAG) const {
7287 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7288 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7290 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7291 // We first build an i32 vector, load it into a QPX register,
7292 // then convert it to a floating-point vector and compare it
7293 // to a zero vector to get the boolean result.
7294 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7295 int FrameIdx = MFI.CreateStackObject(16, 16, false);
7296 MachinePointerInfo PtrInfo =
7297 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7298 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7299 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7301 assert(BVN->getNumOperands() == 4 &&
7302 "BUILD_VECTOR for v4i1 does not have 4 operands");
7304 bool IsConst = true;
7305 for (unsigned i = 0; i < 4; ++i) {
7306 if (BVN->getOperand(i).isUndef()) continue;
7307 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7315 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7317 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7320 for (unsigned i = 0; i < 4; ++i) {
7321 if (BVN->getOperand(i).isUndef())
7322 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7323 else if (isNullConstant(BVN->getOperand(i)))
7329 Constant *CP = ConstantVector::get(CV);
7330 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7331 16 /* alignment */);
7333 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7334 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7335 return DAG.getMemIntrinsicNode(
7336 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7337 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7340 SmallVector<SDValue, 4> Stores;
7341 for (unsigned i = 0; i < 4; ++i) {
7342 if (BVN->getOperand(i).isUndef()) continue;
7344 unsigned Offset = 4*i;
7345 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7346 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7348 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7349 if (StoreSize > 4) {
7351 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7352 PtrInfo.getWithOffset(Offset), MVT::i32));
7354 SDValue StoreValue = BVN->getOperand(i);
7356 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7358 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7359 PtrInfo.getWithOffset(Offset)));
7364 if (!Stores.empty())
7365 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7367 StoreChain = DAG.getEntryNode();
7369 // Now load from v4i32 into the QPX register; this will extend it to
7370 // v4i64 but not yet convert it to a floating point. Nevertheless, this
7371 // is typed as v4f64 because the QPX register integer states are not
7372 // explicitly represented.
7374 SDValue Ops[] = {StoreChain,
7375 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7377 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7379 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7380 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7381 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7382 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7385 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7387 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7390 // All other QPX vectors are handled by generic code.
7391 if (Subtarget.hasQPX())
7394 // Check if this is a splat of a constant value.
7395 APInt APSplatBits, APSplatUndef;
7396 unsigned SplatBitSize;
7398 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7399 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7400 SplatBitSize > 32) {
7401 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7402 // lowered to VSX instructions under certain conditions.
7403 // Without VSX, there is no pattern more efficient than expanding the node.
7404 if (Subtarget.hasVSX() &&
7405 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7410 unsigned SplatBits = APSplatBits.getZExtValue();
7411 unsigned SplatUndef = APSplatUndef.getZExtValue();
7412 unsigned SplatSize = SplatBitSize / 8;
7414 // First, handle single instruction cases.
7417 if (SplatBits == 0) {
7418 // Canonicalize all zero vectors to be v4i32.
7419 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7420 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7421 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7426 // We have XXSPLTIB for constant splats one byte wide
7427 if (Subtarget.hasP9Vector() && SplatSize == 1) {
7428 // This is a splat of 1-byte elements with some elements potentially undef.
7429 // Rather than trying to match undef in the SDAG patterns, ensure that all
7430 // elements are the same constant.
7431 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7432 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7434 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7435 if (Op.getValueType() != MVT::v16i8)
7436 return DAG.getBitcast(Op.getValueType(), NewBV);
7442 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7443 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7445 if (SextVal >= -16 && SextVal <= 15)
7446 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7448 // Two instruction sequences.
7450 // If this value is in the range [-32,30] and is even, use:
7451 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7452 // If this value is in the range [17,31] and is odd, use:
7453 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7454 // If this value is in the range [-31,-17] and is odd, use:
7455 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7456 // Note the last two are three-instruction sequences.
7457 if (SextVal >= -32 && SextVal <= 31) {
7458 // To avoid having these optimizations undone by constant folding,
7459 // we convert to a pseudo that will be expanded later into one of
7461 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7462 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7463 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7464 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7465 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7466 if (VT == Op.getValueType())
7469 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7472 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
7473 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
7475 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7476 // Make -1 and vspltisw -1:
7477 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7479 // Make the VSLW intrinsic, computing 0x8000_0000.
7480 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7483 // xor by OnesV to invert it.
7484 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7485 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7488 // Check to see if this is a wide variety of vsplti*, binop self cases.
7489 static const signed char SplatCsts[] = {
7490 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7491 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7494 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7495 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7496 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
7497 int i = SplatCsts[idx];
7499 // Figure out what shift amount will be used by altivec if shifted by i in
7501 unsigned TypeShiftAmt = i & (SplatBitSize-1);
7503 // vsplti + shl self.
7504 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7505 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7506 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7507 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7508 Intrinsic::ppc_altivec_vslw
7510 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7511 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7514 // vsplti + srl self.
7515 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7516 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7517 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7518 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7519 Intrinsic::ppc_altivec_vsrw
7521 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7522 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7525 // vsplti + sra self.
7526 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7527 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7528 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7529 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7530 Intrinsic::ppc_altivec_vsraw
7532 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7533 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7536 // vsplti + rol self.
7537 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7538 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7539 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7540 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7541 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7542 Intrinsic::ppc_altivec_vrlw
7544 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7545 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7548 // t = vsplti c, result = vsldoi t, t, 1
7549 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7550 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7551 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7552 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7554 // t = vsplti c, result = vsldoi t, t, 2
7555 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7556 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7557 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7558 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7560 // t = vsplti c, result = vsldoi t, t, 3
7561 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7562 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7563 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7564 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7571 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7572 /// the specified operations to build the shuffle.
7573 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7574 SDValue RHS, SelectionDAG &DAG,
7576 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7577 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7578 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7581 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7593 if (OpNum == OP_COPY) {
7594 if (LHSID == (1*9+2)*9+3) return LHS;
7595 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7599 SDValue OpLHS, OpRHS;
7600 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7601 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7605 default: llvm_unreachable("Unknown i32 permute!");
7607 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
7608 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7609 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
7610 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7613 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7614 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7615 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7616 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7619 for (unsigned i = 0; i != 16; ++i)
7620 ShufIdxs[i] = (i&3)+0;
7623 for (unsigned i = 0; i != 16; ++i)
7624 ShufIdxs[i] = (i&3)+4;
7627 for (unsigned i = 0; i != 16; ++i)
7628 ShufIdxs[i] = (i&3)+8;
7631 for (unsigned i = 0; i != 16; ++i)
7632 ShufIdxs[i] = (i&3)+12;
7635 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7637 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7639 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7641 EVT VT = OpLHS.getValueType();
7642 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7643 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7644 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7645 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7648 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
7649 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
7650 /// return the code it can be lowered into. Worst case, it can always be
7651 /// lowered into a vperm.
7652 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7653 SelectionDAG &DAG) const {
7655 SDValue V1 = Op.getOperand(0);
7656 SDValue V2 = Op.getOperand(1);
7657 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7658 EVT VT = Op.getValueType();
7659 bool isLittleEndian = Subtarget.isLittleEndian();
7661 unsigned ShiftElts, InsertAtByte;
7663 if (Subtarget.hasP9Vector() &&
7664 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7668 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7669 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7671 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7672 DAG.getConstant(ShiftElts, dl, MVT::i32));
7673 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7674 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7675 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7677 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7678 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7679 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7682 if (Subtarget.hasVSX()) {
7683 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7684 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7686 // If the source for the shuffle is a scalar_to_vector that came from a
7687 // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7688 if (Subtarget.hasP9Vector() &&
7689 ((isLittleEndian && SplatIdx == 3) ||
7690 (!isLittleEndian && SplatIdx == 0))) {
7691 SDValue Src = V1.getOperand(0);
7692 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7693 Src.getOperand(0).getOpcode() == ISD::LOAD &&
7694 Src.getOperand(0).hasOneUse())
7697 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7698 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7699 DAG.getConstant(SplatIdx, dl, MVT::i32));
7700 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7703 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7704 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7705 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7706 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7707 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7711 if (Subtarget.hasQPX()) {
7712 if (VT.getVectorNumElements() != 4)
7715 if (V2.isUndef()) V2 = V1;
7717 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7718 if (AlignIdx != -1) {
7719 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7720 DAG.getConstant(AlignIdx, dl, MVT::i32));
7721 } else if (SVOp->isSplat()) {
7722 int SplatIdx = SVOp->getSplatIndex();
7723 if (SplatIdx >= 4) {
7728 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7729 DAG.getConstant(SplatIdx, dl, MVT::i32));
7732 // Lower this into a qvgpci/qvfperm pair.
7734 // Compute the qvgpci literal
7736 for (unsigned i = 0; i < 4; ++i) {
7737 int m = SVOp->getMaskElt(i);
7738 unsigned mm = m >= 0 ? (unsigned) m : i;
7739 idx |= mm << (3-i)*3;
7742 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7743 DAG.getConstant(idx, dl, MVT::i32));
7744 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7747 // Cases that are handled by instructions that take permute immediates
7748 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7749 // selected by the instruction selector.
7751 if (PPC::isSplatShuffleMask(SVOp, 1) ||
7752 PPC::isSplatShuffleMask(SVOp, 2) ||
7753 PPC::isSplatShuffleMask(SVOp, 4) ||
7754 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7755 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7756 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7757 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7758 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7759 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7760 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7761 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7762 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7763 (Subtarget.hasP8Altivec() && (
7764 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7765 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7766 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7771 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7772 // and produce a fixed permutation. If any of these match, do not lower to
7774 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7775 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7776 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7777 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7778 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7779 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7780 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7781 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7782 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7783 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7784 (Subtarget.hasP8Altivec() && (
7785 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7786 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7787 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7790 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7791 // perfect shuffle table to emit an optimal matching sequence.
7792 ArrayRef<int> PermMask = SVOp->getMask();
7794 unsigned PFIndexes[4];
7795 bool isFourElementShuffle = true;
7796 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7797 unsigned EltNo = 8; // Start out undef.
7798 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7799 if (PermMask[i*4+j] < 0)
7800 continue; // Undef, ignore it.
7802 unsigned ByteSource = PermMask[i*4+j];
7803 if ((ByteSource & 3) != j) {
7804 isFourElementShuffle = false;
7809 EltNo = ByteSource/4;
7810 } else if (EltNo != ByteSource/4) {
7811 isFourElementShuffle = false;
7815 PFIndexes[i] = EltNo;
7818 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7819 // perfect shuffle vector to determine if it is cost effective to do this as
7820 // discrete instructions, or whether we should use a vperm.
7821 // For now, we skip this for little endian until such time as we have a
7822 // little-endian perfect shuffle table.
7823 if (isFourElementShuffle && !isLittleEndian) {
7824 // Compute the index in the perfect shuffle table.
7825 unsigned PFTableIndex =
7826 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7828 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7829 unsigned Cost = (PFEntry >> 30);
7831 // Determining when to avoid vperm is tricky. Many things affect the cost
7832 // of vperm, particularly how many times the perm mask needs to be computed.
7833 // For example, if the perm mask can be hoisted out of a loop or is already
7834 // used (perhaps because there are multiple permutes with the same shuffle
7835 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7836 // the loop requires an extra register.
7838 // As a compromise, we only emit discrete instructions if the shuffle can be
7839 // generated in 3 or fewer operations. When we have loop information
7840 // available, if this block is within a loop, we should avoid using vperm
7841 // for 3-operation perms and use a constant pool load instead.
7843 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7846 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7847 // vector that will get spilled to the constant pool.
7848 if (V2.isUndef()) V2 = V1;
7850 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7851 // that it is in input element units, not in bytes. Convert now.
7853 // For little endian, the order of the input vectors is reversed, and
7854 // the permutation mask is complemented with respect to 31. This is
7855 // necessary to produce proper semantics with the big-endian-biased vperm
7857 EVT EltVT = V1.getValueType().getVectorElementType();
7858 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7860 SmallVector<SDValue, 16> ResultMask;
7861 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7862 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7864 for (unsigned j = 0; j != BytesPerElement; ++j)
7866 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7869 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7873 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7875 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7878 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7882 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7883 /// vector comparison. If it is, return true and fill in Opc/isDot with
7884 /// information about the intrinsic.
7885 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7886 bool &isDot, const PPCSubtarget &Subtarget) {
7887 unsigned IntrinsicID =
7888 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7891 switch (IntrinsicID) {
7894 // Comparison predicates.
7895 case Intrinsic::ppc_altivec_vcmpbfp_p:
7899 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7903 case Intrinsic::ppc_altivec_vcmpequb_p:
7907 case Intrinsic::ppc_altivec_vcmpequh_p:
7911 case Intrinsic::ppc_altivec_vcmpequw_p:
7915 case Intrinsic::ppc_altivec_vcmpequd_p:
7916 if (Subtarget.hasP8Altivec()) {
7922 case Intrinsic::ppc_altivec_vcmpneb_p:
7923 case Intrinsic::ppc_altivec_vcmpneh_p:
7924 case Intrinsic::ppc_altivec_vcmpnew_p:
7925 case Intrinsic::ppc_altivec_vcmpnezb_p:
7926 case Intrinsic::ppc_altivec_vcmpnezh_p:
7927 case Intrinsic::ppc_altivec_vcmpnezw_p:
7928 if (Subtarget.hasP9Altivec()) {
7929 switch (IntrinsicID) {
7931 llvm_unreachable("Unknown comparison intrinsic.");
7932 case Intrinsic::ppc_altivec_vcmpneb_p:
7935 case Intrinsic::ppc_altivec_vcmpneh_p:
7938 case Intrinsic::ppc_altivec_vcmpnew_p:
7941 case Intrinsic::ppc_altivec_vcmpnezb_p:
7944 case Intrinsic::ppc_altivec_vcmpnezh_p:
7947 case Intrinsic::ppc_altivec_vcmpnezw_p:
7955 case Intrinsic::ppc_altivec_vcmpgefp_p:
7959 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7963 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7967 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7971 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7975 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7976 if (Subtarget.hasP8Altivec()) {
7982 case Intrinsic::ppc_altivec_vcmpgtub_p:
7986 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7990 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7994 case Intrinsic::ppc_altivec_vcmpgtud_p:
7995 if (Subtarget.hasP8Altivec()) {
8002 // VSX predicate comparisons use the same infrastructure
8003 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8004 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8005 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8006 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8007 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8008 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8009 if (Subtarget.hasVSX()) {
8010 switch (IntrinsicID) {
8011 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8014 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8017 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8020 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8023 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8026 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8035 // Normal Comparisons.
8036 case Intrinsic::ppc_altivec_vcmpbfp:
8039 case Intrinsic::ppc_altivec_vcmpeqfp:
8042 case Intrinsic::ppc_altivec_vcmpequb:
8045 case Intrinsic::ppc_altivec_vcmpequh:
8048 case Intrinsic::ppc_altivec_vcmpequw:
8051 case Intrinsic::ppc_altivec_vcmpequd:
8052 if (Subtarget.hasP8Altivec())
8057 case Intrinsic::ppc_altivec_vcmpneb:
8058 case Intrinsic::ppc_altivec_vcmpneh:
8059 case Intrinsic::ppc_altivec_vcmpnew:
8060 case Intrinsic::ppc_altivec_vcmpnezb:
8061 case Intrinsic::ppc_altivec_vcmpnezh:
8062 case Intrinsic::ppc_altivec_vcmpnezw:
8063 if (Subtarget.hasP9Altivec())
8064 switch (IntrinsicID) {
8066 llvm_unreachable("Unknown comparison intrinsic.");
8067 case Intrinsic::ppc_altivec_vcmpneb:
8070 case Intrinsic::ppc_altivec_vcmpneh:
8073 case Intrinsic::ppc_altivec_vcmpnew:
8076 case Intrinsic::ppc_altivec_vcmpnezb:
8079 case Intrinsic::ppc_altivec_vcmpnezh:
8082 case Intrinsic::ppc_altivec_vcmpnezw:
8089 case Intrinsic::ppc_altivec_vcmpgefp:
8092 case Intrinsic::ppc_altivec_vcmpgtfp:
8095 case Intrinsic::ppc_altivec_vcmpgtsb:
8098 case Intrinsic::ppc_altivec_vcmpgtsh:
8101 case Intrinsic::ppc_altivec_vcmpgtsw:
8104 case Intrinsic::ppc_altivec_vcmpgtsd:
8105 if (Subtarget.hasP8Altivec())
8110 case Intrinsic::ppc_altivec_vcmpgtub:
8113 case Intrinsic::ppc_altivec_vcmpgtuh:
8116 case Intrinsic::ppc_altivec_vcmpgtuw:
8119 case Intrinsic::ppc_altivec_vcmpgtud:
8120 if (Subtarget.hasP8Altivec())
8129 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8130 /// lower, do it, otherwise return null.
8131 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8132 SelectionDAG &DAG) const {
8133 unsigned IntrinsicID =
8134 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8136 if (IntrinsicID == Intrinsic::thread_pointer) {
8137 // Reads the thread pointer register, used for __builtin_thread_pointer.
8138 bool is64bit = Subtarget.isPPC64();
8139 return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8140 is64bit ? MVT::i64 : MVT::i32);
8143 // If this is a lowered altivec predicate compare, CompareOpc is set to the
8144 // opcode number of the comparison.
8148 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8149 return SDValue(); // Don't custom lower most intrinsics.
8151 // If this is a non-dot comparison, make the VCMP node and we are done.
8153 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8154 Op.getOperand(1), Op.getOperand(2),
8155 DAG.getConstant(CompareOpc, dl, MVT::i32));
8156 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8159 // Create the PPCISD altivec 'dot' comparison node.
8161 Op.getOperand(2), // LHS
8162 Op.getOperand(3), // RHS
8163 DAG.getConstant(CompareOpc, dl, MVT::i32)
8165 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8166 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8168 // Now that we have the comparison, emit a copy from the CR to a GPR.
8169 // This is flagged to the above dot comparison.
8170 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8171 DAG.getRegister(PPC::CR6, MVT::i32),
8172 CompNode.getValue(1));
8174 // Unpack the result based on how the target uses it.
8175 unsigned BitNo; // Bit # of CR6.
8176 bool InvertBit; // Invert result?
8177 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8178 default: // Can't happen, don't crash on invalid number though.
8179 case 0: // Return the value of the EQ bit of CR6.
8180 BitNo = 0; InvertBit = false;
8182 case 1: // Return the inverted value of the EQ bit of CR6.
8183 BitNo = 0; InvertBit = true;
8185 case 2: // Return the value of the LT bit of CR6.
8186 BitNo = 2; InvertBit = false;
8188 case 3: // Return the inverted value of the LT bit of CR6.
8189 BitNo = 2; InvertBit = true;
8193 // Shift the bit into the low position.
8194 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8195 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8197 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8198 DAG.getConstant(1, dl, MVT::i32));
8200 // If we are supposed to, toggle the bit.
8202 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8203 DAG.getConstant(1, dl, MVT::i32));
8207 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8208 SelectionDAG &DAG) const {
8209 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8210 // the beginning of the argument list.
8211 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8213 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8214 case Intrinsic::ppc_cfence: {
8215 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8216 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8217 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8218 Op.getOperand(ArgStart + 1))),
8227 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8228 SelectionDAG &DAG) const {
8230 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8231 // instructions), but for smaller types, we need to first extend up to v2i32
8232 // before doing going farther.
8233 if (Op.getValueType() == MVT::v2i64) {
8234 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8235 if (ExtVT != MVT::v2i32) {
8236 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8237 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8238 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8239 ExtVT.getVectorElementType(), 4)));
8240 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8241 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8242 DAG.getValueType(MVT::v2i32));
8251 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8252 SelectionDAG &DAG) const {
8254 // Create a stack slot that is 16-byte aligned.
8255 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8256 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8257 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8258 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8260 // Store the input value into Value#0 of the stack slot.
8261 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8262 MachinePointerInfo());
8264 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8267 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8268 SelectionDAG &DAG) const {
8269 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8270 "Should only be called for ISD::INSERT_VECTOR_ELT");
8271 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8272 // We have legal lowering for constant indices but not for variable ones.
8278 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8279 SelectionDAG &DAG) const {
8281 SDNode *N = Op.getNode();
8283 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8284 "Unknown extract_vector_elt type");
8286 SDValue Value = N->getOperand(0);
8288 // The first part of this is like the store lowering except that we don't
8289 // need to track the chain.
8291 // The values are now known to be -1 (false) or 1 (true). To convert this
8292 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8293 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8294 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8296 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8297 // understand how to form the extending load.
8298 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8300 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8302 // Now convert to an integer and store.
8303 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8304 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8307 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8308 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8309 MachinePointerInfo PtrInfo =
8310 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8311 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8312 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8314 SDValue StoreChain = DAG.getEntryNode();
8315 SDValue Ops[] = {StoreChain,
8316 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8318 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8320 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8321 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8323 // Extract the value requested.
8324 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8325 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8326 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8329 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8331 if (!Subtarget.useCRBits())
8334 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8337 /// Lowering for QPX v4i1 loads
8338 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8339 SelectionDAG &DAG) const {
8341 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8342 SDValue LoadChain = LN->getChain();
8343 SDValue BasePtr = LN->getBasePtr();
8345 if (Op.getValueType() == MVT::v4f64 ||
8346 Op.getValueType() == MVT::v4f32) {
8347 EVT MemVT = LN->getMemoryVT();
8348 unsigned Alignment = LN->getAlignment();
8350 // If this load is properly aligned, then it is legal.
8351 if (Alignment >= MemVT.getStoreSize())
8354 EVT ScalarVT = Op.getValueType().getScalarType(),
8355 ScalarMemVT = MemVT.getScalarType();
8356 unsigned Stride = ScalarMemVT.getStoreSize();
8358 SDValue Vals[4], LoadChains[4];
8359 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8361 if (ScalarVT != ScalarMemVT)
8362 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8364 LN->getPointerInfo().getWithOffset(Idx * Stride),
8365 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8366 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8368 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8369 LN->getPointerInfo().getWithOffset(Idx * Stride),
8370 MinAlign(Alignment, Idx * Stride),
8371 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8373 if (Idx == 0 && LN->isIndexed()) {
8374 assert(LN->getAddressingMode() == ISD::PRE_INC &&
8375 "Unknown addressing mode on vector load");
8376 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8377 LN->getAddressingMode());
8381 LoadChains[Idx] = Load.getValue(1);
8383 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8384 DAG.getConstant(Stride, dl,
8385 BasePtr.getValueType()));
8388 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8389 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8391 if (LN->isIndexed()) {
8392 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8393 return DAG.getMergeValues(RetOps, dl);
8396 SDValue RetOps[] = { Value, TF };
8397 return DAG.getMergeValues(RetOps, dl);
8400 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8401 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8403 // To lower v4i1 from a byte array, we load the byte elements of the
8404 // vector and then reuse the BUILD_VECTOR logic.
8406 SDValue VectElmts[4], VectElmtChains[4];
8407 for (unsigned i = 0; i < 4; ++i) {
8408 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8409 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8411 VectElmts[i] = DAG.getExtLoad(
8412 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8413 LN->getPointerInfo().getWithOffset(i), MVT::i8,
8414 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8415 VectElmtChains[i] = VectElmts[i].getValue(1);
8418 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8419 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8421 SDValue RVals[] = { Value, LoadChain };
8422 return DAG.getMergeValues(RVals, dl);
8425 /// Lowering for QPX v4i1 stores
8426 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8427 SelectionDAG &DAG) const {
8429 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8430 SDValue StoreChain = SN->getChain();
8431 SDValue BasePtr = SN->getBasePtr();
8432 SDValue Value = SN->getValue();
8434 if (Value.getValueType() == MVT::v4f64 ||
8435 Value.getValueType() == MVT::v4f32) {
8436 EVT MemVT = SN->getMemoryVT();
8437 unsigned Alignment = SN->getAlignment();
8439 // If this store is properly aligned, then it is legal.
8440 if (Alignment >= MemVT.getStoreSize())
8443 EVT ScalarVT = Value.getValueType().getScalarType(),
8444 ScalarMemVT = MemVT.getScalarType();
8445 unsigned Stride = ScalarMemVT.getStoreSize();
8448 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8449 SDValue Ex = DAG.getNode(
8450 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8451 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8453 if (ScalarVT != ScalarMemVT)
8455 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8456 SN->getPointerInfo().getWithOffset(Idx * Stride),
8457 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8458 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8460 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8461 SN->getPointerInfo().getWithOffset(Idx * Stride),
8462 MinAlign(Alignment, Idx * Stride),
8463 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8465 if (Idx == 0 && SN->isIndexed()) {
8466 assert(SN->getAddressingMode() == ISD::PRE_INC &&
8467 "Unknown addressing mode on vector store");
8468 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8469 SN->getAddressingMode());
8472 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8473 DAG.getConstant(Stride, dl,
8474 BasePtr.getValueType()));
8475 Stores[Idx] = Store;
8478 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8480 if (SN->isIndexed()) {
8481 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8482 return DAG.getMergeValues(RetOps, dl);
8488 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8489 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8491 // The values are now known to be -1 (false) or 1 (true). To convert this
8492 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8493 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8494 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8496 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8497 // understand how to form the extending load.
8498 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8500 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8502 // Now convert to an integer and store.
8503 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8504 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8507 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8508 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8509 MachinePointerInfo PtrInfo =
8510 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8511 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8512 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8514 SDValue Ops[] = {StoreChain,
8515 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8517 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8519 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8520 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8522 // Move data into the byte array.
8523 SDValue Loads[4], LoadChains[4];
8524 for (unsigned i = 0; i < 4; ++i) {
8525 unsigned Offset = 4*i;
8526 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8527 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8529 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8530 PtrInfo.getWithOffset(Offset));
8531 LoadChains[i] = Loads[i].getValue(1);
8534 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8537 for (unsigned i = 0; i < 4; ++i) {
8538 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8539 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8541 Stores[i] = DAG.getTruncStore(
8542 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8543 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8547 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8552 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8554 if (Op.getValueType() == MVT::v4i32) {
8555 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8557 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
8558 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8560 SDValue RHSSwap = // = vrlw RHS, 16
8561 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8563 // Shrinkify inputs to v8i16.
8564 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8565 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8566 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8568 // Low parts multiplied together, generating 32-bit results (we ignore the
8570 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8571 LHS, RHS, DAG, dl, MVT::v4i32);
8573 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8574 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8575 // Shift the high parts up 16 bits.
8576 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8578 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8579 } else if (Op.getValueType() == MVT::v8i16) {
8580 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8582 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8584 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8585 LHS, RHS, Zero, DAG, dl);
8586 } else if (Op.getValueType() == MVT::v16i8) {
8587 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8588 bool isLittleEndian = Subtarget.isLittleEndian();
8590 // Multiply the even 8-bit parts, producing 16-bit sums.
8591 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8592 LHS, RHS, DAG, dl, MVT::v8i16);
8593 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8595 // Multiply the odd 8-bit parts, producing 16-bit sums.
8596 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8597 LHS, RHS, DAG, dl, MVT::v8i16);
8598 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8600 // Merge the results together. Because vmuleub and vmuloub are
8601 // instructions with a big-endian bias, we must reverse the
8602 // element numbering and reverse the meaning of "odd" and "even"
8603 // when generating little endian code.
8605 for (unsigned i = 0; i != 8; ++i) {
8606 if (isLittleEndian) {
8608 Ops[i*2+1] = 2*i+16;
8611 Ops[i*2+1] = 2*i+1+16;
8615 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8617 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8619 llvm_unreachable("Unknown mul to lower!");
8623 /// LowerOperation - Provide custom lowering hooks for some operations.
8625 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8626 switch (Op.getOpcode()) {
8627 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8628 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8629 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8630 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8631 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8632 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8633 case ISD::SETCC: return LowerSETCC(Op, DAG);
8634 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
8635 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
8637 return LowerVASTART(Op, DAG);
8640 return LowerVAARG(Op, DAG);
8643 return LowerVACOPY(Op, DAG);
8645 case ISD::STACKRESTORE:
8646 return LowerSTACKRESTORE(Op, DAG);
8648 case ISD::DYNAMIC_STACKALLOC:
8649 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8651 case ISD::GET_DYNAMIC_AREA_OFFSET:
8652 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8654 case ISD::EH_DWARF_CFA:
8655 return LowerEH_DWARF_CFA(Op, DAG);
8657 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
8658 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
8660 case ISD::LOAD: return LowerLOAD(Op, DAG);
8661 case ISD::STORE: return LowerSTORE(Op, DAG);
8662 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
8663 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8664 case ISD::FP_TO_UINT:
8665 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
8667 case ISD::UINT_TO_FP:
8668 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8669 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8671 // Lower 64-bit shifts.
8672 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
8673 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
8674 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
8676 // Vector-related lowering.
8677 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8678 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8679 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8680 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8681 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
8682 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8683 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8684 case ISD::MUL: return LowerMUL(Op, DAG);
8686 // For counter-based loop handling.
8687 case ISD::INTRINSIC_W_CHAIN: return SDValue();
8689 // Frame & Return address.
8690 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8691 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8693 case ISD::INTRINSIC_VOID:
8694 return LowerINTRINSIC_VOID(Op, DAG);
8698 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8699 SmallVectorImpl<SDValue>&Results,
8700 SelectionDAG &DAG) const {
8702 switch (N->getOpcode()) {
8704 llvm_unreachable("Do not know how to custom type legalize this operation!");
8705 case ISD::READCYCLECOUNTER: {
8706 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8707 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8709 Results.push_back(RTB);
8710 Results.push_back(RTB.getValue(1));
8711 Results.push_back(RTB.getValue(2));
8714 case ISD::INTRINSIC_W_CHAIN: {
8715 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8716 Intrinsic::ppc_is_decremented_ctr_nonzero)
8719 assert(N->getValueType(0) == MVT::i1 &&
8720 "Unexpected result type for CTR decrement intrinsic");
8721 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8722 N->getValueType(0));
8723 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8724 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8727 Results.push_back(NewInt);
8728 Results.push_back(NewInt.getValue(1));
8732 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8735 EVT VT = N->getValueType(0);
8737 if (VT == MVT::i64) {
8738 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8740 Results.push_back(NewNode);
8741 Results.push_back(NewNode.getValue(1));
8745 case ISD::FP_ROUND_INREG: {
8746 assert(N->getValueType(0) == MVT::ppcf128);
8747 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8748 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8749 MVT::f64, N->getOperand(0),
8750 DAG.getIntPtrConstant(0, dl));
8751 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8752 MVT::f64, N->getOperand(0),
8753 DAG.getIntPtrConstant(1, dl));
8755 // Add the two halves of the long double in round-to-zero mode.
8756 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8758 // We know the low half is about to be thrown away, so just use something
8760 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8764 case ISD::FP_TO_SINT:
8765 case ISD::FP_TO_UINT:
8766 // LowerFP_TO_INT() can only handle f32 and f64.
8767 if (N->getOperand(0).getValueType() == MVT::ppcf128)
8769 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8774 //===----------------------------------------------------------------------===//
8775 // Other Lowering Code
8776 //===----------------------------------------------------------------------===//
8778 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8779 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8780 Function *Func = Intrinsic::getDeclaration(M, Id);
8781 return Builder.CreateCall(Func, {});
8784 // The mappings for emitLeading/TrailingFence is taken from
8785 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8786 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8788 AtomicOrdering Ord) const {
8789 if (Ord == AtomicOrdering::SequentiallyConsistent)
8790 return callIntrinsic(Builder, Intrinsic::ppc_sync);
8791 if (isReleaseOrStronger(Ord))
8792 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8796 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8798 AtomicOrdering Ord) const {
8799 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
8800 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8801 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8802 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8803 if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
8804 return Builder.CreateCall(
8805 Intrinsic::getDeclaration(
8806 Builder.GetInsertBlock()->getParent()->getParent(),
8807 Intrinsic::ppc_cfence, {Inst->getType()}),
8809 // FIXME: Can use isync for rmw operation.
8810 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8816 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8817 unsigned AtomicSize,
8820 unsigned CmpPred) const {
8821 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8822 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8824 auto LoadMnemonic = PPC::LDARX;
8825 auto StoreMnemonic = PPC::STDCX;
8826 switch (AtomicSize) {
8828 llvm_unreachable("Unexpected size of atomic entity");
8830 LoadMnemonic = PPC::LBARX;
8831 StoreMnemonic = PPC::STBCX;
8832 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8835 LoadMnemonic = PPC::LHARX;
8836 StoreMnemonic = PPC::STHCX;
8837 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8840 LoadMnemonic = PPC::LWARX;
8841 StoreMnemonic = PPC::STWCX;
8844 LoadMnemonic = PPC::LDARX;
8845 StoreMnemonic = PPC::STDCX;
8849 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8850 MachineFunction *F = BB->getParent();
8851 MachineFunction::iterator It = ++BB->getIterator();
8853 unsigned dest = MI.getOperand(0).getReg();
8854 unsigned ptrA = MI.getOperand(1).getReg();
8855 unsigned ptrB = MI.getOperand(2).getReg();
8856 unsigned incr = MI.getOperand(3).getReg();
8857 DebugLoc dl = MI.getDebugLoc();
8859 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8860 MachineBasicBlock *loop2MBB =
8861 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8862 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8863 F->insert(It, loopMBB);
8865 F->insert(It, loop2MBB);
8866 F->insert(It, exitMBB);
8867 exitMBB->splice(exitMBB->begin(), BB,
8868 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8869 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8871 MachineRegisterInfo &RegInfo = F->getRegInfo();
8872 unsigned TmpReg = (!BinOpcode) ? incr :
8873 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8874 : &PPC::GPRCRegClass);
8878 // fallthrough --> loopMBB
8879 BB->addSuccessor(loopMBB);
8882 // l[wd]arx dest, ptr
8883 // add r0, dest, incr
8884 // st[wd]cx. r0, ptr
8886 // fallthrough --> exitMBB
8890 // l[wd]arx dest, ptr
8891 // cmpl?[wd] incr, dest
8894 // st[wd]cx. dest, ptr
8896 // fallthrough --> exitMBB
8899 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8900 .addReg(ptrA).addReg(ptrB);
8902 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8904 // Signed comparisons of byte or halfword values must be sign-extended.
8905 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8906 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8907 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8908 ExtReg).addReg(dest);
8909 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8910 .addReg(incr).addReg(ExtReg);
8912 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8913 .addReg(incr).addReg(dest);
8915 BuildMI(BB, dl, TII->get(PPC::BCC))
8916 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8917 BB->addSuccessor(loop2MBB);
8918 BB->addSuccessor(exitMBB);
8921 BuildMI(BB, dl, TII->get(StoreMnemonic))
8922 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8923 BuildMI(BB, dl, TII->get(PPC::BCC))
8924 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8925 BB->addSuccessor(loopMBB);
8926 BB->addSuccessor(exitMBB);
8935 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8936 MachineBasicBlock *BB,
8937 bool is8bit, // operation
8940 unsigned CmpPred) const {
8941 // If we support part-word atomic mnemonics, just use them
8942 if (Subtarget.hasPartwordAtomics())
8943 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8944 CmpOpcode, CmpPred);
8946 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8947 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8948 // In 64 bit mode we have to use 64 bits for addresses, even though the
8949 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
8950 // registers without caring whether they're 32 or 64, but here we're
8951 // doing actual arithmetic on the addresses.
8952 bool is64bit = Subtarget.isPPC64();
8953 bool isLittleEndian = Subtarget.isLittleEndian();
8954 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8956 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8957 MachineFunction *F = BB->getParent();
8958 MachineFunction::iterator It = ++BB->getIterator();
8960 unsigned dest = MI.getOperand(0).getReg();
8961 unsigned ptrA = MI.getOperand(1).getReg();
8962 unsigned ptrB = MI.getOperand(2).getReg();
8963 unsigned incr = MI.getOperand(3).getReg();
8964 DebugLoc dl = MI.getDebugLoc();
8966 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8967 MachineBasicBlock *loop2MBB =
8968 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8969 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8970 F->insert(It, loopMBB);
8972 F->insert(It, loop2MBB);
8973 F->insert(It, exitMBB);
8974 exitMBB->splice(exitMBB->begin(), BB,
8975 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8976 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8978 MachineRegisterInfo &RegInfo = F->getRegInfo();
8979 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8980 : &PPC::GPRCRegClass;
8981 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8982 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8984 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8985 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8986 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8987 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8988 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8989 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8990 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8991 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8992 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8994 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8998 // fallthrough --> loopMBB
8999 BB->addSuccessor(loopMBB);
9001 // The 4-byte load must be aligned, while a char or short may be
9002 // anywhere in the word. Hence all this nasty bookkeeping code.
9003 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9004 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9005 // xori shift, shift1, 24 [16]
9006 // rlwinm ptr, ptr1, 0, 0, 29
9007 // slw incr2, incr, shift
9008 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9009 // slw mask, mask2, shift
9011 // lwarx tmpDest, ptr
9012 // add tmp, tmpDest, incr2
9013 // andc tmp2, tmpDest, mask
9014 // and tmp3, tmp, mask
9015 // or tmp4, tmp3, tmp2
9018 // fallthrough --> exitMBB
9019 // srw dest, tmpDest, shift
9020 if (ptrA != ZeroReg) {
9021 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9022 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9023 .addReg(ptrA).addReg(ptrB);
9027 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9028 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9029 if (!isLittleEndian)
9030 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9031 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9033 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9034 .addReg(Ptr1Reg).addImm(0).addImm(61);
9036 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9037 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9038 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9039 .addReg(incr).addReg(ShiftReg);
9041 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9043 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9044 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9046 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9047 .addReg(Mask2Reg).addReg(ShiftReg);
9050 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9051 .addReg(ZeroReg).addReg(PtrReg);
9053 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9054 .addReg(Incr2Reg).addReg(TmpDestReg);
9055 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9056 .addReg(TmpDestReg).addReg(MaskReg);
9057 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9058 .addReg(TmpReg).addReg(MaskReg);
9060 // For unsigned comparisons, we can directly compare the shifted values.
9061 // For signed comparisons we shift and sign extend.
9062 unsigned SReg = RegInfo.createVirtualRegister(RC);
9063 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9064 .addReg(TmpDestReg).addReg(MaskReg);
9065 unsigned ValueReg = SReg;
9066 unsigned CmpReg = Incr2Reg;
9067 if (CmpOpcode == PPC::CMPW) {
9068 ValueReg = RegInfo.createVirtualRegister(RC);
9069 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9070 .addReg(SReg).addReg(ShiftReg);
9071 unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9072 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9074 ValueReg = ValueSReg;
9077 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9078 .addReg(CmpReg).addReg(ValueReg);
9079 BuildMI(BB, dl, TII->get(PPC::BCC))
9080 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9081 BB->addSuccessor(loop2MBB);
9082 BB->addSuccessor(exitMBB);
9085 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9086 .addReg(Tmp3Reg).addReg(Tmp2Reg);
9087 BuildMI(BB, dl, TII->get(PPC::STWCX))
9088 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9089 BuildMI(BB, dl, TII->get(PPC::BCC))
9090 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9091 BB->addSuccessor(loopMBB);
9092 BB->addSuccessor(exitMBB);
9097 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9102 llvm::MachineBasicBlock *
9103 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9104 MachineBasicBlock *MBB) const {
9105 DebugLoc DL = MI.getDebugLoc();
9106 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9107 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9109 MachineFunction *MF = MBB->getParent();
9110 MachineRegisterInfo &MRI = MF->getRegInfo();
9112 const BasicBlock *BB = MBB->getBasicBlock();
9113 MachineFunction::iterator I = ++MBB->getIterator();
9116 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9117 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9119 unsigned DstReg = MI.getOperand(0).getReg();
9120 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9121 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9122 unsigned mainDstReg = MRI.createVirtualRegister(RC);
9123 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9125 MVT PVT = getPointerTy(MF->getDataLayout());
9126 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9127 "Invalid Pointer Size!");
9128 // For v = setjmp(buf), we generate
9131 // SjLjSetup mainMBB
9137 // buf[LabelOffset] = LR
9141 // v = phi(main, restore)
9144 MachineBasicBlock *thisMBB = MBB;
9145 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9146 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9147 MF->insert(I, mainMBB);
9148 MF->insert(I, sinkMBB);
9150 MachineInstrBuilder MIB;
9152 // Transfer the remainder of BB and its successor edges to sinkMBB.
9153 sinkMBB->splice(sinkMBB->begin(), MBB,
9154 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9155 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9157 // Note that the structure of the jmp_buf used here is not compatible
9158 // with that used by libc, and is not designed to be. Specifically, it
9159 // stores only those 'reserved' registers that LLVM does not otherwise
9160 // understand how to spill. Also, by convention, by the time this
9161 // intrinsic is called, Clang has already stored the frame address in the
9162 // first slot of the buffer and stack address in the third. Following the
9163 // X86 target code, we'll store the jump address in the second slot. We also
9164 // need to save the TOC pointer (R2) to handle jumps between shared
9165 // libraries, and that will be stored in the fourth slot. The thread
9166 // identifier (R13) is not affected.
9169 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9170 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9171 const int64_t BPOffset = 4 * PVT.getStoreSize();
9173 // Prepare IP either in reg.
9174 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9175 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9176 unsigned BufReg = MI.getOperand(1).getReg();
9178 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9179 setUsesTOCBasePtr(*MBB->getParent());
9180 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9184 MIB.setMemRefs(MMOBegin, MMOEnd);
9187 // Naked functions never have a base pointer, and so we use r1. For all
9188 // other functions, this decision must be delayed until during PEI.
9190 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9191 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9193 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9195 MIB = BuildMI(*thisMBB, MI, DL,
9196 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9200 MIB.setMemRefs(MMOBegin, MMOEnd);
9203 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9204 MIB.addRegMask(TRI->getNoPreservedMask());
9206 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9208 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9210 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9212 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9213 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9218 BuildMI(mainMBB, DL,
9219 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9222 if (Subtarget.isPPC64()) {
9223 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9225 .addImm(LabelOffset)
9228 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9230 .addImm(LabelOffset)
9234 MIB.setMemRefs(MMOBegin, MMOEnd);
9236 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9237 mainMBB->addSuccessor(sinkMBB);
9240 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9241 TII->get(PPC::PHI), DstReg)
9242 .addReg(mainDstReg).addMBB(mainMBB)
9243 .addReg(restoreDstReg).addMBB(thisMBB);
9245 MI.eraseFromParent();
9250 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9251 MachineBasicBlock *MBB) const {
9252 DebugLoc DL = MI.getDebugLoc();
9253 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9255 MachineFunction *MF = MBB->getParent();
9256 MachineRegisterInfo &MRI = MF->getRegInfo();
9259 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9260 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9262 MVT PVT = getPointerTy(MF->getDataLayout());
9263 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9264 "Invalid Pointer Size!");
9266 const TargetRegisterClass *RC =
9267 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9268 unsigned Tmp = MRI.createVirtualRegister(RC);
9269 // Since FP is only updated here but NOT referenced, it's treated as GPR.
9270 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9271 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9275 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9278 MachineInstrBuilder MIB;
9280 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9281 const int64_t SPOffset = 2 * PVT.getStoreSize();
9282 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9283 const int64_t BPOffset = 4 * PVT.getStoreSize();
9285 unsigned BufReg = MI.getOperand(0).getReg();
9287 // Reload FP (the jumped-to function may not have had a
9288 // frame pointer, and if so, then its r31 will be restored
9290 if (PVT == MVT::i64) {
9291 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9295 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9299 MIB.setMemRefs(MMOBegin, MMOEnd);
9302 if (PVT == MVT::i64) {
9303 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9304 .addImm(LabelOffset)
9307 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9308 .addImm(LabelOffset)
9311 MIB.setMemRefs(MMOBegin, MMOEnd);
9314 if (PVT == MVT::i64) {
9315 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9319 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9323 MIB.setMemRefs(MMOBegin, MMOEnd);
9326 if (PVT == MVT::i64) {
9327 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9331 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9335 MIB.setMemRefs(MMOBegin, MMOEnd);
9338 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9339 setUsesTOCBasePtr(*MBB->getParent());
9340 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9344 MIB.setMemRefs(MMOBegin, MMOEnd);
9348 BuildMI(*MBB, MI, DL,
9349 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9350 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9352 MI.eraseFromParent();
9357 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9358 MachineBasicBlock *BB) const {
9359 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9360 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9361 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9362 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9363 // Call lowering should have added an r2 operand to indicate a dependence
9364 // on the TOC base pointer value. It can't however, because there is no
9365 // way to mark the dependence as implicit there, and so the stackmap code
9366 // will confuse it with a regular operand. Instead, add the dependence
9368 setUsesTOCBasePtr(*BB->getParent());
9369 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9372 return emitPatchPoint(MI, BB);
9375 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9376 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9377 return emitEHSjLjSetJmp(MI, BB);
9378 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9379 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9380 return emitEHSjLjLongJmp(MI, BB);
9383 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9385 // To "insert" these instructions we actually have to insert their
9386 // control-flow patterns.
9387 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9388 MachineFunction::iterator It = ++BB->getIterator();
9390 MachineFunction *F = BB->getParent();
9392 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9393 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9394 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9395 SmallVector<MachineOperand, 2> Cond;
9396 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9397 MI.getOpcode() == PPC::SELECT_CC_I8)
9398 Cond.push_back(MI.getOperand(4));
9400 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9401 Cond.push_back(MI.getOperand(1));
9403 DebugLoc dl = MI.getDebugLoc();
9404 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9405 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9406 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9407 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9408 MI.getOpcode() == PPC::SELECT_CC_F4 ||
9409 MI.getOpcode() == PPC::SELECT_CC_F8 ||
9410 MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9411 MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9412 MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9413 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9414 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9415 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9416 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9417 MI.getOpcode() == PPC::SELECT_I4 ||
9418 MI.getOpcode() == PPC::SELECT_I8 ||
9419 MI.getOpcode() == PPC::SELECT_F4 ||
9420 MI.getOpcode() == PPC::SELECT_F8 ||
9421 MI.getOpcode() == PPC::SELECT_QFRC ||
9422 MI.getOpcode() == PPC::SELECT_QSRC ||
9423 MI.getOpcode() == PPC::SELECT_QBRC ||
9424 MI.getOpcode() == PPC::SELECT_VRRC ||
9425 MI.getOpcode() == PPC::SELECT_VSFRC ||
9426 MI.getOpcode() == PPC::SELECT_VSSRC ||
9427 MI.getOpcode() == PPC::SELECT_VSRC) {
9428 // The incoming instruction knows the destination vreg to set, the
9429 // condition code register to branch on, the true/false values to
9430 // select between, and a branch opcode to use.
9435 // cmpTY ccX, r1, r2
9437 // fallthrough --> copy0MBB
9438 MachineBasicBlock *thisMBB = BB;
9439 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9440 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9441 DebugLoc dl = MI.getDebugLoc();
9442 F->insert(It, copy0MBB);
9443 F->insert(It, sinkMBB);
9445 // Transfer the remainder of BB and its successor edges to sinkMBB.
9446 sinkMBB->splice(sinkMBB->begin(), BB,
9447 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9448 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9450 // Next, add the true and fallthrough blocks as its successors.
9451 BB->addSuccessor(copy0MBB);
9452 BB->addSuccessor(sinkMBB);
9454 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9455 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9456 MI.getOpcode() == PPC::SELECT_QFRC ||
9457 MI.getOpcode() == PPC::SELECT_QSRC ||
9458 MI.getOpcode() == PPC::SELECT_QBRC ||
9459 MI.getOpcode() == PPC::SELECT_VRRC ||
9460 MI.getOpcode() == PPC::SELECT_VSFRC ||
9461 MI.getOpcode() == PPC::SELECT_VSSRC ||
9462 MI.getOpcode() == PPC::SELECT_VSRC) {
9463 BuildMI(BB, dl, TII->get(PPC::BC))
9464 .addReg(MI.getOperand(1).getReg())
9467 unsigned SelectPred = MI.getOperand(4).getImm();
9468 BuildMI(BB, dl, TII->get(PPC::BCC))
9470 .addReg(MI.getOperand(1).getReg())
9475 // %FalseValue = ...
9476 // # fallthrough to sinkMBB
9479 // Update machine-CFG edges
9480 BB->addSuccessor(sinkMBB);
9483 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9486 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9487 .addReg(MI.getOperand(3).getReg())
9489 .addReg(MI.getOperand(2).getReg())
9491 } else if (MI.getOpcode() == PPC::ReadTB) {
9492 // To read the 64-bit time-base register on a 32-bit target, we read the
9493 // two halves. Should the counter have wrapped while it was being read, we
9494 // need to try again.
9497 // mfspr Rx,TBU # load from TBU
9498 // mfspr Ry,TB # load from TB
9499 // mfspr Rz,TBU # load from TBU
9500 // cmpw crX,Rx,Rz # check if 'old'='new'
9501 // bne readLoop # branch if they're not equal
9504 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9505 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9506 DebugLoc dl = MI.getDebugLoc();
9507 F->insert(It, readMBB);
9508 F->insert(It, sinkMBB);
9510 // Transfer the remainder of BB and its successor edges to sinkMBB.
9511 sinkMBB->splice(sinkMBB->begin(), BB,
9512 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9513 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9515 BB->addSuccessor(readMBB);
9518 MachineRegisterInfo &RegInfo = F->getRegInfo();
9519 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9520 unsigned LoReg = MI.getOperand(0).getReg();
9521 unsigned HiReg = MI.getOperand(1).getReg();
9523 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9524 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9525 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9527 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9529 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9530 .addReg(HiReg).addReg(ReadAgainReg);
9531 BuildMI(BB, dl, TII->get(PPC::BCC))
9532 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9534 BB->addSuccessor(readMBB);
9535 BB->addSuccessor(sinkMBB);
9536 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9537 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9538 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9539 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9540 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9541 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9542 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9543 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9545 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9546 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9547 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9548 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9550 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9552 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9555 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9556 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9557 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9559 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9560 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9561 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9564 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9565 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9566 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9568 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9569 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9570 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9573 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9574 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9575 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9576 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9577 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9578 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9579 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9581 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9582 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9583 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9584 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9585 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9586 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9587 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9588 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9590 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9591 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9592 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9593 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9594 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9595 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9596 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9597 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9599 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9600 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9601 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9602 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9603 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9604 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9605 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9606 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9608 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9609 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9610 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9611 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9612 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9613 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9614 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9615 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9617 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9618 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9619 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9620 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9621 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9622 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9624 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9626 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9627 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9628 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9629 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9630 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9631 BB = EmitAtomicBinary(MI, BB, 4, 0);
9632 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9633 BB = EmitAtomicBinary(MI, BB, 8, 0);
9634 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9635 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9636 (Subtarget.hasPartwordAtomics() &&
9637 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9638 (Subtarget.hasPartwordAtomics() &&
9639 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9640 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9642 auto LoadMnemonic = PPC::LDARX;
9643 auto StoreMnemonic = PPC::STDCX;
9644 switch (MI.getOpcode()) {
9646 llvm_unreachable("Compare and swap of unknown size");
9647 case PPC::ATOMIC_CMP_SWAP_I8:
9648 LoadMnemonic = PPC::LBARX;
9649 StoreMnemonic = PPC::STBCX;
9650 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9652 case PPC::ATOMIC_CMP_SWAP_I16:
9653 LoadMnemonic = PPC::LHARX;
9654 StoreMnemonic = PPC::STHCX;
9655 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9657 case PPC::ATOMIC_CMP_SWAP_I32:
9658 LoadMnemonic = PPC::LWARX;
9659 StoreMnemonic = PPC::STWCX;
9661 case PPC::ATOMIC_CMP_SWAP_I64:
9662 LoadMnemonic = PPC::LDARX;
9663 StoreMnemonic = PPC::STDCX;
9666 unsigned dest = MI.getOperand(0).getReg();
9667 unsigned ptrA = MI.getOperand(1).getReg();
9668 unsigned ptrB = MI.getOperand(2).getReg();
9669 unsigned oldval = MI.getOperand(3).getReg();
9670 unsigned newval = MI.getOperand(4).getReg();
9671 DebugLoc dl = MI.getDebugLoc();
9673 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9674 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9675 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9676 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9677 F->insert(It, loop1MBB);
9678 F->insert(It, loop2MBB);
9679 F->insert(It, midMBB);
9680 F->insert(It, exitMBB);
9681 exitMBB->splice(exitMBB->begin(), BB,
9682 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9683 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9687 // fallthrough --> loopMBB
9688 BB->addSuccessor(loop1MBB);
9691 // l[bhwd]arx dest, ptr
9692 // cmp[wd] dest, oldval
9695 // st[bhwd]cx. newval, ptr
9699 // st[bhwd]cx. dest, ptr
9702 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9703 .addReg(ptrA).addReg(ptrB);
9704 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9705 .addReg(oldval).addReg(dest);
9706 BuildMI(BB, dl, TII->get(PPC::BCC))
9707 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9708 BB->addSuccessor(loop2MBB);
9709 BB->addSuccessor(midMBB);
9712 BuildMI(BB, dl, TII->get(StoreMnemonic))
9713 .addReg(newval).addReg(ptrA).addReg(ptrB);
9714 BuildMI(BB, dl, TII->get(PPC::BCC))
9715 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9716 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9717 BB->addSuccessor(loop1MBB);
9718 BB->addSuccessor(exitMBB);
9721 BuildMI(BB, dl, TII->get(StoreMnemonic))
9722 .addReg(dest).addReg(ptrA).addReg(ptrB);
9723 BB->addSuccessor(exitMBB);
9728 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9729 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9730 // We must use 64-bit registers for addresses when targeting 64-bit,
9731 // since we're actually doing arithmetic on them. Other registers
9733 bool is64bit = Subtarget.isPPC64();
9734 bool isLittleEndian = Subtarget.isLittleEndian();
9735 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9737 unsigned dest = MI.getOperand(0).getReg();
9738 unsigned ptrA = MI.getOperand(1).getReg();
9739 unsigned ptrB = MI.getOperand(2).getReg();
9740 unsigned oldval = MI.getOperand(3).getReg();
9741 unsigned newval = MI.getOperand(4).getReg();
9742 DebugLoc dl = MI.getDebugLoc();
9744 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9745 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9746 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9747 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9748 F->insert(It, loop1MBB);
9749 F->insert(It, loop2MBB);
9750 F->insert(It, midMBB);
9751 F->insert(It, exitMBB);
9752 exitMBB->splice(exitMBB->begin(), BB,
9753 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9754 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9756 MachineRegisterInfo &RegInfo = F->getRegInfo();
9757 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9758 : &PPC::GPRCRegClass;
9759 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9760 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9762 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9763 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9764 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9765 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9766 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9767 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9768 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9769 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9770 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9771 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9772 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9774 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9775 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9778 // fallthrough --> loopMBB
9779 BB->addSuccessor(loop1MBB);
9781 // The 4-byte load must be aligned, while a char or short may be
9782 // anywhere in the word. Hence all this nasty bookkeeping code.
9783 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9784 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9785 // xori shift, shift1, 24 [16]
9786 // rlwinm ptr, ptr1, 0, 0, 29
9787 // slw newval2, newval, shift
9788 // slw oldval2, oldval,shift
9789 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9790 // slw mask, mask2, shift
9791 // and newval3, newval2, mask
9792 // and oldval3, oldval2, mask
9794 // lwarx tmpDest, ptr
9795 // and tmp, tmpDest, mask
9796 // cmpw tmp, oldval3
9799 // andc tmp2, tmpDest, mask
9800 // or tmp4, tmp2, newval3
9805 // stwcx. tmpDest, ptr
9807 // srw dest, tmpDest, shift
9808 if (ptrA != ZeroReg) {
9809 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9810 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9811 .addReg(ptrA).addReg(ptrB);
9815 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9816 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9817 if (!isLittleEndian)
9818 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9819 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9821 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9822 .addReg(Ptr1Reg).addImm(0).addImm(61);
9824 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9825 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9826 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9827 .addReg(newval).addReg(ShiftReg);
9828 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9829 .addReg(oldval).addReg(ShiftReg);
9831 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9833 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9834 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9835 .addReg(Mask3Reg).addImm(65535);
9837 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9838 .addReg(Mask2Reg).addReg(ShiftReg);
9839 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9840 .addReg(NewVal2Reg).addReg(MaskReg);
9841 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9842 .addReg(OldVal2Reg).addReg(MaskReg);
9845 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9846 .addReg(ZeroReg).addReg(PtrReg);
9847 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9848 .addReg(TmpDestReg).addReg(MaskReg);
9849 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9850 .addReg(TmpReg).addReg(OldVal3Reg);
9851 BuildMI(BB, dl, TII->get(PPC::BCC))
9852 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9853 BB->addSuccessor(loop2MBB);
9854 BB->addSuccessor(midMBB);
9857 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9858 .addReg(TmpDestReg).addReg(MaskReg);
9859 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9860 .addReg(Tmp2Reg).addReg(NewVal3Reg);
9861 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9862 .addReg(ZeroReg).addReg(PtrReg);
9863 BuildMI(BB, dl, TII->get(PPC::BCC))
9864 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9865 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9866 BB->addSuccessor(loop1MBB);
9867 BB->addSuccessor(exitMBB);
9870 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9871 .addReg(ZeroReg).addReg(PtrReg);
9872 BB->addSuccessor(exitMBB);
9877 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9879 } else if (MI.getOpcode() == PPC::FADDrtz) {
9880 // This pseudo performs an FADD with rounding mode temporarily forced
9881 // to round-to-zero. We emit this via custom inserter since the FPSCR
9882 // is not modeled at the SelectionDAG level.
9883 unsigned Dest = MI.getOperand(0).getReg();
9884 unsigned Src1 = MI.getOperand(1).getReg();
9885 unsigned Src2 = MI.getOperand(2).getReg();
9886 DebugLoc dl = MI.getDebugLoc();
9888 MachineRegisterInfo &RegInfo = F->getRegInfo();
9889 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9891 // Save FPSCR value.
9892 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9894 // Set rounding mode to round-to-zero.
9895 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9896 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9898 // Perform addition.
9899 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9901 // Restore FPSCR value.
9902 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9903 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9904 MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9905 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9906 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9907 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9908 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9911 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9912 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9914 MachineRegisterInfo &RegInfo = F->getRegInfo();
9915 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9916 &PPC::GPRCRegClass :
9917 &PPC::G8RCRegClass);
9919 DebugLoc dl = MI.getDebugLoc();
9920 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9921 .addReg(MI.getOperand(1).getReg())
9923 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9924 MI.getOperand(0).getReg())
9925 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9926 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9927 DebugLoc Dl = MI.getDebugLoc();
9928 MachineRegisterInfo &RegInfo = F->getRegInfo();
9929 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9930 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9933 llvm_unreachable("Unexpected instr type to insert");
9936 MI.eraseFromParent(); // The pseudo instruction is gone now.
9940 //===----------------------------------------------------------------------===//
9941 // Target Optimization Hooks
9942 //===----------------------------------------------------------------------===//
9944 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9945 // For the estimates, convergence is quadratic, so we essentially double the
9946 // number of digits correct after every iteration. For both FRE and FRSQRTE,
9947 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9948 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9949 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9950 if (VT.getScalarType() == MVT::f64)
9952 return RefinementSteps;
9955 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9956 int Enabled, int &RefinementSteps,
9957 bool &UseOneConstNR,
9958 bool Reciprocal) const {
9959 EVT VT = Operand.getValueType();
9960 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9961 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9962 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9963 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9964 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9965 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9966 if (RefinementSteps == ReciprocalEstimate::Unspecified)
9967 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9969 UseOneConstNR = true;
9970 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9975 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9977 int &RefinementSteps) const {
9978 EVT VT = Operand.getValueType();
9979 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9980 (VT == MVT::f64 && Subtarget.hasFRE()) ||
9981 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9982 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9983 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9984 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9985 if (RefinementSteps == ReciprocalEstimate::Unspecified)
9986 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9987 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9992 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9993 // Note: This functionality is used only when unsafe-fp-math is enabled, and
9994 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9995 // enabled for division), this functionality is redundant with the default
9996 // combiner logic (once the division -> reciprocal/multiply transformation
9997 // has taken place). As a result, this matters more for older cores than for
10000 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10001 // reciprocal if there are two or more FDIVs (for embedded cores with only
10002 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10003 switch (Subtarget.getDarwinDirective()) {
10008 case PPC::DIR_E500mc:
10009 case PPC::DIR_E5500:
10014 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10015 // collapsed, and so we need to look through chains of them.
10016 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10017 int64_t& Offset, SelectionDAG &DAG) {
10018 if (DAG.isBaseWithConstantOffset(Loc)) {
10019 Base = Loc.getOperand(0);
10020 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10022 // The base might itself be a base plus an offset, and if so, accumulate
10024 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10028 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10029 unsigned Bytes, int Dist,
10030 SelectionDAG &DAG) {
10031 if (VT.getSizeInBits() / 8 != Bytes)
10034 SDValue BaseLoc = Base->getBasePtr();
10035 if (Loc.getOpcode() == ISD::FrameIndex) {
10036 if (BaseLoc.getOpcode() != ISD::FrameIndex)
10038 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10039 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
10040 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10041 int FS = MFI.getObjectSize(FI);
10042 int BFS = MFI.getObjectSize(BFI);
10043 if (FS != BFS || FS != (int)Bytes) return false;
10044 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10047 SDValue Base1 = Loc, Base2 = BaseLoc;
10048 int64_t Offset1 = 0, Offset2 = 0;
10049 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10050 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10051 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10054 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10055 const GlobalValue *GV1 = nullptr;
10056 const GlobalValue *GV2 = nullptr;
10059 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10060 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10061 if (isGA1 && isGA2 && GV1 == GV2)
10062 return Offset1 == (Offset2 + Dist*Bytes);
10066 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10067 // not enforce equality of the chain operands.
10068 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10069 unsigned Bytes, int Dist,
10070 SelectionDAG &DAG) {
10071 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10072 EVT VT = LS->getMemoryVT();
10073 SDValue Loc = LS->getBasePtr();
10074 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10077 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10079 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10080 default: return false;
10081 case Intrinsic::ppc_qpx_qvlfd:
10082 case Intrinsic::ppc_qpx_qvlfda:
10085 case Intrinsic::ppc_qpx_qvlfs:
10086 case Intrinsic::ppc_qpx_qvlfsa:
10089 case Intrinsic::ppc_qpx_qvlfcd:
10090 case Intrinsic::ppc_qpx_qvlfcda:
10093 case Intrinsic::ppc_qpx_qvlfcs:
10094 case Intrinsic::ppc_qpx_qvlfcsa:
10097 case Intrinsic::ppc_qpx_qvlfiwa:
10098 case Intrinsic::ppc_qpx_qvlfiwz:
10099 case Intrinsic::ppc_altivec_lvx:
10100 case Intrinsic::ppc_altivec_lvxl:
10101 case Intrinsic::ppc_vsx_lxvw4x:
10102 case Intrinsic::ppc_vsx_lxvw4x_be:
10105 case Intrinsic::ppc_vsx_lxvd2x:
10106 case Intrinsic::ppc_vsx_lxvd2x_be:
10109 case Intrinsic::ppc_altivec_lvebx:
10112 case Intrinsic::ppc_altivec_lvehx:
10115 case Intrinsic::ppc_altivec_lvewx:
10120 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10123 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10125 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10126 default: return false;
10127 case Intrinsic::ppc_qpx_qvstfd:
10128 case Intrinsic::ppc_qpx_qvstfda:
10131 case Intrinsic::ppc_qpx_qvstfs:
10132 case Intrinsic::ppc_qpx_qvstfsa:
10135 case Intrinsic::ppc_qpx_qvstfcd:
10136 case Intrinsic::ppc_qpx_qvstfcda:
10139 case Intrinsic::ppc_qpx_qvstfcs:
10140 case Intrinsic::ppc_qpx_qvstfcsa:
10143 case Intrinsic::ppc_qpx_qvstfiw:
10144 case Intrinsic::ppc_qpx_qvstfiwa:
10145 case Intrinsic::ppc_altivec_stvx:
10146 case Intrinsic::ppc_altivec_stvxl:
10147 case Intrinsic::ppc_vsx_stxvw4x:
10150 case Intrinsic::ppc_vsx_stxvd2x:
10153 case Intrinsic::ppc_vsx_stxvw4x_be:
10156 case Intrinsic::ppc_vsx_stxvd2x_be:
10159 case Intrinsic::ppc_altivec_stvebx:
10162 case Intrinsic::ppc_altivec_stvehx:
10165 case Intrinsic::ppc_altivec_stvewx:
10170 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10176 // Return true is there is a nearyby consecutive load to the one provided
10177 // (regardless of alignment). We search up and down the chain, looking though
10178 // token factors and other loads (but nothing else). As a result, a true result
10179 // indicates that it is safe to create a new consecutive load adjacent to the
10181 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10182 SDValue Chain = LD->getChain();
10183 EVT VT = LD->getMemoryVT();
10185 SmallSet<SDNode *, 16> LoadRoots;
10186 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10187 SmallSet<SDNode *, 16> Visited;
10189 // First, search up the chain, branching to follow all token-factor operands.
10190 // If we find a consecutive load, then we're done, otherwise, record all
10191 // nodes just above the top-level loads and token factors.
10192 while (!Queue.empty()) {
10193 SDNode *ChainNext = Queue.pop_back_val();
10194 if (!Visited.insert(ChainNext).second)
10197 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10198 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10201 if (!Visited.count(ChainLD->getChain().getNode()))
10202 Queue.push_back(ChainLD->getChain().getNode());
10203 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10204 for (const SDUse &O : ChainNext->ops())
10205 if (!Visited.count(O.getNode()))
10206 Queue.push_back(O.getNode());
10208 LoadRoots.insert(ChainNext);
10211 // Second, search down the chain, starting from the top-level nodes recorded
10212 // in the first phase. These top-level nodes are the nodes just above all
10213 // loads and token factors. Starting with their uses, recursively look though
10214 // all loads (just the chain uses) and token factors to find a consecutive
10219 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10220 IE = LoadRoots.end(); I != IE; ++I) {
10221 Queue.push_back(*I);
10223 while (!Queue.empty()) {
10224 SDNode *LoadRoot = Queue.pop_back_val();
10225 if (!Visited.insert(LoadRoot).second)
10228 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10229 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10232 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10233 UE = LoadRoot->use_end(); UI != UE; ++UI)
10234 if (((isa<MemSDNode>(*UI) &&
10235 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10236 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10237 Queue.push_back(*UI);
10244 /// This function is called when we have proved that a SETCC node can be replaced
10245 /// by subtraction (and other supporting instructions) so that the result of
10246 /// comparison is kept in a GPR instead of CR. This function is purely for
10247 /// codegen purposes and has some flags to guide the codegen process.
10248 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10249 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10250 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10252 // Zero extend the operands to the largest legal integer. Originally, they
10253 // must be of a strictly smaller size.
10254 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10255 DAG.getConstant(Size, DL, MVT::i32));
10256 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10257 DAG.getConstant(Size, DL, MVT::i32));
10259 // Swap if needed. Depends on the condition code.
10261 std::swap(Op0, Op1);
10263 // Subtract extended integers.
10264 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10266 // Move the sign bit to the least significant position and zero out the rest.
10267 // Now the least significant bit carries the result of original comparison.
10268 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10269 DAG.getConstant(Size - 1, DL, MVT::i32));
10270 auto Final = Shifted;
10272 // Complement the result if needed. Based on the condition code.
10274 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10275 DAG.getConstant(1, DL, MVT::i64));
10277 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10280 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10281 DAGCombinerInfo &DCI) const {
10282 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10284 SelectionDAG &DAG = DCI.DAG;
10287 // Size of integers being compared has a critical role in the following
10288 // analysis, so we prefer to do this when all types are legal.
10289 if (!DCI.isAfterLegalizeVectorOps())
10292 // If all users of SETCC extend its value to a legal integer type
10293 // then we replace SETCC with a subtraction
10294 for (SDNode::use_iterator UI = N->use_begin(),
10295 UE = N->use_end(); UI != UE; ++UI) {
10296 if (UI->getOpcode() != ISD::ZERO_EXTEND)
10300 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10301 auto OpSize = N->getOperand(0).getValueSizeInBits();
10303 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10305 if (OpSize < Size) {
10309 return generateEquivalentSub(N, Size, false, false, DL, DAG);
10311 return generateEquivalentSub(N, Size, true, true, DL, DAG);
10313 return generateEquivalentSub(N, Size, false, true, DL, DAG);
10315 return generateEquivalentSub(N, Size, true, false, DL, DAG);
10322 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10323 DAGCombinerInfo &DCI) const {
10324 SelectionDAG &DAG = DCI.DAG;
10327 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10328 // If we're tracking CR bits, we need to be careful that we don't have:
10329 // trunc(binary-ops(zext(x), zext(y)))
10331 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10332 // such that we're unnecessarily moving things into GPRs when it would be
10333 // better to keep them in CR bits.
10335 // Note that trunc here can be an actual i1 trunc, or can be the effective
10336 // truncation that comes from a setcc or select_cc.
10337 if (N->getOpcode() == ISD::TRUNCATE &&
10338 N->getValueType(0) != MVT::i1)
10341 if (N->getOperand(0).getValueType() != MVT::i32 &&
10342 N->getOperand(0).getValueType() != MVT::i64)
10345 if (N->getOpcode() == ISD::SETCC ||
10346 N->getOpcode() == ISD::SELECT_CC) {
10347 // If we're looking at a comparison, then we need to make sure that the
10348 // high bits (all except for the first) don't matter the result.
10350 cast<CondCodeSDNode>(N->getOperand(
10351 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10352 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10354 if (ISD::isSignedIntSetCC(CC)) {
10355 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10356 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10358 } else if (ISD::isUnsignedIntSetCC(CC)) {
10359 if (!DAG.MaskedValueIsZero(N->getOperand(0),
10360 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10361 !DAG.MaskedValueIsZero(N->getOperand(1),
10362 APInt::getHighBitsSet(OpBits, OpBits-1)))
10363 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10366 // This is neither a signed nor an unsigned comparison, just make sure
10367 // that the high bits are equal.
10368 KnownBits Op1Known, Op2Known;
10369 DAG.computeKnownBits(N->getOperand(0), Op1Known);
10370 DAG.computeKnownBits(N->getOperand(1), Op2Known);
10372 // We don't really care about what is known about the first bit (if
10373 // anything), so clear it in all masks prior to comparing them.
10374 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10375 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10377 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10382 // We now know that the higher-order bits are irrelevant, we just need to
10383 // make sure that all of the intermediate operations are bit operations, and
10384 // all inputs are extensions.
10385 if (N->getOperand(0).getOpcode() != ISD::AND &&
10386 N->getOperand(0).getOpcode() != ISD::OR &&
10387 N->getOperand(0).getOpcode() != ISD::XOR &&
10388 N->getOperand(0).getOpcode() != ISD::SELECT &&
10389 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10390 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10391 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10392 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10393 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10396 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10397 N->getOperand(1).getOpcode() != ISD::AND &&
10398 N->getOperand(1).getOpcode() != ISD::OR &&
10399 N->getOperand(1).getOpcode() != ISD::XOR &&
10400 N->getOperand(1).getOpcode() != ISD::SELECT &&
10401 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10402 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10403 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10404 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10405 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10408 SmallVector<SDValue, 4> Inputs;
10409 SmallVector<SDValue, 8> BinOps, PromOps;
10410 SmallPtrSet<SDNode *, 16> Visited;
10412 for (unsigned i = 0; i < 2; ++i) {
10413 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10414 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10415 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10416 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10417 isa<ConstantSDNode>(N->getOperand(i)))
10418 Inputs.push_back(N->getOperand(i));
10420 BinOps.push_back(N->getOperand(i));
10422 if (N->getOpcode() == ISD::TRUNCATE)
10426 // Visit all inputs, collect all binary operations (and, or, xor and
10427 // select) that are all fed by extensions.
10428 while (!BinOps.empty()) {
10429 SDValue BinOp = BinOps.back();
10432 if (!Visited.insert(BinOp.getNode()).second)
10435 PromOps.push_back(BinOp);
10437 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10438 // The condition of the select is not promoted.
10439 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10441 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10444 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10445 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10446 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10447 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10448 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10449 Inputs.push_back(BinOp.getOperand(i));
10450 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10451 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10452 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10453 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10454 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10455 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10456 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10457 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10458 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10459 BinOps.push_back(BinOp.getOperand(i));
10461 // We have an input that is not an extension or another binary
10462 // operation; we'll abort this transformation.
10468 // Make sure that this is a self-contained cluster of operations (which
10469 // is not quite the same thing as saying that everything has only one
10471 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10472 if (isa<ConstantSDNode>(Inputs[i]))
10475 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10476 UE = Inputs[i].getNode()->use_end();
10478 SDNode *User = *UI;
10479 if (User != N && !Visited.count(User))
10482 // Make sure that we're not going to promote the non-output-value
10483 // operand(s) or SELECT or SELECT_CC.
10484 // FIXME: Although we could sometimes handle this, and it does occur in
10485 // practice that one of the condition inputs to the select is also one of
10486 // the outputs, we currently can't deal with this.
10487 if (User->getOpcode() == ISD::SELECT) {
10488 if (User->getOperand(0) == Inputs[i])
10490 } else if (User->getOpcode() == ISD::SELECT_CC) {
10491 if (User->getOperand(0) == Inputs[i] ||
10492 User->getOperand(1) == Inputs[i])
10498 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10499 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10500 UE = PromOps[i].getNode()->use_end();
10502 SDNode *User = *UI;
10503 if (User != N && !Visited.count(User))
10506 // Make sure that we're not going to promote the non-output-value
10507 // operand(s) or SELECT or SELECT_CC.
10508 // FIXME: Although we could sometimes handle this, and it does occur in
10509 // practice that one of the condition inputs to the select is also one of
10510 // the outputs, we currently can't deal with this.
10511 if (User->getOpcode() == ISD::SELECT) {
10512 if (User->getOperand(0) == PromOps[i])
10514 } else if (User->getOpcode() == ISD::SELECT_CC) {
10515 if (User->getOperand(0) == PromOps[i] ||
10516 User->getOperand(1) == PromOps[i])
10522 // Replace all inputs with the extension operand.
10523 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10524 // Constants may have users outside the cluster of to-be-promoted nodes,
10525 // and so we need to replace those as we do the promotions.
10526 if (isa<ConstantSDNode>(Inputs[i]))
10529 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10532 std::list<HandleSDNode> PromOpHandles;
10533 for (auto &PromOp : PromOps)
10534 PromOpHandles.emplace_back(PromOp);
10536 // Replace all operations (these are all the same, but have a different
10537 // (i1) return type). DAG.getNode will validate that the types of
10538 // a binary operator match, so go through the list in reverse so that
10539 // we've likely promoted both operands first. Any intermediate truncations or
10540 // extensions disappear.
10541 while (!PromOpHandles.empty()) {
10542 SDValue PromOp = PromOpHandles.back().getValue();
10543 PromOpHandles.pop_back();
10545 if (PromOp.getOpcode() == ISD::TRUNCATE ||
10546 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10547 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10548 PromOp.getOpcode() == ISD::ANY_EXTEND) {
10549 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10550 PromOp.getOperand(0).getValueType() != MVT::i1) {
10551 // The operand is not yet ready (see comment below).
10552 PromOpHandles.emplace_front(PromOp);
10556 SDValue RepValue = PromOp.getOperand(0);
10557 if (isa<ConstantSDNode>(RepValue))
10558 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10560 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10565 switch (PromOp.getOpcode()) {
10566 default: C = 0; break;
10567 case ISD::SELECT: C = 1; break;
10568 case ISD::SELECT_CC: C = 2; break;
10571 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10572 PromOp.getOperand(C).getValueType() != MVT::i1) ||
10573 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10574 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10575 // The to-be-promoted operands of this node have not yet been
10576 // promoted (this should be rare because we're going through the
10577 // list backward, but if one of the operands has several users in
10578 // this cluster of to-be-promoted nodes, it is possible).
10579 PromOpHandles.emplace_front(PromOp);
10583 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10584 PromOp.getNode()->op_end());
10586 // If there are any constant inputs, make sure they're replaced now.
10587 for (unsigned i = 0; i < 2; ++i)
10588 if (isa<ConstantSDNode>(Ops[C+i]))
10589 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10591 DAG.ReplaceAllUsesOfValueWith(PromOp,
10592 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10595 // Now we're left with the initial truncation itself.
10596 if (N->getOpcode() == ISD::TRUNCATE)
10597 return N->getOperand(0);
10599 // Otherwise, this is a comparison. The operands to be compared have just
10600 // changed type (to i1), but everything else is the same.
10601 return SDValue(N, 0);
10604 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10605 DAGCombinerInfo &DCI) const {
10606 SelectionDAG &DAG = DCI.DAG;
10609 // If we're tracking CR bits, we need to be careful that we don't have:
10610 // zext(binary-ops(trunc(x), trunc(y)))
10612 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10613 // such that we're unnecessarily moving things into CR bits that can more
10614 // efficiently stay in GPRs. Note that if we're not certain that the high
10615 // bits are set as required by the final extension, we still may need to do
10616 // some masking to get the proper behavior.
10618 // This same functionality is important on PPC64 when dealing with
10619 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10620 // the return values of functions. Because it is so similar, it is handled
10623 if (N->getValueType(0) != MVT::i32 &&
10624 N->getValueType(0) != MVT::i64)
10627 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10628 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10631 if (N->getOperand(0).getOpcode() != ISD::AND &&
10632 N->getOperand(0).getOpcode() != ISD::OR &&
10633 N->getOperand(0).getOpcode() != ISD::XOR &&
10634 N->getOperand(0).getOpcode() != ISD::SELECT &&
10635 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10638 SmallVector<SDValue, 4> Inputs;
10639 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10640 SmallPtrSet<SDNode *, 16> Visited;
10642 // Visit all inputs, collect all binary operations (and, or, xor and
10643 // select) that are all fed by truncations.
10644 while (!BinOps.empty()) {
10645 SDValue BinOp = BinOps.back();
10648 if (!Visited.insert(BinOp.getNode()).second)
10651 PromOps.push_back(BinOp);
10653 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10654 // The condition of the select is not promoted.
10655 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10657 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10660 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10661 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10662 Inputs.push_back(BinOp.getOperand(i));
10663 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10664 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10665 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10666 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10667 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10668 BinOps.push_back(BinOp.getOperand(i));
10670 // We have an input that is not a truncation or another binary
10671 // operation; we'll abort this transformation.
10677 // The operands of a select that must be truncated when the select is
10678 // promoted because the operand is actually part of the to-be-promoted set.
10679 DenseMap<SDNode *, EVT> SelectTruncOp[2];
10681 // Make sure that this is a self-contained cluster of operations (which
10682 // is not quite the same thing as saying that everything has only one
10684 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10685 if (isa<ConstantSDNode>(Inputs[i]))
10688 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10689 UE = Inputs[i].getNode()->use_end();
10691 SDNode *User = *UI;
10692 if (User != N && !Visited.count(User))
10695 // If we're going to promote the non-output-value operand(s) or SELECT or
10696 // SELECT_CC, record them for truncation.
10697 if (User->getOpcode() == ISD::SELECT) {
10698 if (User->getOperand(0) == Inputs[i])
10699 SelectTruncOp[0].insert(std::make_pair(User,
10700 User->getOperand(0).getValueType()));
10701 } else if (User->getOpcode() == ISD::SELECT_CC) {
10702 if (User->getOperand(0) == Inputs[i])
10703 SelectTruncOp[0].insert(std::make_pair(User,
10704 User->getOperand(0).getValueType()));
10705 if (User->getOperand(1) == Inputs[i])
10706 SelectTruncOp[1].insert(std::make_pair(User,
10707 User->getOperand(1).getValueType()));
10712 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10713 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10714 UE = PromOps[i].getNode()->use_end();
10716 SDNode *User = *UI;
10717 if (User != N && !Visited.count(User))
10720 // If we're going to promote the non-output-value operand(s) or SELECT or
10721 // SELECT_CC, record them for truncation.
10722 if (User->getOpcode() == ISD::SELECT) {
10723 if (User->getOperand(0) == PromOps[i])
10724 SelectTruncOp[0].insert(std::make_pair(User,
10725 User->getOperand(0).getValueType()));
10726 } else if (User->getOpcode() == ISD::SELECT_CC) {
10727 if (User->getOperand(0) == PromOps[i])
10728 SelectTruncOp[0].insert(std::make_pair(User,
10729 User->getOperand(0).getValueType()));
10730 if (User->getOperand(1) == PromOps[i])
10731 SelectTruncOp[1].insert(std::make_pair(User,
10732 User->getOperand(1).getValueType()));
10737 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10738 bool ReallyNeedsExt = false;
10739 if (N->getOpcode() != ISD::ANY_EXTEND) {
10740 // If all of the inputs are not already sign/zero extended, then
10741 // we'll still need to do that at the end.
10742 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10743 if (isa<ConstantSDNode>(Inputs[i]))
10747 Inputs[i].getOperand(0).getValueSizeInBits();
10748 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10750 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10751 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10752 APInt::getHighBitsSet(OpBits,
10753 OpBits-PromBits))) ||
10754 (N->getOpcode() == ISD::SIGN_EXTEND &&
10755 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10756 (OpBits-(PromBits-1)))) {
10757 ReallyNeedsExt = true;
10763 // Replace all inputs, either with the truncation operand, or a
10764 // truncation or extension to the final output type.
10765 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10766 // Constant inputs need to be replaced with the to-be-promoted nodes that
10767 // use them because they might have users outside of the cluster of
10769 if (isa<ConstantSDNode>(Inputs[i]))
10772 SDValue InSrc = Inputs[i].getOperand(0);
10773 if (Inputs[i].getValueType() == N->getValueType(0))
10774 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10775 else if (N->getOpcode() == ISD::SIGN_EXTEND)
10776 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10777 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10778 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10779 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10780 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10782 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10783 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10786 std::list<HandleSDNode> PromOpHandles;
10787 for (auto &PromOp : PromOps)
10788 PromOpHandles.emplace_back(PromOp);
10790 // Replace all operations (these are all the same, but have a different
10791 // (promoted) return type). DAG.getNode will validate that the types of
10792 // a binary operator match, so go through the list in reverse so that
10793 // we've likely promoted both operands first.
10794 while (!PromOpHandles.empty()) {
10795 SDValue PromOp = PromOpHandles.back().getValue();
10796 PromOpHandles.pop_back();
10799 switch (PromOp.getOpcode()) {
10800 default: C = 0; break;
10801 case ISD::SELECT: C = 1; break;
10802 case ISD::SELECT_CC: C = 2; break;
10805 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10806 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10807 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10808 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10809 // The to-be-promoted operands of this node have not yet been
10810 // promoted (this should be rare because we're going through the
10811 // list backward, but if one of the operands has several users in
10812 // this cluster of to-be-promoted nodes, it is possible).
10813 PromOpHandles.emplace_front(PromOp);
10817 // For SELECT and SELECT_CC nodes, we do a similar check for any
10818 // to-be-promoted comparison inputs.
10819 if (PromOp.getOpcode() == ISD::SELECT ||
10820 PromOp.getOpcode() == ISD::SELECT_CC) {
10821 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10822 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10823 (SelectTruncOp[1].count(PromOp.getNode()) &&
10824 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10825 PromOpHandles.emplace_front(PromOp);
10830 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10831 PromOp.getNode()->op_end());
10833 // If this node has constant inputs, then they'll need to be promoted here.
10834 for (unsigned i = 0; i < 2; ++i) {
10835 if (!isa<ConstantSDNode>(Ops[C+i]))
10837 if (Ops[C+i].getValueType() == N->getValueType(0))
10840 if (N->getOpcode() == ISD::SIGN_EXTEND)
10841 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10842 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10843 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10845 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10848 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10849 // truncate them again to the original value type.
10850 if (PromOp.getOpcode() == ISD::SELECT ||
10851 PromOp.getOpcode() == ISD::SELECT_CC) {
10852 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10853 if (SI0 != SelectTruncOp[0].end())
10854 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10855 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10856 if (SI1 != SelectTruncOp[1].end())
10857 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10860 DAG.ReplaceAllUsesOfValueWith(PromOp,
10861 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10864 // Now we're left with the initial extension itself.
10865 if (!ReallyNeedsExt)
10866 return N->getOperand(0);
10868 // To zero extend, just mask off everything except for the first bit (in the
10870 if (N->getOpcode() == ISD::ZERO_EXTEND)
10871 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10872 DAG.getConstant(APInt::getLowBitsSet(
10873 N->getValueSizeInBits(0), PromBits),
10874 dl, N->getValueType(0)));
10876 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10877 "Invalid extension type");
10878 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10880 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10881 return DAG.getNode(
10882 ISD::SRA, dl, N->getValueType(0),
10883 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10887 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10889 /// If this vector is built out of floating to integer conversions,
10890 /// transform it to a vector built out of floating point values followed by a
10891 /// single floating to integer conversion of the vector.
10892 /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
10893 /// becomes (fptosi (build_vector ($A, $B, ...)))
10894 SDValue PPCTargetLowering::
10895 combineElementTruncationToVectorTruncation(SDNode *N,
10896 DAGCombinerInfo &DCI) const {
10897 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10898 "Should be called with a BUILD_VECTOR node");
10900 SelectionDAG &DAG = DCI.DAG;
10903 SDValue FirstInput = N->getOperand(0);
10904 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10905 "The input operand must be an fp-to-int conversion.");
10907 // This combine happens after legalization so the fp_to_[su]i nodes are
10908 // already converted to PPCSISD nodes.
10909 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10910 if (FirstConversion == PPCISD::FCTIDZ ||
10911 FirstConversion == PPCISD::FCTIDUZ ||
10912 FirstConversion == PPCISD::FCTIWZ ||
10913 FirstConversion == PPCISD::FCTIWUZ) {
10914 bool IsSplat = true;
10915 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10916 FirstConversion == PPCISD::FCTIWUZ;
10917 EVT SrcVT = FirstInput.getOperand(0).getValueType();
10918 SmallVector<SDValue, 4> Ops;
10919 EVT TargetVT = N->getValueType(0);
10920 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10921 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10923 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10924 if (NextConversion != FirstConversion)
10926 if (N->getOperand(i) != FirstInput)
10930 // If this is a splat, we leave it as-is since there will be only a single
10931 // fp-to-int conversion followed by a splat of the integer. This is better
10932 // for 32-bit and smaller ints and neutral for 64-bit ints.
10936 // Now that we know we have the right type of node, get its operands
10937 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10938 SDValue In = N->getOperand(i).getOperand(0);
10939 // For 32-bit values, we need to add an FP_ROUND node.
10942 Ops.push_back(DAG.getUNDEF(SrcVT));
10944 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10945 MVT::f32, In.getOperand(0),
10946 DAG.getIntPtrConstant(1, dl));
10947 Ops.push_back(Trunc);
10950 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10954 if (FirstConversion == PPCISD::FCTIDZ ||
10955 FirstConversion == PPCISD::FCTIWZ)
10956 Opcode = ISD::FP_TO_SINT;
10958 Opcode = ISD::FP_TO_UINT;
10960 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10961 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10962 return DAG.getNode(Opcode, dl, TargetVT, BV);
10967 /// \brief Reduce the number of loads when building a vector.
10969 /// Building a vector out of multiple loads can be converted to a load
10970 /// of the vector type if the loads are consecutive. If the loads are
10971 /// consecutive but in descending order, a shuffle is added at the end
10972 /// to reorder the vector.
10973 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10974 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10975 "Should be called with a BUILD_VECTOR node");
10978 bool InputsAreConsecutiveLoads = true;
10979 bool InputsAreReverseConsecutive = true;
10980 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10981 SDValue FirstInput = N->getOperand(0);
10982 bool IsRoundOfExtLoad = false;
10984 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10985 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10986 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10987 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10989 // Not a build vector of (possibly fp_rounded) loads.
10990 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10993 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10994 // If any inputs are fp_round(extload), they all must be.
10995 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10998 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11000 if (NextInput.getOpcode() != ISD::LOAD)
11003 SDValue PreviousInput =
11004 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11005 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11006 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11008 // If any inputs are fp_round(extload), they all must be.
11009 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11012 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11013 InputsAreConsecutiveLoads = false;
11014 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11015 InputsAreReverseConsecutive = false;
11017 // Exit early if the loads are neither consecutive nor reverse consecutive.
11018 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11022 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11023 "The loads cannot be both consecutive and reverse consecutive.");
11025 SDValue FirstLoadOp =
11026 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11027 SDValue LastLoadOp =
11028 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11029 N->getOperand(N->getNumOperands()-1);
11031 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11032 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11033 if (InputsAreConsecutiveLoads) {
11034 assert(LD1 && "Input needs to be a LoadSDNode.");
11035 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11036 LD1->getBasePtr(), LD1->getPointerInfo(),
11037 LD1->getAlignment());
11039 if (InputsAreReverseConsecutive) {
11040 assert(LDL && "Input needs to be a LoadSDNode.");
11041 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11042 LDL->getBasePtr(), LDL->getPointerInfo(),
11043 LDL->getAlignment());
11044 SmallVector<int, 16> Ops;
11045 for (int i = N->getNumOperands() - 1; i >= 0; i--)
11048 return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11049 DAG.getUNDEF(N->getValueType(0)), Ops);
11054 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11055 DAGCombinerInfo &DCI) const {
11056 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11057 "Should be called with a BUILD_VECTOR node");
11059 SelectionDAG &DAG = DCI.DAG;
11062 if (!Subtarget.hasVSX())
11065 // The target independent DAG combiner will leave a build_vector of
11066 // float-to-int conversions intact. We can generate MUCH better code for
11067 // a float-to-int conversion of a vector of floats.
11068 SDValue FirstInput = N->getOperand(0);
11069 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11070 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11075 // If we're building a vector out of consecutive loads, just load that
11077 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11081 if (N->getValueType(0) != MVT::v2f64)
11085 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11086 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11087 FirstInput.getOpcode() != ISD::UINT_TO_FP)
11089 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11090 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11092 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11095 SDValue Ext1 = FirstInput.getOperand(0);
11096 SDValue Ext2 = N->getOperand(1).getOperand(0);
11097 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11098 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11101 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11102 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11103 if (!Ext1Op || !Ext2Op)
11105 if (Ext1.getValueType() != MVT::i32 ||
11106 Ext2.getValueType() != MVT::i32)
11107 if (Ext1.getOperand(0) != Ext2.getOperand(0))
11110 int FirstElem = Ext1Op->getZExtValue();
11111 int SecondElem = Ext2Op->getZExtValue();
11113 if (FirstElem == 0 && SecondElem == 1)
11114 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11115 else if (FirstElem == 2 && SecondElem == 3)
11116 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11120 SDValue SrcVec = Ext1.getOperand(0);
11121 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11122 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11123 return DAG.getNode(NodeType, dl, MVT::v2f64,
11124 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11127 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11128 DAGCombinerInfo &DCI) const {
11129 assert((N->getOpcode() == ISD::SINT_TO_FP ||
11130 N->getOpcode() == ISD::UINT_TO_FP) &&
11131 "Need an int -> FP conversion node here");
11133 if (useSoftFloat() || !Subtarget.has64BitSupport())
11136 SelectionDAG &DAG = DCI.DAG;
11140 SDValue FirstOperand(Op.getOperand(0));
11141 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11142 (FirstOperand.getValueType() == MVT::i8 ||
11143 FirstOperand.getValueType() == MVT::i16);
11144 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11145 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11146 bool DstDouble = Op.getValueType() == MVT::f64;
11147 unsigned ConvOp = Signed ?
11148 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
11149 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11150 SDValue WidthConst =
11151 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11153 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11154 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11155 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11156 DAG.getVTList(MVT::f64, MVT::Other),
11157 Ops, MVT::i8, LDN->getMemOperand());
11159 // For signed conversion, we need to sign-extend the value in the VSR
11161 SDValue ExtOps[] = { Ld, WidthConst };
11162 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11163 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11165 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11168 // Don't handle ppc_fp128 here or i1 conversions.
11169 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11171 if (Op.getOperand(0).getValueType() == MVT::i1)
11174 // For i32 intermediate values, unfortunately, the conversion functions
11175 // leave the upper 32 bits of the value are undefined. Within the set of
11176 // scalar instructions, we have no method for zero- or sign-extending the
11177 // value. Thus, we cannot handle i32 intermediate values here.
11178 if (Op.getOperand(0).getValueType() == MVT::i32)
11181 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11182 "UINT_TO_FP is supported only with FPCVT");
11184 // If we have FCFIDS, then use it when converting to single-precision.
11185 // Otherwise, convert to double-precision and then round.
11186 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11187 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11189 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11191 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11195 // If we're converting from a float, to an int, and back to a float again,
11196 // then we don't need the store/load pair at all.
11197 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11198 Subtarget.hasFPCVT()) ||
11199 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11200 SDValue Src = Op.getOperand(0).getOperand(0);
11201 if (Src.getValueType() == MVT::f32) {
11202 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11203 DCI.AddToWorklist(Src.getNode());
11204 } else if (Src.getValueType() != MVT::f64) {
11205 // Make sure that we don't pick up a ppc_fp128 source value.
11210 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11213 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11214 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11216 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11217 FP = DAG.getNode(ISD::FP_ROUND, dl,
11218 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11219 DCI.AddToWorklist(FP.getNode());
11228 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11229 // builtins) into loads with swaps.
11230 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11231 DAGCombinerInfo &DCI) const {
11232 SelectionDAG &DAG = DCI.DAG;
11236 MachineMemOperand *MMO;
11238 switch (N->getOpcode()) {
11240 llvm_unreachable("Unexpected opcode for little endian VSX load");
11242 LoadSDNode *LD = cast<LoadSDNode>(N);
11243 Chain = LD->getChain();
11244 Base = LD->getBasePtr();
11245 MMO = LD->getMemOperand();
11246 // If the MMO suggests this isn't a load of a full vector, leave
11247 // things alone. For a built-in, we have to make the change for
11248 // correctness, so if there is a size problem that will be a bug.
11249 if (MMO->getSize() < 16)
11253 case ISD::INTRINSIC_W_CHAIN: {
11254 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11255 Chain = Intrin->getChain();
11256 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11257 // us what we want. Get operand 2 instead.
11258 Base = Intrin->getOperand(2);
11259 MMO = Intrin->getMemOperand();
11264 MVT VecTy = N->getValueType(0).getSimpleVT();
11266 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11267 // aligned and the type is a vector with elements up to 4 bytes
11268 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11269 && VecTy.getScalarSizeInBits() <= 32 ) {
11273 SDValue LoadOps[] = { Chain, Base };
11274 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11275 DAG.getVTList(MVT::v2f64, MVT::Other),
11276 LoadOps, MVT::v2f64, MMO);
11278 DCI.AddToWorklist(Load.getNode());
11279 Chain = Load.getValue(1);
11280 SDValue Swap = DAG.getNode(
11281 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11282 DCI.AddToWorklist(Swap.getNode());
11284 // Add a bitcast if the resulting load type doesn't match v2f64.
11285 if (VecTy != MVT::v2f64) {
11286 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11287 DCI.AddToWorklist(N.getNode());
11288 // Package {bitcast value, swap's chain} to match Load's shape.
11289 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11290 N, Swap.getValue(1));
11296 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11297 // builtins) into stores with swaps.
11298 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11299 DAGCombinerInfo &DCI) const {
11300 SelectionDAG &DAG = DCI.DAG;
11305 MachineMemOperand *MMO;
11307 switch (N->getOpcode()) {
11309 llvm_unreachable("Unexpected opcode for little endian VSX store");
11311 StoreSDNode *ST = cast<StoreSDNode>(N);
11312 Chain = ST->getChain();
11313 Base = ST->getBasePtr();
11314 MMO = ST->getMemOperand();
11316 // If the MMO suggests this isn't a store of a full vector, leave
11317 // things alone. For a built-in, we have to make the change for
11318 // correctness, so if there is a size problem that will be a bug.
11319 if (MMO->getSize() < 16)
11323 case ISD::INTRINSIC_VOID: {
11324 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11325 Chain = Intrin->getChain();
11326 // Intrin->getBasePtr() oddly does not get what we want.
11327 Base = Intrin->getOperand(3);
11328 MMO = Intrin->getMemOperand();
11334 SDValue Src = N->getOperand(SrcOpnd);
11335 MVT VecTy = Src.getValueType().getSimpleVT();
11337 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11338 // aligned and the type is a vector with elements up to 4 bytes
11339 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11340 && VecTy.getScalarSizeInBits() <= 32 ) {
11344 // All stores are done as v2f64 and possible bit cast.
11345 if (VecTy != MVT::v2f64) {
11346 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11347 DCI.AddToWorklist(Src.getNode());
11350 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11351 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11352 DCI.AddToWorklist(Swap.getNode());
11353 Chain = Swap.getValue(1);
11354 SDValue StoreOps[] = { Chain, Swap, Base };
11355 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11356 DAG.getVTList(MVT::Other),
11357 StoreOps, VecTy, MMO);
11358 DCI.AddToWorklist(Store.getNode());
11362 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11363 DAGCombinerInfo &DCI) const {
11364 SelectionDAG &DAG = DCI.DAG;
11366 switch (N->getOpcode()) {
11369 return combineSHL(N, DCI);
11371 return combineSRA(N, DCI);
11373 return combineSRL(N, DCI);
11375 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11376 return N->getOperand(0);
11379 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11380 return N->getOperand(0);
11383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11384 if (C->isNullValue() || // 0 >>s V -> 0.
11385 C->isAllOnesValue()) // -1 >>s V -> -1.
11386 return N->getOperand(0);
11389 case ISD::SIGN_EXTEND:
11390 case ISD::ZERO_EXTEND:
11391 case ISD::ANY_EXTEND:
11392 return DAGCombineExtBoolTrunc(N, DCI);
11393 case ISD::TRUNCATE:
11395 case ISD::SELECT_CC:
11396 return DAGCombineTruncBoolExt(N, DCI);
11397 case ISD::SINT_TO_FP:
11398 case ISD::UINT_TO_FP:
11399 return combineFPToIntToFP(N, DCI);
11401 EVT Op1VT = N->getOperand(1).getValueType();
11402 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11403 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11405 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11406 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11407 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11408 ValidTypeForStoreFltAsInt &&
11409 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11410 SDValue Val = N->getOperand(1).getOperand(0);
11411 if (Val.getValueType() == MVT::f32) {
11412 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11413 DCI.AddToWorklist(Val.getNode());
11415 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11416 DCI.AddToWorklist(Val.getNode());
11418 if (Op1VT == MVT::i32) {
11420 N->getOperand(0), Val, N->getOperand(2),
11421 DAG.getValueType(N->getOperand(1).getValueType())
11424 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11425 DAG.getVTList(MVT::Other), Ops,
11426 cast<StoreSDNode>(N)->getMemoryVT(),
11427 cast<StoreSDNode>(N)->getMemOperand());
11429 unsigned WidthInBytes =
11430 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11431 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11434 N->getOperand(0), Val, N->getOperand(2), WidthConst,
11435 DAG.getValueType(N->getOperand(1).getValueType())
11437 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11438 DAG.getVTList(MVT::Other), Ops,
11439 cast<StoreSDNode>(N)->getMemoryVT(),
11440 cast<StoreSDNode>(N)->getMemOperand());
11443 DCI.AddToWorklist(Val.getNode());
11447 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11448 if (cast<StoreSDNode>(N)->isUnindexed() &&
11449 N->getOperand(1).getOpcode() == ISD::BSWAP &&
11450 N->getOperand(1).getNode()->hasOneUse() &&
11451 (N->getOperand(1).getValueType() == MVT::i32 ||
11452 N->getOperand(1).getValueType() == MVT::i16 ||
11453 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11454 N->getOperand(1).getValueType() == MVT::i64))) {
11455 SDValue BSwapOp = N->getOperand(1).getOperand(0);
11456 // Do an any-extend to 32-bits if this is a half-word input.
11457 if (BSwapOp.getValueType() == MVT::i16)
11458 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11460 // If the type of BSWAP operand is wider than stored memory width
11461 // it need to be shifted to the right side before STBRX.
11462 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11463 if (Op1VT.bitsGT(mVT)) {
11464 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11465 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11466 DAG.getConstant(Shift, dl, MVT::i32));
11467 // Need to truncate if this is a bswap of i64 stored as i32/i16.
11468 if (Op1VT == MVT::i64)
11469 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11473 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11476 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11477 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11478 cast<StoreSDNode>(N)->getMemOperand());
11481 // For little endian, VSX stores require generating xxswapd/lxvd2x.
11482 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11483 EVT VT = N->getOperand(1).getValueType();
11484 if (VT.isSimple()) {
11485 MVT StoreVT = VT.getSimpleVT();
11486 if (Subtarget.needsSwapsForVSXMemOps() &&
11487 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11488 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11489 return expandVSXStoreForLE(N, DCI);
11494 LoadSDNode *LD = cast<LoadSDNode>(N);
11495 EVT VT = LD->getValueType(0);
11497 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11498 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11499 if (VT.isSimple()) {
11500 MVT LoadVT = VT.getSimpleVT();
11501 if (Subtarget.needsSwapsForVSXMemOps() &&
11502 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11503 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11504 return expandVSXLoadForLE(N, DCI);
11507 // We sometimes end up with a 64-bit integer load, from which we extract
11508 // two single-precision floating-point numbers. This happens with
11509 // std::complex<float>, and other similar structures, because of the way we
11510 // canonicalize structure copies. However, if we lack direct moves,
11511 // then the final bitcasts from the extracted integer values to the
11512 // floating-point numbers turn into store/load pairs. Even with direct moves,
11513 // just loading the two floating-point numbers is likely better.
11514 auto ReplaceTwoFloatLoad = [&]() {
11515 if (VT != MVT::i64)
11518 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11522 // We're looking for a sequence like this:
11523 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11524 // t16: i64 = srl t13, Constant:i32<32>
11525 // t17: i32 = truncate t16
11526 // t18: f32 = bitcast t17
11527 // t19: i32 = truncate t13
11528 // t20: f32 = bitcast t19
11530 if (!LD->hasNUsesOfValue(2, 0))
11533 auto UI = LD->use_begin();
11534 while (UI.getUse().getResNo() != 0) ++UI;
11535 SDNode *Trunc = *UI++;
11536 while (UI.getUse().getResNo() != 0) ++UI;
11537 SDNode *RightShift = *UI;
11538 if (Trunc->getOpcode() != ISD::TRUNCATE)
11539 std::swap(Trunc, RightShift);
11541 if (Trunc->getOpcode() != ISD::TRUNCATE ||
11542 Trunc->getValueType(0) != MVT::i32 ||
11543 !Trunc->hasOneUse())
11545 if (RightShift->getOpcode() != ISD::SRL ||
11546 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11547 RightShift->getConstantOperandVal(1) != 32 ||
11548 !RightShift->hasOneUse())
11551 SDNode *Trunc2 = *RightShift->use_begin();
11552 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11553 Trunc2->getValueType(0) != MVT::i32 ||
11554 !Trunc2->hasOneUse())
11557 SDNode *Bitcast = *Trunc->use_begin();
11558 SDNode *Bitcast2 = *Trunc2->use_begin();
11560 if (Bitcast->getOpcode() != ISD::BITCAST ||
11561 Bitcast->getValueType(0) != MVT::f32)
11563 if (Bitcast2->getOpcode() != ISD::BITCAST ||
11564 Bitcast2->getValueType(0) != MVT::f32)
11567 if (Subtarget.isLittleEndian())
11568 std::swap(Bitcast, Bitcast2);
11570 // Bitcast has the second float (in memory-layout order) and Bitcast2
11571 // has the first one.
11573 SDValue BasePtr = LD->getBasePtr();
11574 if (LD->isIndexed()) {
11575 assert(LD->getAddressingMode() == ISD::PRE_INC &&
11576 "Non-pre-inc AM on PPC?");
11578 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11583 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11584 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11585 LD->getPointerInfo(), LD->getAlignment(),
11586 MMOFlags, LD->getAAInfo());
11588 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11589 BasePtr, DAG.getIntPtrConstant(4, dl));
11590 SDValue FloatLoad2 = DAG.getLoad(
11591 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11592 LD->getPointerInfo().getWithOffset(4),
11593 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11595 if (LD->isIndexed()) {
11596 // Note that DAGCombine should re-form any pre-increment load(s) from
11597 // what is produced here if that makes sense.
11598 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11601 DCI.CombineTo(Bitcast2, FloatLoad);
11602 DCI.CombineTo(Bitcast, FloatLoad2);
11604 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11605 SDValue(FloatLoad2.getNode(), 1));
11609 if (ReplaceTwoFloatLoad())
11610 return SDValue(N, 0);
11612 EVT MemVT = LD->getMemoryVT();
11613 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11614 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11615 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11616 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11617 if (LD->isUnindexed() && VT.isVector() &&
11618 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11619 // P8 and later hardware should just use LOAD.
11620 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11621 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11622 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11623 LD->getAlignment() >= ScalarABIAlignment)) &&
11624 LD->getAlignment() < ABIAlignment) {
11625 // This is a type-legal unaligned Altivec or QPX load.
11626 SDValue Chain = LD->getChain();
11627 SDValue Ptr = LD->getBasePtr();
11628 bool isLittleEndian = Subtarget.isLittleEndian();
11630 // This implements the loading of unaligned vectors as described in
11631 // the venerable Apple Velocity Engine overview. Specifically:
11632 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11633 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11635 // The general idea is to expand a sequence of one or more unaligned
11636 // loads into an alignment-based permutation-control instruction (lvsl
11637 // or lvsr), a series of regular vector loads (which always truncate
11638 // their input address to an aligned address), and a series of
11639 // permutations. The results of these permutations are the requested
11640 // loaded values. The trick is that the last "extra" load is not taken
11641 // from the address you might suspect (sizeof(vector) bytes after the
11642 // last requested load), but rather sizeof(vector) - 1 bytes after the
11643 // last requested vector. The point of this is to avoid a page fault if
11644 // the base address happened to be aligned. This works because if the
11645 // base address is aligned, then adding less than a full vector length
11646 // will cause the last vector in the sequence to be (re)loaded.
11647 // Otherwise, the next vector will be fetched as you might suspect was
11650 // We might be able to reuse the permutation generation from
11651 // a different base address offset from this one by an aligned amount.
11652 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11653 // optimization later.
11654 Intrinsic::ID Intr, IntrLD, IntrPerm;
11655 MVT PermCntlTy, PermTy, LDTy;
11656 if (Subtarget.hasAltivec()) {
11657 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
11658 Intrinsic::ppc_altivec_lvsl;
11659 IntrLD = Intrinsic::ppc_altivec_lvx;
11660 IntrPerm = Intrinsic::ppc_altivec_vperm;
11661 PermCntlTy = MVT::v16i8;
11662 PermTy = MVT::v4i32;
11665 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11666 Intrinsic::ppc_qpx_qvlpcls;
11667 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11668 Intrinsic::ppc_qpx_qvlfs;
11669 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11670 PermCntlTy = MVT::v4f64;
11671 PermTy = MVT::v4f64;
11672 LDTy = MemVT.getSimpleVT();
11675 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11677 // Create the new MMO for the new base load. It is like the original MMO,
11678 // but represents an area in memory almost twice the vector size centered
11679 // on the original address. If the address is unaligned, we might start
11680 // reading up to (sizeof(vector)-1) bytes below the address of the
11681 // original unaligned load.
11682 MachineFunction &MF = DAG.getMachineFunction();
11683 MachineMemOperand *BaseMMO =
11684 MF.getMachineMemOperand(LD->getMemOperand(),
11685 -(long)MemVT.getStoreSize()+1,
11686 2*MemVT.getStoreSize()-1);
11688 // Create the new base load.
11690 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11691 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11693 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11694 DAG.getVTList(PermTy, MVT::Other),
11695 BaseLoadOps, LDTy, BaseMMO);
11697 // Note that the value of IncOffset (which is provided to the next
11698 // load's pointer info offset value, and thus used to calculate the
11699 // alignment), and the value of IncValue (which is actually used to
11700 // increment the pointer value) are different! This is because we
11701 // require the next load to appear to be aligned, even though it
11702 // is actually offset from the base pointer by a lesser amount.
11703 int IncOffset = VT.getSizeInBits() / 8;
11704 int IncValue = IncOffset;
11706 // Walk (both up and down) the chain looking for another load at the real
11707 // (aligned) offset (the alignment of the other load does not matter in
11708 // this case). If found, then do not use the offset reduction trick, as
11709 // that will prevent the loads from being later combined (as they would
11710 // otherwise be duplicates).
11711 if (!findConsecutiveLoad(LD, DAG))
11714 SDValue Increment =
11715 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11716 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11718 MachineMemOperand *ExtraMMO =
11719 MF.getMachineMemOperand(LD->getMemOperand(),
11720 1, 2*MemVT.getStoreSize()-1);
11721 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11722 SDValue ExtraLoad =
11723 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11724 DAG.getVTList(PermTy, MVT::Other),
11725 ExtraLoadOps, LDTy, ExtraMMO);
11727 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11728 BaseLoad.getValue(1), ExtraLoad.getValue(1));
11730 // Because vperm has a big-endian bias, we must reverse the order
11731 // of the input vectors and complement the permute control vector
11732 // when generating little endian code. We have already handled the
11733 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11734 // and ExtraLoad here.
11736 if (isLittleEndian)
11737 Perm = BuildIntrinsicOp(IntrPerm,
11738 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11740 Perm = BuildIntrinsicOp(IntrPerm,
11741 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11744 Perm = Subtarget.hasAltivec() ?
11745 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11746 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11747 DAG.getTargetConstant(1, dl, MVT::i64));
11748 // second argument is 1 because this rounding
11749 // is always exact.
11751 // The output of the permutation is our loaded result, the TokenFactor is
11753 DCI.CombineTo(N, Perm, TF);
11754 return SDValue(N, 0);
11758 case ISD::INTRINSIC_WO_CHAIN: {
11759 bool isLittleEndian = Subtarget.isLittleEndian();
11760 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11761 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11762 : Intrinsic::ppc_altivec_lvsl);
11763 if ((IID == Intr ||
11764 IID == Intrinsic::ppc_qpx_qvlpcld ||
11765 IID == Intrinsic::ppc_qpx_qvlpcls) &&
11766 N->getOperand(1)->getOpcode() == ISD::ADD) {
11767 SDValue Add = N->getOperand(1);
11769 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11770 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11772 if (DAG.MaskedValueIsZero(Add->getOperand(1),
11773 APInt::getAllOnesValue(Bits /* alignment */)
11774 .zext(Add.getScalarValueSizeInBits()))) {
11775 SDNode *BasePtr = Add->getOperand(0).getNode();
11776 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11777 UE = BasePtr->use_end();
11779 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11780 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11781 // We've found another LVSL/LVSR, and this address is an aligned
11782 // multiple of that one. The results will be the same, so use the
11783 // one we've just found instead.
11785 return SDValue(*UI, 0);
11790 if (isa<ConstantSDNode>(Add->getOperand(1))) {
11791 SDNode *BasePtr = Add->getOperand(0).getNode();
11792 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11793 UE = BasePtr->use_end(); UI != UE; ++UI) {
11794 if (UI->getOpcode() == ISD::ADD &&
11795 isa<ConstantSDNode>(UI->getOperand(1)) &&
11796 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11797 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11798 (1ULL << Bits) == 0) {
11799 SDNode *OtherAdd = *UI;
11800 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11801 VE = OtherAdd->use_end(); VI != VE; ++VI) {
11802 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11803 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11804 return SDValue(*VI, 0);
11814 case ISD::INTRINSIC_W_CHAIN:
11815 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11816 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11817 if (Subtarget.needsSwapsForVSXMemOps()) {
11818 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11821 case Intrinsic::ppc_vsx_lxvw4x:
11822 case Intrinsic::ppc_vsx_lxvd2x:
11823 return expandVSXLoadForLE(N, DCI);
11827 case ISD::INTRINSIC_VOID:
11828 // For little endian, VSX stores require generating xxswapd/stxvd2x.
11829 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11830 if (Subtarget.needsSwapsForVSXMemOps()) {
11831 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11834 case Intrinsic::ppc_vsx_stxvw4x:
11835 case Intrinsic::ppc_vsx_stxvd2x:
11836 return expandVSXStoreForLE(N, DCI);
11841 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11842 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11843 N->getOperand(0).hasOneUse() &&
11844 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11845 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11846 N->getValueType(0) == MVT::i64))) {
11847 SDValue Load = N->getOperand(0);
11848 LoadSDNode *LD = cast<LoadSDNode>(Load);
11849 // Create the byte-swapping load.
11851 LD->getChain(), // Chain
11852 LD->getBasePtr(), // Ptr
11853 DAG.getValueType(N->getValueType(0)) // VT
11856 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11857 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11858 MVT::i64 : MVT::i32, MVT::Other),
11859 Ops, LD->getMemoryVT(), LD->getMemOperand());
11861 // If this is an i16 load, insert the truncate.
11862 SDValue ResVal = BSLoad;
11863 if (N->getValueType(0) == MVT::i16)
11864 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11866 // First, combine the bswap away. This makes the value produced by the
11868 DCI.CombineTo(N, ResVal);
11870 // Next, combine the load away, we give it a bogus result value but a real
11871 // chain result. The result value is dead because the bswap is dead.
11872 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11874 // Return N so it doesn't get rechecked!
11875 return SDValue(N, 0);
11879 // If a VCMPo node already exists with exactly the same operands as this
11880 // node, use its result instead of this node (VCMPo computes both a CR6 and
11881 // a normal output).
11883 if (!N->getOperand(0).hasOneUse() &&
11884 !N->getOperand(1).hasOneUse() &&
11885 !N->getOperand(2).hasOneUse()) {
11887 // Scan all of the users of the LHS, looking for VCMPo's that match.
11888 SDNode *VCMPoNode = nullptr;
11890 SDNode *LHSN = N->getOperand(0).getNode();
11891 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11893 if (UI->getOpcode() == PPCISD::VCMPo &&
11894 UI->getOperand(1) == N->getOperand(1) &&
11895 UI->getOperand(2) == N->getOperand(2) &&
11896 UI->getOperand(0) == N->getOperand(0)) {
11901 // If there is no VCMPo node, or if the flag value has a single use, don't
11903 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11906 // Look at the (necessarily single) use of the flag value. If it has a
11907 // chain, this transformation is more complex. Note that multiple things
11908 // could use the value result, which we should ignore.
11909 SDNode *FlagUser = nullptr;
11910 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11911 FlagUser == nullptr; ++UI) {
11912 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11913 SDNode *User = *UI;
11914 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11915 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11922 // If the user is a MFOCRF instruction, we know this is safe.
11923 // Otherwise we give up for right now.
11924 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11925 return SDValue(VCMPoNode, 0);
11928 case ISD::BRCOND: {
11929 SDValue Cond = N->getOperand(1);
11930 SDValue Target = N->getOperand(2);
11932 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11933 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11934 Intrinsic::ppc_is_decremented_ctr_nonzero) {
11936 // We now need to make the intrinsic dead (it cannot be instruction
11938 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11939 assert(Cond.getNode()->hasOneUse() &&
11940 "Counter decrement has more than one use");
11942 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11943 N->getOperand(0), Target);
11948 // If this is a branch on an altivec predicate comparison, lower this so
11949 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
11950 // lowering is done pre-legalize, because the legalizer lowers the predicate
11951 // compare down to code that is difficult to reassemble.
11952 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11953 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11955 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11956 // value. If so, pass-through the AND to get to the intrinsic.
11957 if (LHS.getOpcode() == ISD::AND &&
11958 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11959 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11960 Intrinsic::ppc_is_decremented_ctr_nonzero &&
11961 isa<ConstantSDNode>(LHS.getOperand(1)) &&
11962 !isNullConstant(LHS.getOperand(1)))
11963 LHS = LHS.getOperand(0);
11965 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11966 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11967 Intrinsic::ppc_is_decremented_ctr_nonzero &&
11968 isa<ConstantSDNode>(RHS)) {
11969 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11970 "Counter decrement comparison is not EQ or NE");
11972 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11973 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11974 (CC == ISD::SETNE && !Val);
11976 // We now need to make the intrinsic dead (it cannot be instruction
11978 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11979 assert(LHS.getNode()->hasOneUse() &&
11980 "Counter decrement has more than one use");
11982 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11983 N->getOperand(0), N->getOperand(4));
11989 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11990 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11991 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11992 assert(isDot && "Can't compare against a vector result!");
11994 // If this is a comparison against something other than 0/1, then we know
11995 // that the condition is never/always true.
11996 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11997 if (Val != 0 && Val != 1) {
11998 if (CC == ISD::SETEQ) // Cond never true, remove branch.
11999 return N->getOperand(0);
12000 // Always !=, turn it into an unconditional branch.
12001 return DAG.getNode(ISD::BR, dl, MVT::Other,
12002 N->getOperand(0), N->getOperand(4));
12005 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12007 // Create the PPCISD altivec 'dot' comparison node.
12009 LHS.getOperand(2), // LHS of compare
12010 LHS.getOperand(3), // RHS of compare
12011 DAG.getConstant(CompareOpc, dl, MVT::i32)
12013 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12014 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12016 // Unpack the result based on how the target uses it.
12017 PPC::Predicate CompOpc;
12018 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12019 default: // Can't happen, don't crash on invalid number though.
12020 case 0: // Branch on the value of the EQ bit of CR6.
12021 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12023 case 1: // Branch on the inverted value of the EQ bit of CR6.
12024 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12026 case 2: // Branch on the value of the LT bit of CR6.
12027 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12029 case 3: // Branch on the inverted value of the LT bit of CR6.
12030 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12034 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12035 DAG.getConstant(CompOpc, dl, MVT::i32),
12036 DAG.getRegister(PPC::CR6, MVT::i32),
12037 N->getOperand(4), CompNode.getValue(1));
12041 case ISD::BUILD_VECTOR:
12042 return DAGCombineBuildVector(N, DCI);
12049 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12051 std::vector<SDNode *> *Created) const {
12052 // fold (sdiv X, pow2)
12053 EVT VT = N->getValueType(0);
12054 if (VT == MVT::i64 && !Subtarget.isPPC64())
12056 if ((VT != MVT::i32 && VT != MVT::i64) ||
12057 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12061 SDValue N0 = N->getOperand(0);
12063 bool IsNegPow2 = (-Divisor).isPowerOf2();
12064 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12065 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12067 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12069 Created->push_back(Op.getNode());
12072 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12074 Created->push_back(Op.getNode());
12080 //===----------------------------------------------------------------------===//
12081 // Inline Assembly Support
12082 //===----------------------------------------------------------------------===//
12084 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12086 const APInt &DemandedElts,
12087 const SelectionDAG &DAG,
12088 unsigned Depth) const {
12090 switch (Op.getOpcode()) {
12092 case PPCISD::LBRX: {
12093 // lhbrx is known to have the top bits cleared out.
12094 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12095 Known.Zero = 0xFFFF0000;
12098 case ISD::INTRINSIC_WO_CHAIN: {
12099 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12101 case Intrinsic::ppc_altivec_vcmpbfp_p:
12102 case Intrinsic::ppc_altivec_vcmpeqfp_p:
12103 case Intrinsic::ppc_altivec_vcmpequb_p:
12104 case Intrinsic::ppc_altivec_vcmpequh_p:
12105 case Intrinsic::ppc_altivec_vcmpequw_p:
12106 case Intrinsic::ppc_altivec_vcmpequd_p:
12107 case Intrinsic::ppc_altivec_vcmpgefp_p:
12108 case Intrinsic::ppc_altivec_vcmpgtfp_p:
12109 case Intrinsic::ppc_altivec_vcmpgtsb_p:
12110 case Intrinsic::ppc_altivec_vcmpgtsh_p:
12111 case Intrinsic::ppc_altivec_vcmpgtsw_p:
12112 case Intrinsic::ppc_altivec_vcmpgtsd_p:
12113 case Intrinsic::ppc_altivec_vcmpgtub_p:
12114 case Intrinsic::ppc_altivec_vcmpgtuh_p:
12115 case Intrinsic::ppc_altivec_vcmpgtuw_p:
12116 case Intrinsic::ppc_altivec_vcmpgtud_p:
12117 Known.Zero = ~1U; // All bits but the low one are known to be zero.
12124 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12125 switch (Subtarget.getDarwinDirective()) {
12128 case PPC::DIR_PWR4:
12129 case PPC::DIR_PWR5:
12130 case PPC::DIR_PWR5X:
12131 case PPC::DIR_PWR6:
12132 case PPC::DIR_PWR6X:
12133 case PPC::DIR_PWR7:
12134 case PPC::DIR_PWR8:
12135 case PPC::DIR_PWR9: {
12139 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12141 // For small loops (between 5 and 8 instructions), align to a 32-byte
12142 // boundary so that the entire loop fits in one instruction-cache line.
12143 uint64_t LoopSize = 0;
12144 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12145 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12146 LoopSize += TII->getInstSizeInBytes(*J);
12151 if (LoopSize > 16 && LoopSize <= 32)
12158 return TargetLowering::getPrefLoopAlignment(ML);
12161 /// getConstraintType - Given a constraint, return the type of
12162 /// constraint it is for this target.
12163 PPCTargetLowering::ConstraintType
12164 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12165 if (Constraint.size() == 1) {
12166 switch (Constraint[0]) {
12174 return C_RegisterClass;
12176 // FIXME: While Z does indicate a memory constraint, it specifically
12177 // indicates an r+r address (used in conjunction with the 'y' modifier
12178 // in the replacement string). Currently, we're forcing the base
12179 // register to be r0 in the asm printer (which is interpreted as zero)
12180 // and forming the complete address in the second register. This is
12184 } else if (Constraint == "wc") { // individual CR bits.
12185 return C_RegisterClass;
12186 } else if (Constraint == "wa" || Constraint == "wd" ||
12187 Constraint == "wf" || Constraint == "ws") {
12188 return C_RegisterClass; // VSX registers.
12190 return TargetLowering::getConstraintType(Constraint);
12193 /// Examine constraint type and operand type and determine a weight value.
12194 /// This object must already have been set up with the operand type
12195 /// and the current alternative constraint selected.
12196 TargetLowering::ConstraintWeight
12197 PPCTargetLowering::getSingleConstraintMatchWeight(
12198 AsmOperandInfo &info, const char *constraint) const {
12199 ConstraintWeight weight = CW_Invalid;
12200 Value *CallOperandVal = info.CallOperandVal;
12201 // If we don't have a value, we can't do a match,
12202 // but allow it at the lowest weight.
12203 if (!CallOperandVal)
12205 Type *type = CallOperandVal->getType();
12207 // Look at the constraint type.
12208 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12209 return CW_Register; // an individual CR bit.
12210 else if ((StringRef(constraint) == "wa" ||
12211 StringRef(constraint) == "wd" ||
12212 StringRef(constraint) == "wf") &&
12213 type->isVectorTy())
12214 return CW_Register;
12215 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12216 return CW_Register;
12218 switch (*constraint) {
12220 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12223 if (type->isIntegerTy())
12224 weight = CW_Register;
12227 if (type->isFloatTy())
12228 weight = CW_Register;
12231 if (type->isDoubleTy())
12232 weight = CW_Register;
12235 if (type->isVectorTy())
12236 weight = CW_Register;
12239 weight = CW_Register;
12242 weight = CW_Memory;
12248 std::pair<unsigned, const TargetRegisterClass *>
12249 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12250 StringRef Constraint,
12252 if (Constraint.size() == 1) {
12253 // GCC RS6000 Constraint Letters
12254 switch (Constraint[0]) {
12255 case 'b': // R1-R31
12256 if (VT == MVT::i64 && Subtarget.isPPC64())
12257 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12258 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12259 case 'r': // R0-R31
12260 if (VT == MVT::i64 && Subtarget.isPPC64())
12261 return std::make_pair(0U, &PPC::G8RCRegClass);
12262 return std::make_pair(0U, &PPC::GPRCRegClass);
12263 // 'd' and 'f' constraints are both defined to be "the floating point
12264 // registers", where one is for 32-bit and the other for 64-bit. We don't
12265 // really care overly much here so just give them all the same reg classes.
12268 if (VT == MVT::f32 || VT == MVT::i32)
12269 return std::make_pair(0U, &PPC::F4RCRegClass);
12270 if (VT == MVT::f64 || VT == MVT::i64)
12271 return std::make_pair(0U, &PPC::F8RCRegClass);
12272 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12273 return std::make_pair(0U, &PPC::QFRCRegClass);
12274 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12275 return std::make_pair(0U, &PPC::QSRCRegClass);
12278 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12279 return std::make_pair(0U, &PPC::QFRCRegClass);
12280 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12281 return std::make_pair(0U, &PPC::QSRCRegClass);
12282 if (Subtarget.hasAltivec())
12283 return std::make_pair(0U, &PPC::VRRCRegClass);
12285 return std::make_pair(0U, &PPC::CRRCRegClass);
12287 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12288 // An individual CR bit.
12289 return std::make_pair(0U, &PPC::CRBITRCRegClass);
12290 } else if ((Constraint == "wa" || Constraint == "wd" ||
12291 Constraint == "wf") && Subtarget.hasVSX()) {
12292 return std::make_pair(0U, &PPC::VSRCRegClass);
12293 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12294 if (VT == MVT::f32 && Subtarget.hasP8Vector())
12295 return std::make_pair(0U, &PPC::VSSRCRegClass);
12297 return std::make_pair(0U, &PPC::VSFRCRegClass);
12300 std::pair<unsigned, const TargetRegisterClass *> R =
12301 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12303 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12304 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12305 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12307 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12308 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12309 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12310 PPC::GPRCRegClass.contains(R.first))
12311 return std::make_pair(TRI->getMatchingSuperReg(R.first,
12312 PPC::sub_32, &PPC::G8RCRegClass),
12313 &PPC::G8RCRegClass);
12315 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12316 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12317 R.first = PPC::CR0;
12318 R.second = &PPC::CRRCRegClass;
12324 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12325 /// vector. If it is invalid, don't add anything to Ops.
12326 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12327 std::string &Constraint,
12328 std::vector<SDValue>&Ops,
12329 SelectionDAG &DAG) const {
12332 // Only support length 1 constraints.
12333 if (Constraint.length() > 1) return;
12335 char Letter = Constraint[0];
12346 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12347 if (!CST) return; // Must be an immediate to match.
12349 int64_t Value = CST->getSExtValue();
12350 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12351 // numbers are printed as such.
12353 default: llvm_unreachable("Unknown constraint letter!");
12354 case 'I': // "I" is a signed 16-bit constant.
12355 if (isInt<16>(Value))
12356 Result = DAG.getTargetConstant(Value, dl, TCVT);
12358 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
12359 if (isShiftedUInt<16, 16>(Value))
12360 Result = DAG.getTargetConstant(Value, dl, TCVT);
12362 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
12363 if (isShiftedInt<16, 16>(Value))
12364 Result = DAG.getTargetConstant(Value, dl, TCVT);
12366 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
12367 if (isUInt<16>(Value))
12368 Result = DAG.getTargetConstant(Value, dl, TCVT);
12370 case 'M': // "M" is a constant that is greater than 31.
12372 Result = DAG.getTargetConstant(Value, dl, TCVT);
12374 case 'N': // "N" is a positive constant that is an exact power of two.
12375 if (Value > 0 && isPowerOf2_64(Value))
12376 Result = DAG.getTargetConstant(Value, dl, TCVT);
12378 case 'O': // "O" is the constant zero.
12380 Result = DAG.getTargetConstant(Value, dl, TCVT);
12382 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
12383 if (isInt<16>(-Value))
12384 Result = DAG.getTargetConstant(Value, dl, TCVT);
12391 if (Result.getNode()) {
12392 Ops.push_back(Result);
12396 // Handle standard constraint letters.
12397 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12400 // isLegalAddressingMode - Return true if the addressing mode represented
12401 // by AM is legal for this target, for a load/store of the specified type.
12402 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12403 const AddrMode &AM, Type *Ty,
12404 unsigned AS) const {
12405 // PPC does not allow r+i addressing modes for vectors!
12406 if (Ty->isVectorTy() && AM.BaseOffs != 0)
12409 // PPC allows a sign-extended 16-bit immediate field.
12410 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12413 // No global is ever allowed as a base.
12417 // PPC only support r+r,
12418 switch (AM.Scale) {
12419 case 0: // "r+i" or just "i", depending on HasBaseReg.
12422 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
12424 // Otherwise we have r+r or r+i.
12427 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
12429 // Allow 2*r as r+r.
12432 // No other scales are supported.
12439 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12440 SelectionDAG &DAG) const {
12441 MachineFunction &MF = DAG.getMachineFunction();
12442 MachineFrameInfo &MFI = MF.getFrameInfo();
12443 MFI.setReturnAddressIsTaken(true);
12445 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12449 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12451 // Make sure the function does not optimize away the store of the RA to
12453 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12454 FuncInfo->setLRStoreRequired();
12455 bool isPPC64 = Subtarget.isPPC64();
12456 auto PtrVT = getPointerTy(MF.getDataLayout());
12459 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12461 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12462 isPPC64 ? MVT::i64 : MVT::i32);
12463 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12464 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12465 MachinePointerInfo());
12468 // Just load the return address off the stack.
12469 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12470 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12471 MachinePointerInfo());
12474 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12475 SelectionDAG &DAG) const {
12477 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12479 MachineFunction &MF = DAG.getMachineFunction();
12480 MachineFrameInfo &MFI = MF.getFrameInfo();
12481 MFI.setFrameAddressIsTaken(true);
12483 EVT PtrVT = getPointerTy(MF.getDataLayout());
12484 bool isPPC64 = PtrVT == MVT::i64;
12486 // Naked functions never have a frame pointer, and so we use r1. For all
12487 // other functions, this decision must be delayed until during PEI.
12489 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12490 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12492 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12494 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12497 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12498 FrameAddr, MachinePointerInfo());
12502 // FIXME? Maybe this could be a TableGen attribute on some registers and
12503 // this table could be generated automatically from RegInfo.
12504 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12505 SelectionDAG &DAG) const {
12506 bool isPPC64 = Subtarget.isPPC64();
12507 bool isDarwinABI = Subtarget.isDarwinABI();
12509 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12510 (!isPPC64 && VT != MVT::i32))
12511 report_fatal_error("Invalid register global variable type");
12513 bool is64Bit = isPPC64 && VT == MVT::i64;
12514 unsigned Reg = StringSwitch<unsigned>(RegName)
12515 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12516 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12517 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12518 (is64Bit ? PPC::X13 : PPC::R13))
12523 report_fatal_error("Invalid register name global variable");
12527 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12528 // The PowerPC target isn't yet aware of offsets.
12532 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12534 unsigned Intrinsic) const {
12535 switch (Intrinsic) {
12536 case Intrinsic::ppc_qpx_qvlfd:
12537 case Intrinsic::ppc_qpx_qvlfs:
12538 case Intrinsic::ppc_qpx_qvlfcd:
12539 case Intrinsic::ppc_qpx_qvlfcs:
12540 case Intrinsic::ppc_qpx_qvlfiwa:
12541 case Intrinsic::ppc_qpx_qvlfiwz:
12542 case Intrinsic::ppc_altivec_lvx:
12543 case Intrinsic::ppc_altivec_lvxl:
12544 case Intrinsic::ppc_altivec_lvebx:
12545 case Intrinsic::ppc_altivec_lvehx:
12546 case Intrinsic::ppc_altivec_lvewx:
12547 case Intrinsic::ppc_vsx_lxvd2x:
12548 case Intrinsic::ppc_vsx_lxvw4x: {
12550 switch (Intrinsic) {
12551 case Intrinsic::ppc_altivec_lvebx:
12554 case Intrinsic::ppc_altivec_lvehx:
12557 case Intrinsic::ppc_altivec_lvewx:
12560 case Intrinsic::ppc_vsx_lxvd2x:
12563 case Intrinsic::ppc_qpx_qvlfd:
12566 case Intrinsic::ppc_qpx_qvlfs:
12569 case Intrinsic::ppc_qpx_qvlfcd:
12572 case Intrinsic::ppc_qpx_qvlfcs:
12580 Info.opc = ISD::INTRINSIC_W_CHAIN;
12582 Info.ptrVal = I.getArgOperand(0);
12583 Info.offset = -VT.getStoreSize()+1;
12584 Info.size = 2*VT.getStoreSize()-1;
12587 Info.readMem = true;
12588 Info.writeMem = false;
12591 case Intrinsic::ppc_qpx_qvlfda:
12592 case Intrinsic::ppc_qpx_qvlfsa:
12593 case Intrinsic::ppc_qpx_qvlfcda:
12594 case Intrinsic::ppc_qpx_qvlfcsa:
12595 case Intrinsic::ppc_qpx_qvlfiwaa:
12596 case Intrinsic::ppc_qpx_qvlfiwza: {
12598 switch (Intrinsic) {
12599 case Intrinsic::ppc_qpx_qvlfda:
12602 case Intrinsic::ppc_qpx_qvlfsa:
12605 case Intrinsic::ppc_qpx_qvlfcda:
12608 case Intrinsic::ppc_qpx_qvlfcsa:
12616 Info.opc = ISD::INTRINSIC_W_CHAIN;
12618 Info.ptrVal = I.getArgOperand(0);
12620 Info.size = VT.getStoreSize();
12623 Info.readMem = true;
12624 Info.writeMem = false;
12627 case Intrinsic::ppc_qpx_qvstfd:
12628 case Intrinsic::ppc_qpx_qvstfs:
12629 case Intrinsic::ppc_qpx_qvstfcd:
12630 case Intrinsic::ppc_qpx_qvstfcs:
12631 case Intrinsic::ppc_qpx_qvstfiw:
12632 case Intrinsic::ppc_altivec_stvx:
12633 case Intrinsic::ppc_altivec_stvxl:
12634 case Intrinsic::ppc_altivec_stvebx:
12635 case Intrinsic::ppc_altivec_stvehx:
12636 case Intrinsic::ppc_altivec_stvewx:
12637 case Intrinsic::ppc_vsx_stxvd2x:
12638 case Intrinsic::ppc_vsx_stxvw4x: {
12640 switch (Intrinsic) {
12641 case Intrinsic::ppc_altivec_stvebx:
12644 case Intrinsic::ppc_altivec_stvehx:
12647 case Intrinsic::ppc_altivec_stvewx:
12650 case Intrinsic::ppc_vsx_stxvd2x:
12653 case Intrinsic::ppc_qpx_qvstfd:
12656 case Intrinsic::ppc_qpx_qvstfs:
12659 case Intrinsic::ppc_qpx_qvstfcd:
12662 case Intrinsic::ppc_qpx_qvstfcs:
12670 Info.opc = ISD::INTRINSIC_VOID;
12672 Info.ptrVal = I.getArgOperand(1);
12673 Info.offset = -VT.getStoreSize()+1;
12674 Info.size = 2*VT.getStoreSize()-1;
12677 Info.readMem = false;
12678 Info.writeMem = true;
12681 case Intrinsic::ppc_qpx_qvstfda:
12682 case Intrinsic::ppc_qpx_qvstfsa:
12683 case Intrinsic::ppc_qpx_qvstfcda:
12684 case Intrinsic::ppc_qpx_qvstfcsa:
12685 case Intrinsic::ppc_qpx_qvstfiwa: {
12687 switch (Intrinsic) {
12688 case Intrinsic::ppc_qpx_qvstfda:
12691 case Intrinsic::ppc_qpx_qvstfsa:
12694 case Intrinsic::ppc_qpx_qvstfcda:
12697 case Intrinsic::ppc_qpx_qvstfcsa:
12705 Info.opc = ISD::INTRINSIC_VOID;
12707 Info.ptrVal = I.getArgOperand(1);
12709 Info.size = VT.getStoreSize();
12712 Info.readMem = false;
12713 Info.writeMem = true;
12723 /// getOptimalMemOpType - Returns the target specific optimal type for load
12724 /// and store operations as a result of memset, memcpy, and memmove
12725 /// lowering. If DstAlign is zero that means it's safe to destination
12726 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12727 /// means there isn't a need to check it against alignment requirement,
12728 /// probably because the source does not need to be loaded. If 'IsMemset' is
12729 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12730 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12731 /// source is constant so it does not need to be loaded.
12732 /// It returns EVT::Other if the type should be determined using generic
12733 /// target-independent logic.
12734 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12735 unsigned DstAlign, unsigned SrcAlign,
12736 bool IsMemset, bool ZeroMemset,
12738 MachineFunction &MF) const {
12739 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12740 const Function *F = MF.getFunction();
12741 // When expanding a memset, require at least two QPX instructions to cover
12742 // the cost of loading the value to be stored from the constant pool.
12743 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12744 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12745 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12749 // We should use Altivec/VSX loads and stores when available. For unaligned
12750 // addresses, unaligned VSX loads are only fast starting with the P8.
12751 if (Subtarget.hasAltivec() && Size >= 16 &&
12752 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12753 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12757 if (Subtarget.isPPC64()) {
12764 /// \brief Returns true if it is beneficial to convert a load of a constant
12765 /// to just the constant itself.
12766 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12768 assert(Ty->isIntegerTy());
12770 unsigned BitSize = Ty->getPrimitiveSizeInBits();
12771 return !(BitSize == 0 || BitSize > 64);
12774 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12775 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12777 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12778 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12779 return NumBits1 == 64 && NumBits2 == 32;
12782 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12783 if (!VT1.isInteger() || !VT2.isInteger())
12785 unsigned NumBits1 = VT1.getSizeInBits();
12786 unsigned NumBits2 = VT2.getSizeInBits();
12787 return NumBits1 == 64 && NumBits2 == 32;
12790 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12791 // Generally speaking, zexts are not free, but they are free when they can be
12792 // folded with other operations.
12793 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12794 EVT MemVT = LD->getMemoryVT();
12795 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12796 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12797 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12798 LD->getExtensionType() == ISD::ZEXTLOAD))
12802 // FIXME: Add other cases...
12803 // - 32-bit shifts with a zext to i64
12804 // - zext after ctlz, bswap, etc.
12805 // - zext after and by a constant mask
12807 return TargetLowering::isZExtFree(Val, VT2);
12810 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12811 assert(VT.isFloatingPoint());
12815 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12816 return isInt<16>(Imm) || isUInt<16>(Imm);
12819 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12820 return isInt<16>(Imm) || isUInt<16>(Imm);
12823 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12826 bool *Fast) const {
12827 if (DisablePPCUnaligned)
12830 // PowerPC supports unaligned memory access for simple non-vector types.
12831 // Although accessing unaligned addresses is not as efficient as accessing
12832 // aligned addresses, it is generally more efficient than manual expansion,
12833 // and generally only traps for software emulation when crossing page
12836 if (!VT.isSimple())
12839 if (VT.getSimpleVT().isVector()) {
12840 if (Subtarget.hasVSX()) {
12841 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12842 VT != MVT::v4f32 && VT != MVT::v4i32)
12849 if (VT == MVT::ppcf128)
12858 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12859 VT = VT.getScalarType();
12861 if (!VT.isSimple())
12864 switch (VT.getSimpleVT().SimpleTy) {
12876 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12877 // LR is a callee-save register, but we must treat it as clobbered by any call
12878 // site. Hence we include LR in the scratch registers, which are in turn added
12879 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12880 // to CTR, which is used by any indirect call.
12881 static const MCPhysReg ScratchRegs[] = {
12882 PPC::X12, PPC::LR8, PPC::CTR8, 0
12885 return ScratchRegs;
12888 unsigned PPCTargetLowering::getExceptionPointerRegister(
12889 const Constant *PersonalityFn) const {
12890 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12893 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12894 const Constant *PersonalityFn) const {
12895 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12899 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12900 EVT VT , unsigned DefinedValues) const {
12901 if (VT == MVT::v2i64)
12902 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12904 if (Subtarget.hasVSX() || Subtarget.hasQPX())
12907 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12910 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12911 if (DisableILPPref || Subtarget.enableMachineScheduler())
12912 return TargetLowering::getSchedulingPreference(N);
12917 // Create a fast isel object.
12919 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12920 const TargetLibraryInfo *LibInfo) const {
12921 return PPC::createFastISel(FuncInfo, LibInfo);
12924 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12925 if (Subtarget.isDarwinABI()) return;
12926 if (!Subtarget.isPPC64()) return;
12928 // Update IsSplitCSR in PPCFunctionInfo
12929 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12930 PFI->setIsSplitCSR(true);
12933 void PPCTargetLowering::insertCopiesSplitCSR(
12934 MachineBasicBlock *Entry,
12935 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12936 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12937 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12941 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12942 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12943 MachineBasicBlock::iterator MBBI = Entry->begin();
12944 for (const MCPhysReg *I = IStart; *I; ++I) {
12945 const TargetRegisterClass *RC = nullptr;
12946 if (PPC::G8RCRegClass.contains(*I))
12947 RC = &PPC::G8RCRegClass;
12948 else if (PPC::F8RCRegClass.contains(*I))
12949 RC = &PPC::F8RCRegClass;
12950 else if (PPC::CRRCRegClass.contains(*I))
12951 RC = &PPC::CRRCRegClass;
12952 else if (PPC::VRRCRegClass.contains(*I))
12953 RC = &PPC::VRRCRegClass;
12955 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12957 unsigned NewVR = MRI->createVirtualRegister(RC);
12958 // Create copy from CSR to a virtual register.
12959 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12960 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12961 // nounwind. If we want to generalize this later, we may need to emit
12962 // CFI pseudo-instructions.
12963 assert(Entry->getParent()->getFunction()->hasFnAttribute(
12964 Attribute::NoUnwind) &&
12965 "Function should be nounwind in insertCopiesSplitCSR!");
12966 Entry->addLiveIn(*I);
12967 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12970 // Insert the copy-back instructions right before the terminator
12971 for (auto *Exit : Exits)
12972 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12973 TII->get(TargetOpcode::COPY), *I)
12978 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12979 bool PPCTargetLowering::useLoadStackGuardNode() const {
12980 if (!Subtarget.isTargetLinux())
12981 return TargetLowering::useLoadStackGuardNode();
12985 // Override to disable global variable loading on Linux.
12986 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12987 if (!Subtarget.isTargetLinux())
12988 return TargetLowering::insertSSPDeclarations(M);
12991 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12992 if (!VT.isSimple() || !Subtarget.hasVSX())
12995 switch(VT.getSimpleVT().SimpleTy) {
12997 // For FP types that are currently not supported by PPC backend, return
12998 // false. Examples: f16, f80.
13003 return Imm.isPosZero();
13007 // For vector shift operation op, fold
13008 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13009 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13010 SelectionDAG &DAG) {
13011 SDValue N0 = N->getOperand(0);
13012 SDValue N1 = N->getOperand(1);
13013 EVT VT = N0.getValueType();
13014 unsigned OpSizeInBits = VT.getScalarSizeInBits();
13015 unsigned Opcode = N->getOpcode();
13016 unsigned TargetOpcode;
13020 llvm_unreachable("Unexpected shift operation");
13022 TargetOpcode = PPCISD::SHL;
13025 TargetOpcode = PPCISD::SRL;
13028 TargetOpcode = PPCISD::SRA;
13032 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13033 N1->getOpcode() == ISD::AND)
13034 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13035 if (Mask->getZExtValue() == OpSizeInBits - 1)
13036 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13041 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13042 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13048 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13049 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13055 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13056 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))