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 "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61 const PPCSubtarget &STI)
62 : TargetLowering(TM), Subtarget(STI) {
63 // Use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(true);
65 setUseUnderscoreLongJmp(true);
67 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68 // arguments are at least 4/8 bytes aligned.
69 bool isPPC64 = Subtarget.isPPC64();
70 setMinStackArgumentAlignment(isPPC64 ? 8:4);
72 // Set up the register classes.
73 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78 for (MVT VT : MVT::integer_valuetypes()) {
79 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
83 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
85 // PowerPC has pre-inc load and store's.
86 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
101 if (Subtarget.useCRBits()) {
102 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
104 if (isPPC64 || Subtarget.hasFPCVT()) {
105 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107 isPPC64 ? MVT::i64 : MVT::i32);
108 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
110 isPPC64 ? MVT::i64 : MVT::i32);
112 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
116 // PowerPC does not support direct load / store of condition registers
117 setOperationAction(ISD::LOAD, MVT::i1, Custom);
118 setOperationAction(ISD::STORE, MVT::i1, Custom);
120 // FIXME: Remove this once the ANDI glue bug is fixed:
122 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
124 for (MVT VT : MVT::integer_valuetypes()) {
125 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127 setTruncStoreAction(VT, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget.hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget.hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185 Subtarget.hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget.hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget.hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget.hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget.useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget.useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget.useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget.isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget.isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget.has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (Subtarget.hasFPCVT()) {
371 if (Subtarget.has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget.use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget.hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (MVT VT : MVT::vector_valuetypes()) {
404 // add/sub are legal for all supported vector VT's.
405 setOperationAction(ISD::ADD , VT, Legal);
406 setOperationAction(ISD::SUB , VT, Legal);
408 // Vector instructions introduced in P8
409 if (Subtarget.hasP8Altivec()) {
410 setOperationAction(ISD::CTPOP, VT, Legal);
411 setOperationAction(ISD::CTLZ, VT, Legal);
414 setOperationAction(ISD::CTPOP, VT, Expand);
415 setOperationAction(ISD::CTLZ, VT, Expand);
418 // We promote all shuffles to v16i8.
419 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
422 // We promote all non-typed operations to v4i32.
423 setOperationAction(ISD::AND , VT, Promote);
424 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
425 setOperationAction(ISD::OR , VT, Promote);
426 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
427 setOperationAction(ISD::XOR , VT, Promote);
428 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
429 setOperationAction(ISD::LOAD , VT, Promote);
430 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
431 setOperationAction(ISD::SELECT, VT, Promote);
432 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433 setOperationAction(ISD::STORE, VT, Promote);
434 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
436 // No other operations are legal.
437 setOperationAction(ISD::MUL , VT, Expand);
438 setOperationAction(ISD::SDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UDIV, VT, Expand);
441 setOperationAction(ISD::UREM, VT, Expand);
442 setOperationAction(ISD::FDIV, VT, Expand);
443 setOperationAction(ISD::FREM, VT, Expand);
444 setOperationAction(ISD::FNEG, VT, Expand);
445 setOperationAction(ISD::FSQRT, VT, Expand);
446 setOperationAction(ISD::FLOG, VT, Expand);
447 setOperationAction(ISD::FLOG10, VT, Expand);
448 setOperationAction(ISD::FLOG2, VT, Expand);
449 setOperationAction(ISD::FEXP, VT, Expand);
450 setOperationAction(ISD::FEXP2, VT, Expand);
451 setOperationAction(ISD::FSIN, VT, Expand);
452 setOperationAction(ISD::FCOS, VT, Expand);
453 setOperationAction(ISD::FABS, VT, Expand);
454 setOperationAction(ISD::FPOWI, VT, Expand);
455 setOperationAction(ISD::FFLOOR, VT, Expand);
456 setOperationAction(ISD::FCEIL, VT, Expand);
457 setOperationAction(ISD::FTRUNC, VT, Expand);
458 setOperationAction(ISD::FRINT, VT, Expand);
459 setOperationAction(ISD::FNEARBYINT, VT, Expand);
460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463 setOperationAction(ISD::MULHU, VT, Expand);
464 setOperationAction(ISD::MULHS, VT, Expand);
465 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467 setOperationAction(ISD::UDIVREM, VT, Expand);
468 setOperationAction(ISD::SDIVREM, VT, Expand);
469 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470 setOperationAction(ISD::FPOW, VT, Expand);
471 setOperationAction(ISD::BSWAP, VT, Expand);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473 setOperationAction(ISD::CTTZ, VT, Expand);
474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475 setOperationAction(ISD::VSELECT, VT, Expand);
476 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
478 for (MVT InnerVT : MVT::vector_valuetypes()) {
479 setTruncStoreAction(VT, InnerVT, Expand);
480 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
486 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487 // with merges, splats, etc.
488 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
490 setOperationAction(ISD::AND , MVT::v4i32, Legal);
491 setOperationAction(ISD::OR , MVT::v4i32, Legal);
492 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
493 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
494 setOperationAction(ISD::SELECT, MVT::v4i32,
495 Subtarget.useCRBits() ? Legal : Expand);
496 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
506 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
511 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
514 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
519 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
523 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
524 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
526 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
527 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
528 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
529 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
531 // Altivec does not contain unordered floating-point compare instructions
532 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
535 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
537 if (Subtarget.hasVSX()) {
538 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
541 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
547 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
549 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
552 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
561 // Share the Altivec comparison restrictions.
562 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
567 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
568 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
570 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
572 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
574 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
575 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
577 // VSX v2i64 only supports non-arithmetic operations.
578 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
579 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
581 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
582 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
583 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
585 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
587 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
588 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
589 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
590 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
592 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
594 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
595 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
596 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
597 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
599 // Vector operation legalization checks the result type of
600 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
601 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
602 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
603 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
604 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
606 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
609 if (Subtarget.hasP8Altivec())
610 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
613 if (Subtarget.hasQPX()) {
614 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
615 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
616 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
617 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
619 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
620 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
622 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
623 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
625 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
626 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
628 if (!Subtarget.useCRBits())
629 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
630 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
632 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
633 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
634 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
635 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
636 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
637 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
640 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
641 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
643 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
644 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
645 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
647 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
648 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
649 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
650 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
651 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
652 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
653 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
654 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
655 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
656 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
657 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
659 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
660 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
662 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
663 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
665 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
667 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
668 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
669 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
670 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
672 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
673 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
675 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
676 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
678 if (!Subtarget.useCRBits())
679 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
680 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
682 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
683 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
684 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
685 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
686 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
687 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
688 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
690 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
691 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
693 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
694 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
695 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
696 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
697 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
698 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
699 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
700 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
701 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
702 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
703 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
705 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
706 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
708 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
709 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
711 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
713 setOperationAction(ISD::AND , MVT::v4i1, Legal);
714 setOperationAction(ISD::OR , MVT::v4i1, Legal);
715 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
717 if (!Subtarget.useCRBits())
718 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
719 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
721 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
722 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
724 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
725 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
726 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
727 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
728 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
729 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
730 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
732 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
733 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
735 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
737 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
738 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
739 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
740 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
742 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
743 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
744 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
745 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
747 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
748 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
750 // These need to set FE_INEXACT, and so cannot be vectorized here.
751 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
752 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
754 if (TM.Options.UnsafeFPMath) {
755 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
756 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
758 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
759 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
761 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
762 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
764 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
765 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
769 if (Subtarget.has64BitSupport())
770 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
772 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
775 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
776 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
779 setBooleanContents(ZeroOrOneBooleanContent);
781 if (Subtarget.hasAltivec()) {
782 // Altivec instructions set fields to all zeros or all ones.
783 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
787 // These libcalls are not available in 32-bit.
788 setLibcallName(RTLIB::SHL_I128, nullptr);
789 setLibcallName(RTLIB::SRL_I128, nullptr);
790 setLibcallName(RTLIB::SRA_I128, nullptr);
794 setStackPointerRegisterToSaveRestore(PPC::X1);
795 setExceptionPointerRegister(PPC::X3);
796 setExceptionSelectorRegister(PPC::X4);
798 setStackPointerRegisterToSaveRestore(PPC::R1);
799 setExceptionPointerRegister(PPC::R3);
800 setExceptionSelectorRegister(PPC::R4);
803 // We have target-specific dag combine patterns for the following nodes:
804 setTargetDAGCombine(ISD::SINT_TO_FP);
805 if (Subtarget.hasFPCVT())
806 setTargetDAGCombine(ISD::UINT_TO_FP);
807 setTargetDAGCombine(ISD::LOAD);
808 setTargetDAGCombine(ISD::STORE);
809 setTargetDAGCombine(ISD::BR_CC);
810 if (Subtarget.useCRBits())
811 setTargetDAGCombine(ISD::BRCOND);
812 setTargetDAGCombine(ISD::BSWAP);
813 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
814 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
815 setTargetDAGCombine(ISD::INTRINSIC_VOID);
817 setTargetDAGCombine(ISD::SIGN_EXTEND);
818 setTargetDAGCombine(ISD::ZERO_EXTEND);
819 setTargetDAGCombine(ISD::ANY_EXTEND);
821 if (Subtarget.useCRBits()) {
822 setTargetDAGCombine(ISD::TRUNCATE);
823 setTargetDAGCombine(ISD::SETCC);
824 setTargetDAGCombine(ISD::SELECT_CC);
827 // Use reciprocal estimates.
828 if (TM.Options.UnsafeFPMath) {
829 setTargetDAGCombine(ISD::FDIV);
830 setTargetDAGCombine(ISD::FSQRT);
833 // Darwin long double math library functions have $LDBL128 appended.
834 if (Subtarget.isDarwin()) {
835 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
836 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
837 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
838 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
839 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
840 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
841 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
842 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
843 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
844 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
847 // With 32 condition bits, we don't need to sink (and duplicate) compares
848 // aggressively in CodeGenPrep.
849 if (Subtarget.useCRBits()) {
850 setHasMultipleConditionRegisters();
851 setJumpIsExpensive();
854 setMinFunctionAlignment(2);
855 if (Subtarget.isDarwin())
856 setPrefFunctionAlignment(4);
858 switch (Subtarget.getDarwinDirective()) {
862 case PPC::DIR_E500mc:
871 setPrefFunctionAlignment(4);
872 setPrefLoopAlignment(4);
876 setInsertFencesForAtomic(true);
878 if (Subtarget.enableMachineScheduler())
879 setSchedulingPreference(Sched::Source);
881 setSchedulingPreference(Sched::Hybrid);
883 computeRegisterProperties();
885 // The Freescale cores do better with aggressive inlining of memcpy and
886 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
887 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
888 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
889 MaxStoresPerMemset = 32;
890 MaxStoresPerMemsetOptSize = 16;
891 MaxStoresPerMemcpy = 32;
892 MaxStoresPerMemcpyOptSize = 8;
893 MaxStoresPerMemmove = 32;
894 MaxStoresPerMemmoveOptSize = 8;
898 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
899 /// the desired ByVal argument alignment.
900 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
901 unsigned MaxMaxAlign) {
902 if (MaxAlign == MaxMaxAlign)
904 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
905 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
907 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
909 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
910 unsigned EltAlign = 0;
911 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
912 if (EltAlign > MaxAlign)
914 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
915 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
916 unsigned EltAlign = 0;
917 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
918 if (EltAlign > MaxAlign)
920 if (MaxAlign == MaxMaxAlign)
926 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
927 /// function arguments in the caller parameter area.
928 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
929 // Darwin passes everything on 4 byte boundary.
930 if (Subtarget.isDarwin())
933 // 16byte and wider vectors are passed on 16byte boundary.
934 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
935 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
936 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
937 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
941 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
943 default: return nullptr;
944 case PPCISD::FSEL: return "PPCISD::FSEL";
945 case PPCISD::FCFID: return "PPCISD::FCFID";
946 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
947 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
948 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
949 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
950 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
951 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
952 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
953 case PPCISD::FRE: return "PPCISD::FRE";
954 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
955 case PPCISD::STFIWX: return "PPCISD::STFIWX";
956 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
957 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
958 case PPCISD::VPERM: return "PPCISD::VPERM";
959 case PPCISD::CMPB: return "PPCISD::CMPB";
960 case PPCISD::Hi: return "PPCISD::Hi";
961 case PPCISD::Lo: return "PPCISD::Lo";
962 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
963 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
964 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
965 case PPCISD::SRL: return "PPCISD::SRL";
966 case PPCISD::SRA: return "PPCISD::SRA";
967 case PPCISD::SHL: return "PPCISD::SHL";
968 case PPCISD::CALL: return "PPCISD::CALL";
969 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
970 case PPCISD::MTCTR: return "PPCISD::MTCTR";
971 case PPCISD::BCTRL: return "PPCISD::BCTRL";
972 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
973 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
974 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
975 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
976 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
977 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
978 case PPCISD::VCMP: return "PPCISD::VCMP";
979 case PPCISD::VCMPo: return "PPCISD::VCMPo";
980 case PPCISD::LBRX: return "PPCISD::LBRX";
981 case PPCISD::STBRX: return "PPCISD::STBRX";
982 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
983 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
984 case PPCISD::LARX: return "PPCISD::LARX";
985 case PPCISD::STCX: return "PPCISD::STCX";
986 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
987 case PPCISD::BDNZ: return "PPCISD::BDNZ";
988 case PPCISD::BDZ: return "PPCISD::BDZ";
989 case PPCISD::MFFS: return "PPCISD::MFFS";
990 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
991 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
992 case PPCISD::CR6SET: return "PPCISD::CR6SET";
993 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
994 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
995 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
996 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
997 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
998 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
999 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1000 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1001 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1002 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1003 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1004 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1005 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1006 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1007 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1008 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1009 case PPCISD::SC: return "PPCISD::SC";
1010 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1011 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1012 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1013 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1014 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1015 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1019 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1021 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1023 if (Subtarget.hasQPX())
1024 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1026 return VT.changeVectorElementTypeToInteger();
1029 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1030 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1034 //===----------------------------------------------------------------------===//
1035 // Node matching predicates, for use by the tblgen matching code.
1036 //===----------------------------------------------------------------------===//
1038 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1039 static bool isFloatingPointZero(SDValue Op) {
1040 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1041 return CFP->getValueAPF().isZero();
1042 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1043 // Maybe this has already been legalized into the constant pool?
1044 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1045 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1046 return CFP->getValueAPF().isZero();
1051 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1052 /// true if Op is undef or if it matches the specified value.
1053 static bool isConstantOrUndef(int Op, int Val) {
1054 return Op < 0 || Op == Val;
1057 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1058 /// VPKUHUM instruction.
1059 /// The ShuffleKind distinguishes between big-endian operations with
1060 /// two different inputs (0), either-endian operations with two identical
1061 /// inputs (1), and little-endian operantion with two different inputs (2).
1062 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1063 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1064 SelectionDAG &DAG) {
1065 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1066 if (ShuffleKind == 0) {
1069 for (unsigned i = 0; i != 16; ++i)
1070 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1072 } else if (ShuffleKind == 2) {
1075 for (unsigned i = 0; i != 16; ++i)
1076 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1078 } else if (ShuffleKind == 1) {
1079 unsigned j = IsLE ? 0 : 1;
1080 for (unsigned i = 0; i != 8; ++i)
1081 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1082 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1088 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1089 /// VPKUWUM instruction.
1090 /// The ShuffleKind distinguishes between big-endian operations with
1091 /// two different inputs (0), either-endian operations with two identical
1092 /// inputs (1), and little-endian operantion with two different inputs (2).
1093 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1094 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1095 SelectionDAG &DAG) {
1096 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1097 if (ShuffleKind == 0) {
1100 for (unsigned i = 0; i != 16; i += 2)
1101 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1102 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1104 } else if (ShuffleKind == 2) {
1107 for (unsigned i = 0; i != 16; i += 2)
1108 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1109 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1111 } else if (ShuffleKind == 1) {
1112 unsigned j = IsLE ? 0 : 2;
1113 for (unsigned i = 0; i != 8; i += 2)
1114 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1115 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1116 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1117 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1123 /// isVMerge - Common function, used to match vmrg* shuffles.
1125 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1126 unsigned LHSStart, unsigned RHSStart) {
1127 if (N->getValueType(0) != MVT::v16i8)
1129 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1130 "Unsupported merge size!");
1132 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1133 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1134 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1135 LHSStart+j+i*UnitSize) ||
1136 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1137 RHSStart+j+i*UnitSize))
1143 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1144 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1145 /// The ShuffleKind distinguishes between big-endian merges with two
1146 /// different inputs (0), either-endian merges with two identical inputs (1),
1147 /// and little-endian merges with two different inputs (2). For the latter,
1148 /// the input operands are swapped (see PPCInstrAltivec.td).
1149 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1150 unsigned ShuffleKind, SelectionDAG &DAG) {
1151 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1152 if (ShuffleKind == 1) // unary
1153 return isVMerge(N, UnitSize, 0, 0);
1154 else if (ShuffleKind == 2) // swapped
1155 return isVMerge(N, UnitSize, 0, 16);
1159 if (ShuffleKind == 1) // unary
1160 return isVMerge(N, UnitSize, 8, 8);
1161 else if (ShuffleKind == 0) // normal
1162 return isVMerge(N, UnitSize, 8, 24);
1168 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1169 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1170 /// The ShuffleKind distinguishes between big-endian merges with two
1171 /// different inputs (0), either-endian merges with two identical inputs (1),
1172 /// and little-endian merges with two different inputs (2). For the latter,
1173 /// the input operands are swapped (see PPCInstrAltivec.td).
1174 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1175 unsigned ShuffleKind, SelectionDAG &DAG) {
1176 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1177 if (ShuffleKind == 1) // unary
1178 return isVMerge(N, UnitSize, 8, 8);
1179 else if (ShuffleKind == 2) // swapped
1180 return isVMerge(N, UnitSize, 8, 24);
1184 if (ShuffleKind == 1) // unary
1185 return isVMerge(N, UnitSize, 0, 0);
1186 else if (ShuffleKind == 0) // normal
1187 return isVMerge(N, UnitSize, 0, 16);
1194 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1195 /// amount, otherwise return -1.
1196 /// The ShuffleKind distinguishes between big-endian operations with two
1197 /// different inputs (0), either-endian operations with two identical inputs
1198 /// (1), and little-endian operations with two different inputs (2). For the
1199 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1200 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1201 SelectionDAG &DAG) {
1202 if (N->getValueType(0) != MVT::v16i8)
1205 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1207 // Find the first non-undef value in the shuffle mask.
1209 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1212 if (i == 16) return -1; // all undef.
1214 // Otherwise, check to see if the rest of the elements are consecutively
1215 // numbered from this value.
1216 unsigned ShiftAmt = SVOp->getMaskElt(i);
1217 if (ShiftAmt < i) return -1;
1220 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1222 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1223 // Check the rest of the elements to see if they are consecutive.
1224 for (++i; i != 16; ++i)
1225 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1227 } else if (ShuffleKind == 1) {
1228 // Check the rest of the elements to see if they are consecutive.
1229 for (++i; i != 16; ++i)
1230 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1235 if (ShuffleKind == 2 && isLE)
1236 ShiftAmt = 16 - ShiftAmt;
1241 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1242 /// specifies a splat of a single element that is suitable for input to
1243 /// VSPLTB/VSPLTH/VSPLTW.
1244 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1245 assert(N->getValueType(0) == MVT::v16i8 &&
1246 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1248 // This is a splat operation if each element of the permute is the same, and
1249 // if the value doesn't reference the second vector.
1250 unsigned ElementBase = N->getMaskElt(0);
1252 // FIXME: Handle UNDEF elements too!
1253 if (ElementBase >= 16)
1256 // Check that the indices are consecutive, in the case of a multi-byte element
1257 // splatted with a v16i8 mask.
1258 for (unsigned i = 1; i != EltSize; ++i)
1259 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1262 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1263 if (N->getMaskElt(i) < 0) continue;
1264 for (unsigned j = 0; j != EltSize; ++j)
1265 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1271 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1273 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1274 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1276 APInt APVal, APUndef;
1280 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1281 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1282 return CFP->getValueAPF().isNegZero();
1287 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1288 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1289 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1290 SelectionDAG &DAG) {
1291 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1292 assert(isSplatShuffleMask(SVOp, EltSize));
1293 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1294 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1296 return SVOp->getMaskElt(0) / EltSize;
1299 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1300 /// by using a vspltis[bhw] instruction of the specified element size, return
1301 /// the constant being splatted. The ByteSize field indicates the number of
1302 /// bytes of each element [124] -> [bhw].
1303 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1304 SDValue OpVal(nullptr, 0);
1306 // If ByteSize of the splat is bigger than the element size of the
1307 // build_vector, then we have a case where we are checking for a splat where
1308 // multiple elements of the buildvector are folded together into a single
1309 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1310 unsigned EltSize = 16/N->getNumOperands();
1311 if (EltSize < ByteSize) {
1312 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1313 SDValue UniquedVals[4];
1314 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1316 // See if all of the elements in the buildvector agree across.
1317 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1318 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1319 // If the element isn't a constant, bail fully out.
1320 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1323 if (!UniquedVals[i&(Multiple-1)].getNode())
1324 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1325 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1326 return SDValue(); // no match.
1329 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1330 // either constant or undef values that are identical for each chunk. See
1331 // if these chunks can form into a larger vspltis*.
1333 // Check to see if all of the leading entries are either 0 or -1. If
1334 // neither, then this won't fit into the immediate field.
1335 bool LeadingZero = true;
1336 bool LeadingOnes = true;
1337 for (unsigned i = 0; i != Multiple-1; ++i) {
1338 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1340 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1341 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1343 // Finally, check the least significant entry.
1345 if (!UniquedVals[Multiple-1].getNode())
1346 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1347 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1349 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1352 if (!UniquedVals[Multiple-1].getNode())
1353 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1354 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1355 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1356 return DAG.getTargetConstant(Val, MVT::i32);
1362 // Check to see if this buildvec has a single non-undef value in its elements.
1363 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1364 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1365 if (!OpVal.getNode())
1366 OpVal = N->getOperand(i);
1367 else if (OpVal != N->getOperand(i))
1371 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1373 unsigned ValSizeInBytes = EltSize;
1375 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1376 Value = CN->getZExtValue();
1377 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1378 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1379 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1382 // If the splat value is larger than the element value, then we can never do
1383 // this splat. The only case that we could fit the replicated bits into our
1384 // immediate field for would be zero, and we prefer to use vxor for it.
1385 if (ValSizeInBytes < ByteSize) return SDValue();
1387 // If the element value is larger than the splat value, cut it in half and
1388 // check to see if the two halves are equal. Continue doing this until we
1389 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1390 while (ValSizeInBytes > ByteSize) {
1391 ValSizeInBytes >>= 1;
1393 // If the top half equals the bottom half, we're still ok.
1394 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1395 (Value & ((1 << (8*ValSizeInBytes))-1)))
1399 // Properly sign extend the value.
1400 int MaskVal = SignExtend32(Value, ByteSize * 8);
1402 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1403 if (MaskVal == 0) return SDValue();
1405 // Finally, if this value fits in a 5 bit sext field, return it
1406 if (SignExtend32<5>(MaskVal) == MaskVal)
1407 return DAG.getTargetConstant(MaskVal, MVT::i32);
1411 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1412 /// amount, otherwise return -1.
1413 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1414 EVT VT = N->getValueType(0);
1415 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1418 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1420 // Find the first non-undef value in the shuffle mask.
1422 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1425 if (i == 4) return -1; // all undef.
1427 // Otherwise, check to see if the rest of the elements are consecutively
1428 // numbered from this value.
1429 unsigned ShiftAmt = SVOp->getMaskElt(i);
1430 if (ShiftAmt < i) return -1;
1433 // Check the rest of the elements to see if they are consecutive.
1434 for (++i; i != 4; ++i)
1435 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1441 //===----------------------------------------------------------------------===//
1442 // Addressing Mode Selection
1443 //===----------------------------------------------------------------------===//
1445 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1446 /// or 64-bit immediate, and if the value can be accurately represented as a
1447 /// sign extension from a 16-bit value. If so, this returns true and the
1449 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1450 if (!isa<ConstantSDNode>(N))
1453 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1454 if (N->getValueType(0) == MVT::i32)
1455 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1457 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1459 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1460 return isIntS16Immediate(Op.getNode(), Imm);
1464 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1465 /// can be represented as an indexed [r+r] operation. Returns false if it
1466 /// can be more efficiently represented with [r+imm].
1467 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1469 SelectionDAG &DAG) const {
1471 if (N.getOpcode() == ISD::ADD) {
1472 if (isIntS16Immediate(N.getOperand(1), imm))
1473 return false; // r+i
1474 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1475 return false; // r+i
1477 Base = N.getOperand(0);
1478 Index = N.getOperand(1);
1480 } else if (N.getOpcode() == ISD::OR) {
1481 if (isIntS16Immediate(N.getOperand(1), imm))
1482 return false; // r+i can fold it if we can.
1484 // If this is an or of disjoint bitfields, we can codegen this as an add
1485 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1487 APInt LHSKnownZero, LHSKnownOne;
1488 APInt RHSKnownZero, RHSKnownOne;
1489 DAG.computeKnownBits(N.getOperand(0),
1490 LHSKnownZero, LHSKnownOne);
1492 if (LHSKnownZero.getBoolValue()) {
1493 DAG.computeKnownBits(N.getOperand(1),
1494 RHSKnownZero, RHSKnownOne);
1495 // If all of the bits are known zero on the LHS or RHS, the add won't
1497 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1498 Base = N.getOperand(0);
1499 Index = N.getOperand(1);
1508 // If we happen to be doing an i64 load or store into a stack slot that has
1509 // less than a 4-byte alignment, then the frame-index elimination may need to
1510 // use an indexed load or store instruction (because the offset may not be a
1511 // multiple of 4). The extra register needed to hold the offset comes from the
1512 // register scavenger, and it is possible that the scavenger will need to use
1513 // an emergency spill slot. As a result, we need to make sure that a spill slot
1514 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1516 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1517 // FIXME: This does not handle the LWA case.
1521 // NOTE: We'll exclude negative FIs here, which come from argument
1522 // lowering, because there are no known test cases triggering this problem
1523 // using packed structures (or similar). We can remove this exclusion if
1524 // we find such a test case. The reason why this is so test-case driven is
1525 // because this entire 'fixup' is only to prevent crashes (from the
1526 // register scavenger) on not-really-valid inputs. For example, if we have:
1528 // %b = bitcast i1* %a to i64*
1529 // store i64* a, i64 b
1530 // then the store should really be marked as 'align 1', but is not. If it
1531 // were marked as 'align 1' then the indexed form would have been
1532 // instruction-selected initially, and the problem this 'fixup' is preventing
1533 // won't happen regardless.
1537 MachineFunction &MF = DAG.getMachineFunction();
1538 MachineFrameInfo *MFI = MF.getFrameInfo();
1540 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1544 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1545 FuncInfo->setHasNonRISpills();
1548 /// Returns true if the address N can be represented by a base register plus
1549 /// a signed 16-bit displacement [r+imm], and if it is not better
1550 /// represented as reg+reg. If Aligned is true, only accept displacements
1551 /// suitable for STD and friends, i.e. multiples of 4.
1552 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1555 bool Aligned) const {
1556 // FIXME dl should come from parent load or store, not from address
1558 // If this can be more profitably realized as r+r, fail.
1559 if (SelectAddressRegReg(N, Disp, Base, DAG))
1562 if (N.getOpcode() == ISD::ADD) {
1564 if (isIntS16Immediate(N.getOperand(1), imm) &&
1565 (!Aligned || (imm & 3) == 0)) {
1566 Disp = DAG.getTargetConstant(imm, N.getValueType());
1567 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1568 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1569 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1571 Base = N.getOperand(0);
1573 return true; // [r+i]
1574 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1575 // Match LOAD (ADD (X, Lo(G))).
1576 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1577 && "Cannot handle constant offsets yet!");
1578 Disp = N.getOperand(1).getOperand(0); // The global address.
1579 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1580 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1581 Disp.getOpcode() == ISD::TargetConstantPool ||
1582 Disp.getOpcode() == ISD::TargetJumpTable);
1583 Base = N.getOperand(0);
1584 return true; // [&g+r]
1586 } else if (N.getOpcode() == ISD::OR) {
1588 if (isIntS16Immediate(N.getOperand(1), imm) &&
1589 (!Aligned || (imm & 3) == 0)) {
1590 // If this is an or of disjoint bitfields, we can codegen this as an add
1591 // (for better address arithmetic) if the LHS and RHS of the OR are
1592 // provably disjoint.
1593 APInt LHSKnownZero, LHSKnownOne;
1594 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1596 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1597 // If all of the bits are known zero on the LHS or RHS, the add won't
1599 if (FrameIndexSDNode *FI =
1600 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1601 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1602 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1604 Base = N.getOperand(0);
1606 Disp = DAG.getTargetConstant(imm, N.getValueType());
1610 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1611 // Loading from a constant address.
1613 // If this address fits entirely in a 16-bit sext immediate field, codegen
1616 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1617 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1618 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1619 CN->getValueType(0));
1623 // Handle 32-bit sext immediates with LIS + addr mode.
1624 if ((CN->getValueType(0) == MVT::i32 ||
1625 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1626 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1627 int Addr = (int)CN->getZExtValue();
1629 // Otherwise, break this down into an LIS + disp.
1630 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1632 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1633 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1634 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1639 Disp = DAG.getTargetConstant(0, getPointerTy());
1640 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1641 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1642 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1645 return true; // [r+0]
1648 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1649 /// represented as an indexed [r+r] operation.
1650 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1652 SelectionDAG &DAG) const {
1653 // Check to see if we can easily represent this as an [r+r] address. This
1654 // will fail if it thinks that the address is more profitably represented as
1655 // reg+imm, e.g. where imm = 0.
1656 if (SelectAddressRegReg(N, Base, Index, DAG))
1659 // If the operand is an addition, always emit this as [r+r], since this is
1660 // better (for code size, and execution, as the memop does the add for free)
1661 // than emitting an explicit add.
1662 if (N.getOpcode() == ISD::ADD) {
1663 Base = N.getOperand(0);
1664 Index = N.getOperand(1);
1668 // Otherwise, do it the hard way, using R0 as the base register.
1669 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1675 /// getPreIndexedAddressParts - returns true by value, base pointer and
1676 /// offset pointer and addressing mode by reference if the node's address
1677 /// can be legally represented as pre-indexed load / store address.
1678 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1680 ISD::MemIndexedMode &AM,
1681 SelectionDAG &DAG) const {
1682 if (DisablePPCPreinc) return false;
1688 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1689 Ptr = LD->getBasePtr();
1690 VT = LD->getMemoryVT();
1691 Alignment = LD->getAlignment();
1692 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1693 Ptr = ST->getBasePtr();
1694 VT = ST->getMemoryVT();
1695 Alignment = ST->getAlignment();
1700 // PowerPC doesn't have preinc load/store instructions for vectors (except
1701 // for QPX, which does have preinc r+r forms).
1702 if (VT.isVector()) {
1703 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1705 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1711 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1713 // Common code will reject creating a pre-inc form if the base pointer
1714 // is a frame index, or if N is a store and the base pointer is either
1715 // the same as or a predecessor of the value being stored. Check for
1716 // those situations here, and try with swapped Base/Offset instead.
1719 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1722 SDValue Val = cast<StoreSDNode>(N)->getValue();
1723 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1728 std::swap(Base, Offset);
1734 // LDU/STU can only handle immediates that are a multiple of 4.
1735 if (VT != MVT::i64) {
1736 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1739 // LDU/STU need an address with at least 4-byte alignment.
1743 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1747 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1748 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1749 // sext i32 to i64 when addr mode is r+i.
1750 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1751 LD->getExtensionType() == ISD::SEXTLOAD &&
1752 isa<ConstantSDNode>(Offset))
1760 //===----------------------------------------------------------------------===//
1761 // LowerOperation implementation
1762 //===----------------------------------------------------------------------===//
1764 /// GetLabelAccessInfo - Return true if we should reference labels using a
1765 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1766 static bool GetLabelAccessInfo(const TargetMachine &TM,
1767 const PPCSubtarget &Subtarget,
1768 unsigned &HiOpFlags, unsigned &LoOpFlags,
1769 const GlobalValue *GV = nullptr) {
1770 HiOpFlags = PPCII::MO_HA;
1771 LoOpFlags = PPCII::MO_LO;
1773 // Don't use the pic base if not in PIC relocation model.
1774 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1777 HiOpFlags |= PPCII::MO_PIC_FLAG;
1778 LoOpFlags |= PPCII::MO_PIC_FLAG;
1781 // If this is a reference to a global value that requires a non-lazy-ptr, make
1782 // sure that instruction lowering adds it.
1783 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1784 HiOpFlags |= PPCII::MO_NLP_FLAG;
1785 LoOpFlags |= PPCII::MO_NLP_FLAG;
1787 if (GV->hasHiddenVisibility()) {
1788 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1789 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1796 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1797 SelectionDAG &DAG) {
1798 EVT PtrVT = HiPart.getValueType();
1799 SDValue Zero = DAG.getConstant(0, PtrVT);
1802 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1803 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1805 // With PIC, the first instruction is actually "GR+hi(&G)".
1807 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1808 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1810 // Generate non-pic code that has direct accesses to the constant pool.
1811 // The address of the global is just (hi(&g)+lo(&g)).
1812 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1815 static void setUsesTOCBasePtr(MachineFunction &MF) {
1816 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1817 FuncInfo->setUsesTOCBasePtr();
1820 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1821 setUsesTOCBasePtr(DAG.getMachineFunction());
1824 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1825 SelectionDAG &DAG) const {
1826 EVT PtrVT = Op.getValueType();
1827 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1828 const Constant *C = CP->getConstVal();
1830 // 64-bit SVR4 ABI code is always position-independent.
1831 // The actual address of the GlobalValue is stored in the TOC.
1832 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1833 setUsesTOCBasePtr(DAG);
1834 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1835 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1836 DAG.getRegister(PPC::X2, MVT::i64));
1839 unsigned MOHiFlag, MOLoFlag;
1841 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1843 if (isPIC && Subtarget.isSVR4ABI()) {
1844 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1845 PPCII::MO_PIC_FLAG);
1847 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1848 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1852 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1854 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1855 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1858 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1859 EVT PtrVT = Op.getValueType();
1860 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1862 // 64-bit SVR4 ABI code is always position-independent.
1863 // The actual address of the GlobalValue is stored in the TOC.
1864 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1865 setUsesTOCBasePtr(DAG);
1866 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1867 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1868 DAG.getRegister(PPC::X2, MVT::i64));
1871 unsigned MOHiFlag, MOLoFlag;
1873 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1875 if (isPIC && Subtarget.isSVR4ABI()) {
1876 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1877 PPCII::MO_PIC_FLAG);
1879 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1880 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1883 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1884 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1885 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1888 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1889 SelectionDAG &DAG) const {
1890 EVT PtrVT = Op.getValueType();
1891 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1892 const BlockAddress *BA = BASDN->getBlockAddress();
1894 // 64-bit SVR4 ABI code is always position-independent.
1895 // The actual BlockAddress is stored in the TOC.
1896 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1897 setUsesTOCBasePtr(DAG);
1898 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1899 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1900 DAG.getRegister(PPC::X2, MVT::i64));
1903 unsigned MOHiFlag, MOLoFlag;
1905 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1906 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1907 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1908 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1911 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1912 SelectionDAG &DAG) const {
1914 // FIXME: TLS addresses currently use medium model code sequences,
1915 // which is the most useful form. Eventually support for small and
1916 // large models could be added if users need it, at the cost of
1917 // additional complexity.
1918 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1920 const GlobalValue *GV = GA->getGlobal();
1921 EVT PtrVT = getPointerTy();
1922 bool is64bit = Subtarget.isPPC64();
1923 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1924 PICLevel::Level picLevel = M->getPICLevel();
1926 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1928 if (Model == TLSModel::LocalExec) {
1929 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1930 PPCII::MO_TPREL_HA);
1931 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1932 PPCII::MO_TPREL_LO);
1933 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1934 is64bit ? MVT::i64 : MVT::i32);
1935 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1936 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1939 if (Model == TLSModel::InitialExec) {
1940 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1941 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1945 setUsesTOCBasePtr(DAG);
1946 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1947 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1948 PtrVT, GOTReg, TGA);
1950 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1951 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1952 PtrVT, TGA, GOTPtr);
1953 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1956 if (Model == TLSModel::GeneralDynamic) {
1957 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1960 setUsesTOCBasePtr(DAG);
1961 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1962 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1965 if (picLevel == PICLevel::Small)
1966 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1968 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1970 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1974 if (Model == TLSModel::LocalDynamic) {
1975 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1978 setUsesTOCBasePtr(DAG);
1979 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1980 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1983 if (picLevel == PICLevel::Small)
1984 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1986 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1988 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
1989 PtrVT, GOTPtr, TGA, TGA);
1990 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
1991 PtrVT, TLSAddr, TGA);
1992 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1995 llvm_unreachable("Unknown TLS model!");
1998 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1999 SelectionDAG &DAG) const {
2000 EVT PtrVT = Op.getValueType();
2001 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2003 const GlobalValue *GV = GSDN->getGlobal();
2005 // 64-bit SVR4 ABI code is always position-independent.
2006 // The actual address of the GlobalValue is stored in the TOC.
2007 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2008 setUsesTOCBasePtr(DAG);
2009 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2010 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
2011 DAG.getRegister(PPC::X2, MVT::i64));
2014 unsigned MOHiFlag, MOLoFlag;
2016 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2018 if (isPIC && Subtarget.isSVR4ABI()) {
2019 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2021 PPCII::MO_PIC_FLAG);
2022 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
2023 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
2027 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2029 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2031 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2033 // If the global reference is actually to a non-lazy-pointer, we have to do an
2034 // extra load to get the address of the global.
2035 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2036 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2037 false, false, false, 0);
2041 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2042 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2045 if (Op.getValueType() == MVT::v2i64) {
2046 // When the operands themselves are v2i64 values, we need to do something
2047 // special because VSX has no underlying comparison operations for these.
2048 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2049 // Equality can be handled by casting to the legal type for Altivec
2050 // comparisons, everything else needs to be expanded.
2051 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2052 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2053 DAG.getSetCC(dl, MVT::v4i32,
2054 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2055 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2062 // We handle most of these in the usual way.
2066 // If we're comparing for equality to zero, expose the fact that this is
2067 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2068 // fold the new nodes.
2069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2070 if (C->isNullValue() && CC == ISD::SETEQ) {
2071 EVT VT = Op.getOperand(0).getValueType();
2072 SDValue Zext = Op.getOperand(0);
2073 if (VT.bitsLT(MVT::i32)) {
2075 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2077 unsigned Log2b = Log2_32(VT.getSizeInBits());
2078 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2079 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2080 DAG.getConstant(Log2b, MVT::i32));
2081 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2083 // Leave comparisons against 0 and -1 alone for now, since they're usually
2084 // optimized. FIXME: revisit this when we can custom lower all setcc
2086 if (C->isAllOnesValue() || C->isNullValue())
2090 // If we have an integer seteq/setne, turn it into a compare against zero
2091 // by xor'ing the rhs with the lhs, which is faster than setting a
2092 // condition register, reading it back out, and masking the correct bit. The
2093 // normal approach here uses sub to do this instead of xor. Using xor exposes
2094 // the result to other bit-twiddling opportunities.
2095 EVT LHSVT = Op.getOperand(0).getValueType();
2096 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2097 EVT VT = Op.getValueType();
2098 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2100 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2105 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2106 const PPCSubtarget &Subtarget) const {
2107 SDNode *Node = Op.getNode();
2108 EVT VT = Node->getValueType(0);
2109 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2110 SDValue InChain = Node->getOperand(0);
2111 SDValue VAListPtr = Node->getOperand(1);
2112 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2115 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2118 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2119 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2120 false, false, false, 0);
2121 InChain = GprIndex.getValue(1);
2123 if (VT == MVT::i64) {
2124 // Check if GprIndex is even
2125 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2126 DAG.getConstant(1, MVT::i32));
2127 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2128 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2129 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2130 DAG.getConstant(1, MVT::i32));
2131 // Align GprIndex to be even if it isn't
2132 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2136 // fpr index is 1 byte after gpr
2137 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2138 DAG.getConstant(1, MVT::i32));
2141 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2142 FprPtr, MachinePointerInfo(SV), MVT::i8,
2143 false, false, false, 0);
2144 InChain = FprIndex.getValue(1);
2146 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2147 DAG.getConstant(8, MVT::i32));
2149 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2150 DAG.getConstant(4, MVT::i32));
2153 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2154 MachinePointerInfo(), false, false,
2156 InChain = OverflowArea.getValue(1);
2158 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2159 MachinePointerInfo(), false, false,
2161 InChain = RegSaveArea.getValue(1);
2163 // select overflow_area if index > 8
2164 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2165 DAG.getConstant(8, MVT::i32), ISD::SETLT);
2167 // adjustment constant gpr_index * 4/8
2168 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2169 VT.isInteger() ? GprIndex : FprIndex,
2170 DAG.getConstant(VT.isInteger() ? 4 : 8,
2173 // OurReg = RegSaveArea + RegConstant
2174 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2177 // Floating types are 32 bytes into RegSaveArea
2178 if (VT.isFloatingPoint())
2179 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2180 DAG.getConstant(32, MVT::i32));
2182 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2183 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2184 VT.isInteger() ? GprIndex : FprIndex,
2185 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2188 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2189 VT.isInteger() ? VAListPtr : FprPtr,
2190 MachinePointerInfo(SV),
2191 MVT::i8, false, false, 0);
2193 // determine if we should load from reg_save_area or overflow_area
2194 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2196 // increase overflow_area by 4/8 if gpr/fpr > 8
2197 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2198 DAG.getConstant(VT.isInteger() ? 4 : 8,
2201 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2204 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2206 MachinePointerInfo(),
2207 MVT::i32, false, false, 0);
2209 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2210 false, false, false, 0);
2213 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2214 const PPCSubtarget &Subtarget) const {
2215 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2217 // We have to copy the entire va_list struct:
2218 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2219 return DAG.getMemcpy(Op.getOperand(0), Op,
2220 Op.getOperand(1), Op.getOperand(2),
2221 DAG.getConstant(12, MVT::i32), 8, false, true,
2222 MachinePointerInfo(), MachinePointerInfo());
2225 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2226 SelectionDAG &DAG) const {
2227 return Op.getOperand(0);
2230 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2231 SelectionDAG &DAG) const {
2232 SDValue Chain = Op.getOperand(0);
2233 SDValue Trmp = Op.getOperand(1); // trampoline
2234 SDValue FPtr = Op.getOperand(2); // nested function
2235 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2238 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2239 bool isPPC64 = (PtrVT == MVT::i64);
2241 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2244 TargetLowering::ArgListTy Args;
2245 TargetLowering::ArgListEntry Entry;
2247 Entry.Ty = IntPtrTy;
2248 Entry.Node = Trmp; Args.push_back(Entry);
2250 // TrampSize == (isPPC64 ? 48 : 40);
2251 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2252 isPPC64 ? MVT::i64 : MVT::i32);
2253 Args.push_back(Entry);
2255 Entry.Node = FPtr; Args.push_back(Entry);
2256 Entry.Node = Nest; Args.push_back(Entry);
2258 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2259 TargetLowering::CallLoweringInfo CLI(DAG);
2260 CLI.setDebugLoc(dl).setChain(Chain)
2261 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2262 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2263 std::move(Args), 0);
2265 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2266 return CallResult.second;
2269 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2270 const PPCSubtarget &Subtarget) const {
2271 MachineFunction &MF = DAG.getMachineFunction();
2272 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2276 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2277 // vastart just stores the address of the VarArgsFrameIndex slot into the
2278 // memory location argument.
2279 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2280 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2281 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2282 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2283 MachinePointerInfo(SV),
2287 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2288 // We suppose the given va_list is already allocated.
2291 // char gpr; /* index into the array of 8 GPRs
2292 // * stored in the register save area
2293 // * gpr=0 corresponds to r3,
2294 // * gpr=1 to r4, etc.
2296 // char fpr; /* index into the array of 8 FPRs
2297 // * stored in the register save area
2298 // * fpr=0 corresponds to f1,
2299 // * fpr=1 to f2, etc.
2301 // char *overflow_arg_area;
2302 // /* location on stack that holds
2303 // * the next overflow argument
2305 // char *reg_save_area;
2306 // /* where r3:r10 and f1:f8 (if saved)
2312 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2313 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2316 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2318 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2320 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2323 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2324 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2326 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2327 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2329 uint64_t FPROffset = 1;
2330 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2332 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2334 // Store first byte : number of int regs
2335 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2337 MachinePointerInfo(SV),
2338 MVT::i8, false, false, 0);
2339 uint64_t nextOffset = FPROffset;
2340 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2343 // Store second byte : number of float regs
2344 SDValue secondStore =
2345 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2346 MachinePointerInfo(SV, nextOffset), MVT::i8,
2348 nextOffset += StackOffset;
2349 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2351 // Store second word : arguments given on stack
2352 SDValue thirdStore =
2353 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2354 MachinePointerInfo(SV, nextOffset),
2356 nextOffset += FrameOffset;
2357 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2359 // Store third word : arguments given in registers
2360 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2361 MachinePointerInfo(SV, nextOffset),
2366 #include "PPCGenCallingConv.inc"
2368 // Function whose sole purpose is to kill compiler warnings
2369 // stemming from unused functions included from PPCGenCallingConv.inc.
2370 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2371 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2374 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2375 CCValAssign::LocInfo &LocInfo,
2376 ISD::ArgFlagsTy &ArgFlags,
2381 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2383 CCValAssign::LocInfo &LocInfo,
2384 ISD::ArgFlagsTy &ArgFlags,
2386 static const MCPhysReg ArgRegs[] = {
2387 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2388 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2390 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2392 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2394 // Skip one register if the first unallocated register has an even register
2395 // number and there are still argument registers available which have not been
2396 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2397 // need to skip a register if RegNum is odd.
2398 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2399 State.AllocateReg(ArgRegs[RegNum]);
2402 // Always return false here, as this function only makes sure that the first
2403 // unallocated register has an odd register number and does not actually
2404 // allocate a register for the current argument.
2408 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2410 CCValAssign::LocInfo &LocInfo,
2411 ISD::ArgFlagsTy &ArgFlags,
2413 static const MCPhysReg ArgRegs[] = {
2414 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2418 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2420 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2422 // If there is only one Floating-point register left we need to put both f64
2423 // values of a split ppc_fp128 value on the stack.
2424 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2425 State.AllocateReg(ArgRegs[RegNum]);
2428 // Always return false here, as this function only makes sure that the two f64
2429 // values a ppc_fp128 value is split into are both passed in registers or both
2430 // passed on the stack and does not actually allocate a register for the
2431 // current argument.
2435 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2437 static const MCPhysReg *GetFPR() {
2438 static const MCPhysReg FPR[] = {
2439 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2440 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2446 /// GetQFPR - Get the set of QPX registers that should be allocated for
2448 static const MCPhysReg *GetQFPR() {
2449 static const MCPhysReg QFPR[] = {
2450 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2451 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13
2457 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2459 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2460 unsigned PtrByteSize) {
2461 unsigned ArgSize = ArgVT.getStoreSize();
2462 if (Flags.isByVal())
2463 ArgSize = Flags.getByValSize();
2465 // Round up to multiples of the pointer size, except for array members,
2466 // which are always packed.
2467 if (!Flags.isInConsecutiveRegs())
2468 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2473 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2475 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2476 ISD::ArgFlagsTy Flags,
2477 unsigned PtrByteSize) {
2478 unsigned Align = PtrByteSize;
2480 // Altivec parameters are padded to a 16 byte boundary.
2481 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2482 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2483 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2485 // QPX vector types stored in double-precision are padded to a 32 byte
2487 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2490 // ByVal parameters are aligned as requested.
2491 if (Flags.isByVal()) {
2492 unsigned BVAlign = Flags.getByValAlign();
2493 if (BVAlign > PtrByteSize) {
2494 if (BVAlign % PtrByteSize != 0)
2496 "ByVal alignment is not a multiple of the pointer size");
2502 // Array members are always packed to their original alignment.
2503 if (Flags.isInConsecutiveRegs()) {
2504 // If the array member was split into multiple registers, the first
2505 // needs to be aligned to the size of the full type. (Except for
2506 // ppcf128, which is only aligned as its f64 components.)
2507 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2508 Align = OrigVT.getStoreSize();
2510 Align = ArgVT.getStoreSize();
2516 /// CalculateStackSlotUsed - Return whether this argument will use its
2517 /// stack slot (instead of being passed in registers). ArgOffset,
2518 /// AvailableFPRs, and AvailableVRs must hold the current argument
2519 /// position, and will be updated to account for this argument.
2520 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2521 ISD::ArgFlagsTy Flags,
2522 unsigned PtrByteSize,
2523 unsigned LinkageSize,
2524 unsigned ParamAreaSize,
2525 unsigned &ArgOffset,
2526 unsigned &AvailableFPRs,
2527 unsigned &AvailableVRs, bool HasQPX) {
2528 bool UseMemory = false;
2530 // Respect alignment of argument on the stack.
2532 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2533 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2534 // If there's no space left in the argument save area, we must
2535 // use memory (this check also catches zero-sized arguments).
2536 if (ArgOffset >= LinkageSize + ParamAreaSize)
2539 // Allocate argument on the stack.
2540 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2541 if (Flags.isInConsecutiveRegsLast())
2542 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2543 // If we overran the argument save area, we must use memory
2544 // (this check catches arguments passed partially in memory)
2545 if (ArgOffset > LinkageSize + ParamAreaSize)
2548 // However, if the argument is actually passed in an FPR or a VR,
2549 // we don't use memory after all.
2550 if (!Flags.isByVal()) {
2551 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2552 // QPX registers overlap with the scalar FP registers.
2553 (HasQPX && (ArgVT == MVT::v4f32 ||
2554 ArgVT == MVT::v4f64 ||
2555 ArgVT == MVT::v4i1)))
2556 if (AvailableFPRs > 0) {
2560 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2561 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2562 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2563 if (AvailableVRs > 0) {
2572 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2573 /// ensure minimum alignment required for target.
2574 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2575 unsigned NumBytes) {
2576 unsigned TargetAlign = Lowering->getStackAlignment();
2577 unsigned AlignMask = TargetAlign - 1;
2578 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2583 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2584 CallingConv::ID CallConv, bool isVarArg,
2585 const SmallVectorImpl<ISD::InputArg>
2587 SDLoc dl, SelectionDAG &DAG,
2588 SmallVectorImpl<SDValue> &InVals)
2590 if (Subtarget.isSVR4ABI()) {
2591 if (Subtarget.isPPC64())
2592 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2595 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2598 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2604 PPCTargetLowering::LowerFormalArguments_32SVR4(
2606 CallingConv::ID CallConv, bool isVarArg,
2607 const SmallVectorImpl<ISD::InputArg>
2609 SDLoc dl, SelectionDAG &DAG,
2610 SmallVectorImpl<SDValue> &InVals) const {
2612 // 32-bit SVR4 ABI Stack Frame Layout:
2613 // +-----------------------------------+
2614 // +--> | Back chain |
2615 // | +-----------------------------------+
2616 // | | Floating-point register save area |
2617 // | +-----------------------------------+
2618 // | | General register save area |
2619 // | +-----------------------------------+
2620 // | | CR save word |
2621 // | +-----------------------------------+
2622 // | | VRSAVE save word |
2623 // | +-----------------------------------+
2624 // | | Alignment padding |
2625 // | +-----------------------------------+
2626 // | | Vector register save area |
2627 // | +-----------------------------------+
2628 // | | Local variable space |
2629 // | +-----------------------------------+
2630 // | | Parameter list area |
2631 // | +-----------------------------------+
2632 // | | LR save word |
2633 // | +-----------------------------------+
2634 // SP--> +--- | Back chain |
2635 // +-----------------------------------+
2638 // System V Application Binary Interface PowerPC Processor Supplement
2639 // AltiVec Technology Programming Interface Manual
2641 MachineFunction &MF = DAG.getMachineFunction();
2642 MachineFrameInfo *MFI = MF.getFrameInfo();
2643 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2645 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2646 // Potential tail calls could cause overwriting of argument stack slots.
2647 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2648 (CallConv == CallingConv::Fast));
2649 unsigned PtrByteSize = 4;
2651 // Assign locations to all of the incoming arguments.
2652 SmallVector<CCValAssign, 16> ArgLocs;
2653 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2656 // Reserve space for the linkage area on the stack.
2657 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2658 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2660 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2662 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2663 CCValAssign &VA = ArgLocs[i];
2665 // Arguments stored in registers.
2666 if (VA.isRegLoc()) {
2667 const TargetRegisterClass *RC;
2668 EVT ValVT = VA.getValVT();
2670 switch (ValVT.getSimpleVT().SimpleTy) {
2672 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2675 RC = &PPC::GPRCRegClass;
2678 RC = &PPC::F4RCRegClass;
2681 if (Subtarget.hasVSX())
2682 RC = &PPC::VSFRCRegClass;
2684 RC = &PPC::F8RCRegClass;
2689 RC = &PPC::VRRCRegClass;
2692 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2696 RC = &PPC::VSHRCRegClass;
2699 RC = &PPC::QFRCRegClass;
2702 RC = &PPC::QBRCRegClass;
2706 // Transform the arguments stored in physical registers into virtual ones.
2707 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2708 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2709 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2711 if (ValVT == MVT::i1)
2712 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2714 InVals.push_back(ArgValue);
2716 // Argument stored in memory.
2717 assert(VA.isMemLoc());
2719 unsigned ArgSize = VA.getLocVT().getStoreSize();
2720 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2723 // Create load nodes to retrieve arguments from the stack.
2724 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2725 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2726 MachinePointerInfo(),
2727 false, false, false, 0));
2731 // Assign locations to all of the incoming aggregate by value arguments.
2732 // Aggregates passed by value are stored in the local variable space of the
2733 // caller's stack frame, right above the parameter list area.
2734 SmallVector<CCValAssign, 16> ByValArgLocs;
2735 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2736 ByValArgLocs, *DAG.getContext());
2738 // Reserve stack space for the allocations in CCInfo.
2739 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2741 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2743 // Area that is at least reserved in the caller of this function.
2744 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2745 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2747 // Set the size that is at least reserved in caller of this function. Tail
2748 // call optimized function's reserved stack space needs to be aligned so that
2749 // taking the difference between two stack areas will result in an aligned
2752 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2753 FuncInfo->setMinReservedArea(MinReservedArea);
2755 SmallVector<SDValue, 8> MemOps;
2757 // If the function takes variable number of arguments, make a frame index for
2758 // the start of the first vararg value... for expansion of llvm.va_start.
2760 static const MCPhysReg GPArgRegs[] = {
2761 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2762 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2764 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2766 static const MCPhysReg FPArgRegs[] = {
2767 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2770 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2771 if (DisablePPCFloatInVariadic)
2774 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2775 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2777 // Make room for NumGPArgRegs and NumFPArgRegs.
2778 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2779 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2781 FuncInfo->setVarArgsStackOffset(
2782 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2783 CCInfo.getNextStackOffset(), true));
2785 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2786 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2788 // The fixed integer arguments of a variadic function are stored to the
2789 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2790 // the result of va_next.
2791 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2792 // Get an existing live-in vreg, or add a new one.
2793 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2795 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2797 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2798 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2799 MachinePointerInfo(), false, false, 0);
2800 MemOps.push_back(Store);
2801 // Increment the address by four for the next argument to store
2802 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2803 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2806 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2808 // The double arguments are stored to the VarArgsFrameIndex
2810 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2811 // Get an existing live-in vreg, or add a new one.
2812 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2814 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2816 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2817 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2818 MachinePointerInfo(), false, false, 0);
2819 MemOps.push_back(Store);
2820 // Increment the address by eight for the next argument to store
2821 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2823 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2827 if (!MemOps.empty())
2828 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2833 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2834 // value to MVT::i64 and then truncate to the correct register size.
2836 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2837 SelectionDAG &DAG, SDValue ArgVal,
2840 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2841 DAG.getValueType(ObjectVT));
2842 else if (Flags.isZExt())
2843 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2844 DAG.getValueType(ObjectVT));
2846 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2850 PPCTargetLowering::LowerFormalArguments_64SVR4(
2852 CallingConv::ID CallConv, bool isVarArg,
2853 const SmallVectorImpl<ISD::InputArg>
2855 SDLoc dl, SelectionDAG &DAG,
2856 SmallVectorImpl<SDValue> &InVals) const {
2857 // TODO: add description of PPC stack frame format, or at least some docs.
2859 bool isELFv2ABI = Subtarget.isELFv2ABI();
2860 bool isLittleEndian = Subtarget.isLittleEndian();
2861 MachineFunction &MF = DAG.getMachineFunction();
2862 MachineFrameInfo *MFI = MF.getFrameInfo();
2863 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2865 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2866 "fastcc not supported on varargs functions");
2868 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2869 // Potential tail calls could cause overwriting of argument stack slots.
2870 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2871 (CallConv == CallingConv::Fast));
2872 unsigned PtrByteSize = 8;
2873 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2875 static const MCPhysReg GPR[] = {
2876 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2877 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2880 static const MCPhysReg *FPR = GetFPR();
2882 static const MCPhysReg VR[] = {
2883 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2884 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2886 static const MCPhysReg VSRH[] = {
2887 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2888 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2891 static const MCPhysReg *QFPR = GetQFPR();
2893 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2894 const unsigned Num_FPR_Regs = 13;
2895 const unsigned Num_VR_Regs = array_lengthof(VR);
2896 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2898 // Do a first pass over the arguments to determine whether the ABI
2899 // guarantees that our caller has allocated the parameter save area
2900 // on its stack frame. In the ELFv1 ABI, this is always the case;
2901 // in the ELFv2 ABI, it is true if this is a vararg function or if
2902 // any parameter is located in a stack slot.
2904 bool HasParameterArea = !isELFv2ABI || isVarArg;
2905 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2906 unsigned NumBytes = LinkageSize;
2907 unsigned AvailableFPRs = Num_FPR_Regs;
2908 unsigned AvailableVRs = Num_VR_Regs;
2909 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2910 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2911 PtrByteSize, LinkageSize, ParamAreaSize,
2912 NumBytes, AvailableFPRs, AvailableVRs,
2913 Subtarget.hasQPX()))
2914 HasParameterArea = true;
2916 // Add DAG nodes to load the arguments or copy them out of registers. On
2917 // entry to a function on PPC, the arguments start after the linkage area,
2918 // although the first ones are often in registers.
2920 unsigned ArgOffset = LinkageSize;
2921 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2922 unsigned &QFPR_idx = FPR_idx;
2923 SmallVector<SDValue, 8> MemOps;
2924 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2925 unsigned CurArgIdx = 0;
2926 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2928 bool needsLoad = false;
2929 EVT ObjectVT = Ins[ArgNo].VT;
2930 EVT OrigVT = Ins[ArgNo].ArgVT;
2931 unsigned ObjSize = ObjectVT.getStoreSize();
2932 unsigned ArgSize = ObjSize;
2933 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2934 if (Ins[ArgNo].isOrigArg()) {
2935 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2936 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2938 // We re-align the argument offset for each argument, except when using the
2939 // fast calling convention, when we need to make sure we do that only when
2940 // we'll actually use a stack slot.
2941 unsigned CurArgOffset, Align;
2942 auto ComputeArgOffset = [&]() {
2943 /* Respect alignment of argument on the stack. */
2944 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2945 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2946 CurArgOffset = ArgOffset;
2949 if (CallConv != CallingConv::Fast) {
2952 /* Compute GPR index associated with argument offset. */
2953 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2954 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2957 // FIXME the codegen can be much improved in some cases.
2958 // We do not have to keep everything in memory.
2959 if (Flags.isByVal()) {
2960 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2962 if (CallConv == CallingConv::Fast)
2965 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2966 ObjSize = Flags.getByValSize();
2967 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2968 // Empty aggregate parameters do not take up registers. Examples:
2972 // etc. However, we have to provide a place-holder in InVals, so
2973 // pretend we have an 8-byte item at the current address for that
2976 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2977 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2978 InVals.push_back(FIN);
2982 // Create a stack object covering all stack doublewords occupied
2983 // by the argument. If the argument is (fully or partially) on
2984 // the stack, or if the argument is fully in registers but the
2985 // caller has allocated the parameter save anyway, we can refer
2986 // directly to the caller's stack frame. Otherwise, create a
2987 // local copy in our own frame.
2989 if (HasParameterArea ||
2990 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2991 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2993 FI = MFI->CreateStackObject(ArgSize, Align, false);
2994 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2996 // Handle aggregates smaller than 8 bytes.
2997 if (ObjSize < PtrByteSize) {
2998 // The value of the object is its address, which differs from the
2999 // address of the enclosing doubleword on big-endian systems.
3001 if (!isLittleEndian) {
3002 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3003 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3005 InVals.push_back(Arg);
3007 if (GPR_idx != Num_GPR_Regs) {
3008 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3009 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3012 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3013 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3014 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3015 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3016 MachinePointerInfo(FuncArg),
3017 ObjType, false, false, 0);
3019 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3020 // store the whole register as-is to the parameter save area
3022 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3023 MachinePointerInfo(FuncArg),
3027 MemOps.push_back(Store);
3029 // Whether we copied from a register or not, advance the offset
3030 // into the parameter save area by a full doubleword.
3031 ArgOffset += PtrByteSize;
3035 // The value of the object is its address, which is the address of
3036 // its first stack doubleword.
3037 InVals.push_back(FIN);
3039 // Store whatever pieces of the object are in registers to memory.
3040 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3041 if (GPR_idx == Num_GPR_Regs)
3044 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3045 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3048 SDValue Off = DAG.getConstant(j, PtrVT);
3049 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3051 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3052 MachinePointerInfo(FuncArg, j),
3054 MemOps.push_back(Store);
3057 ArgOffset += ArgSize;
3061 switch (ObjectVT.getSimpleVT().SimpleTy) {
3062 default: llvm_unreachable("Unhandled argument type!");
3066 // These can be scalar arguments or elements of an integer array type
3067 // passed directly. Clang may use those instead of "byval" aggregate
3068 // types to avoid forcing arguments to memory unnecessarily.
3069 if (GPR_idx != Num_GPR_Regs) {
3070 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3071 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3073 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3074 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3075 // value to MVT::i64 and then truncate to the correct register size.
3076 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3078 if (CallConv == CallingConv::Fast)
3082 ArgSize = PtrByteSize;
3084 if (CallConv != CallingConv::Fast || needsLoad)
3090 // These can be scalar arguments or elements of a float array type
3091 // passed directly. The latter are used to implement ELFv2 homogenous
3092 // float aggregates.
3093 if (FPR_idx != Num_FPR_Regs) {
3096 if (ObjectVT == MVT::f32)
3097 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3099 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3100 ? &PPC::VSFRCRegClass
3101 : &PPC::F8RCRegClass);
3103 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3105 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3106 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3107 // once we support fp <-> gpr moves.
3109 // This can only ever happen in the presence of f32 array types,
3110 // since otherwise we never run out of FPRs before running out
3112 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3113 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3115 if (ObjectVT == MVT::f32) {
3116 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3117 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3118 DAG.getConstant(32, MVT::i32));
3119 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3122 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3124 if (CallConv == CallingConv::Fast)
3130 // When passing an array of floats, the array occupies consecutive
3131 // space in the argument area; only round up to the next doubleword
3132 // at the end of the array. Otherwise, each float takes 8 bytes.
3133 if (CallConv != CallingConv::Fast || needsLoad) {
3134 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3135 ArgOffset += ArgSize;
3136 if (Flags.isInConsecutiveRegsLast())
3137 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3146 if (!Subtarget.hasQPX()) {
3147 // These can be scalar arguments or elements of a vector array type
3148 // passed directly. The latter are used to implement ELFv2 homogenous
3149 // vector aggregates.
3150 if (VR_idx != Num_VR_Regs) {
3151 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3152 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3153 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3154 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3157 if (CallConv == CallingConv::Fast)
3162 if (CallConv != CallingConv::Fast || needsLoad)
3167 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3168 "Invalid QPX parameter type");
3173 // QPX vectors are treated like their scalar floating-point subregisters
3174 // (except that they're larger).
3175 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3176 if (QFPR_idx != Num_QFPR_Regs) {
3177 const TargetRegisterClass *RC;
3178 switch (ObjectVT.getSimpleVT().SimpleTy) {
3179 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3180 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3181 default: RC = &PPC::QBRCRegClass; break;
3184 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3185 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3188 if (CallConv == CallingConv::Fast)
3192 if (CallConv != CallingConv::Fast || needsLoad)
3197 // We need to load the argument to a virtual register if we determined
3198 // above that we ran out of physical registers of the appropriate type.
3200 if (ObjSize < ArgSize && !isLittleEndian)
3201 CurArgOffset += ArgSize - ObjSize;
3202 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3203 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3204 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3205 false, false, false, 0);
3208 InVals.push_back(ArgVal);
3211 // Area that is at least reserved in the caller of this function.
3212 unsigned MinReservedArea;
3213 if (HasParameterArea)
3214 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3216 MinReservedArea = LinkageSize;
3218 // Set the size that is at least reserved in caller of this function. Tail
3219 // call optimized functions' reserved stack space needs to be aligned so that
3220 // taking the difference between two stack areas will result in an aligned
3223 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3224 FuncInfo->setMinReservedArea(MinReservedArea);
3226 // If the function takes variable number of arguments, make a frame index for
3227 // the start of the first vararg value... for expansion of llvm.va_start.
3229 int Depth = ArgOffset;
3231 FuncInfo->setVarArgsFrameIndex(
3232 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3233 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3235 // If this function is vararg, store any remaining integer argument regs
3236 // to their spots on the stack so that they may be loaded by deferencing the
3237 // result of va_next.
3238 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3239 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3240 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3241 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3242 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3243 MachinePointerInfo(), false, false, 0);
3244 MemOps.push_back(Store);
3245 // Increment the address by four for the next argument to store
3246 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3247 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3251 if (!MemOps.empty())
3252 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3258 PPCTargetLowering::LowerFormalArguments_Darwin(
3260 CallingConv::ID CallConv, bool isVarArg,
3261 const SmallVectorImpl<ISD::InputArg>
3263 SDLoc dl, SelectionDAG &DAG,
3264 SmallVectorImpl<SDValue> &InVals) const {
3265 // TODO: add description of PPC stack frame format, or at least some docs.
3267 MachineFunction &MF = DAG.getMachineFunction();
3268 MachineFrameInfo *MFI = MF.getFrameInfo();
3269 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3271 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3272 bool isPPC64 = PtrVT == MVT::i64;
3273 // Potential tail calls could cause overwriting of argument stack slots.
3274 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3275 (CallConv == CallingConv::Fast));
3276 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3277 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3278 unsigned ArgOffset = LinkageSize;
3279 // Area that is at least reserved in caller of this function.
3280 unsigned MinReservedArea = ArgOffset;
3282 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3283 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3284 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3286 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3287 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3288 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3291 static const MCPhysReg *FPR = GetFPR();
3293 static const MCPhysReg VR[] = {
3294 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3295 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3298 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3299 const unsigned Num_FPR_Regs = 13;
3300 const unsigned Num_VR_Regs = array_lengthof( VR);
3302 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3304 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3306 // In 32-bit non-varargs functions, the stack space for vectors is after the
3307 // stack space for non-vectors. We do not use this space unless we have
3308 // too many vectors to fit in registers, something that only occurs in
3309 // constructed examples:), but we have to walk the arglist to figure
3310 // that out...for the pathological case, compute VecArgOffset as the
3311 // start of the vector parameter area. Computing VecArgOffset is the
3312 // entire point of the following loop.
3313 unsigned VecArgOffset = ArgOffset;
3314 if (!isVarArg && !isPPC64) {
3315 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3317 EVT ObjectVT = Ins[ArgNo].VT;
3318 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3320 if (Flags.isByVal()) {
3321 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3322 unsigned ObjSize = Flags.getByValSize();
3324 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3325 VecArgOffset += ArgSize;
3329 switch(ObjectVT.getSimpleVT().SimpleTy) {
3330 default: llvm_unreachable("Unhandled argument type!");
3336 case MVT::i64: // PPC64
3338 // FIXME: We are guaranteed to be !isPPC64 at this point.
3339 // Does MVT::i64 apply?
3346 // Nothing to do, we're only looking at Nonvector args here.
3351 // We've found where the vector parameter area in memory is. Skip the
3352 // first 12 parameters; these don't use that memory.
3353 VecArgOffset = ((VecArgOffset+15)/16)*16;
3354 VecArgOffset += 12*16;
3356 // Add DAG nodes to load the arguments or copy them out of registers. On
3357 // entry to a function on PPC, the arguments start after the linkage area,
3358 // although the first ones are often in registers.
3360 SmallVector<SDValue, 8> MemOps;
3361 unsigned nAltivecParamsAtEnd = 0;
3362 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3363 unsigned CurArgIdx = 0;
3364 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3366 bool needsLoad = false;
3367 EVT ObjectVT = Ins[ArgNo].VT;
3368 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3369 unsigned ArgSize = ObjSize;
3370 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3371 if (Ins[ArgNo].isOrigArg()) {
3372 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3373 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3375 unsigned CurArgOffset = ArgOffset;
3377 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3378 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3379 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3380 if (isVarArg || isPPC64) {
3381 MinReservedArea = ((MinReservedArea+15)/16)*16;
3382 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3385 } else nAltivecParamsAtEnd++;
3387 // Calculate min reserved area.
3388 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3392 // FIXME the codegen can be much improved in some cases.
3393 // We do not have to keep everything in memory.
3394 if (Flags.isByVal()) {
3395 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3397 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3398 ObjSize = Flags.getByValSize();
3399 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3400 // Objects of size 1 and 2 are right justified, everything else is
3401 // left justified. This means the memory address is adjusted forwards.
3402 if (ObjSize==1 || ObjSize==2) {
3403 CurArgOffset = CurArgOffset + (4 - ObjSize);
3405 // The value of the object is its address.
3406 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3407 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3408 InVals.push_back(FIN);
3409 if (ObjSize==1 || ObjSize==2) {
3410 if (GPR_idx != Num_GPR_Regs) {
3413 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3415 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3416 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3417 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3418 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3419 MachinePointerInfo(FuncArg),
3420 ObjType, false, false, 0);
3421 MemOps.push_back(Store);
3425 ArgOffset += PtrByteSize;
3429 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3430 // Store whatever pieces of the object are in registers
3431 // to memory. ArgOffset will be the address of the beginning
3433 if (GPR_idx != Num_GPR_Regs) {
3436 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3438 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3439 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3440 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3441 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3442 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3443 MachinePointerInfo(FuncArg, j),
3445 MemOps.push_back(Store);
3447 ArgOffset += PtrByteSize;
3449 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3456 switch (ObjectVT.getSimpleVT().SimpleTy) {
3457 default: llvm_unreachable("Unhandled argument type!");
3461 if (GPR_idx != Num_GPR_Regs) {
3462 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3463 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3465 if (ObjectVT == MVT::i1)
3466 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3471 ArgSize = PtrByteSize;
3473 // All int arguments reserve stack space in the Darwin ABI.
3474 ArgOffset += PtrByteSize;
3478 case MVT::i64: // PPC64
3479 if (GPR_idx != Num_GPR_Regs) {
3480 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3481 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3483 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3484 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3485 // value to MVT::i64 and then truncate to the correct register size.
3486 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3491 ArgSize = PtrByteSize;
3493 // All int arguments reserve stack space in the Darwin ABI.
3499 // Every 4 bytes of argument space consumes one of the GPRs available for
3500 // argument passing.
3501 if (GPR_idx != Num_GPR_Regs) {
3503 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3506 if (FPR_idx != Num_FPR_Regs) {
3509 if (ObjectVT == MVT::f32)
3510 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3512 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3514 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3520 // All FP arguments reserve stack space in the Darwin ABI.
3521 ArgOffset += isPPC64 ? 8 : ObjSize;
3527 // Note that vector arguments in registers don't reserve stack space,
3528 // except in varargs functions.
3529 if (VR_idx != Num_VR_Regs) {
3530 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3531 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3533 while ((ArgOffset % 16) != 0) {
3534 ArgOffset += PtrByteSize;
3535 if (GPR_idx != Num_GPR_Regs)
3539 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3543 if (!isVarArg && !isPPC64) {
3544 // Vectors go after all the nonvectors.
3545 CurArgOffset = VecArgOffset;
3548 // Vectors are aligned.
3549 ArgOffset = ((ArgOffset+15)/16)*16;
3550 CurArgOffset = ArgOffset;
3558 // We need to load the argument to a virtual register if we determined above
3559 // that we ran out of physical registers of the appropriate type.
3561 int FI = MFI->CreateFixedObject(ObjSize,
3562 CurArgOffset + (ArgSize - ObjSize),
3564 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3565 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3566 false, false, false, 0);
3569 InVals.push_back(ArgVal);
3572 // Allow for Altivec parameters at the end, if needed.
3573 if (nAltivecParamsAtEnd) {
3574 MinReservedArea = ((MinReservedArea+15)/16)*16;
3575 MinReservedArea += 16*nAltivecParamsAtEnd;
3578 // Area that is at least reserved in the caller of this function.
3579 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3581 // Set the size that is at least reserved in caller of this function. Tail
3582 // call optimized functions' reserved stack space needs to be aligned so that
3583 // taking the difference between two stack areas will result in an aligned
3586 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3587 FuncInfo->setMinReservedArea(MinReservedArea);
3589 // If the function takes variable number of arguments, make a frame index for
3590 // the start of the first vararg value... for expansion of llvm.va_start.
3592 int Depth = ArgOffset;
3594 FuncInfo->setVarArgsFrameIndex(
3595 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3597 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3599 // If this function is vararg, store any remaining integer argument regs
3600 // to their spots on the stack so that they may be loaded by deferencing the
3601 // result of va_next.
3602 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3606 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3608 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3610 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3611 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3612 MachinePointerInfo(), false, false, 0);
3613 MemOps.push_back(Store);
3614 // Increment the address by four for the next argument to store
3615 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3616 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3620 if (!MemOps.empty())
3621 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3626 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3627 /// adjusted to accommodate the arguments for the tailcall.
3628 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3629 unsigned ParamSize) {
3631 if (!isTailCall) return 0;
3633 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3634 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3635 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3636 // Remember only if the new adjustement is bigger.
3637 if (SPDiff < FI->getTailCallSPDelta())
3638 FI->setTailCallSPDelta(SPDiff);
3643 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3644 /// for tail call optimization. Targets which want to do tail call
3645 /// optimization should implement this function.
3647 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3648 CallingConv::ID CalleeCC,
3650 const SmallVectorImpl<ISD::InputArg> &Ins,
3651 SelectionDAG& DAG) const {
3652 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3655 // Variable argument functions are not supported.
3659 MachineFunction &MF = DAG.getMachineFunction();
3660 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3661 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3662 // Functions containing by val parameters are not supported.
3663 for (unsigned i = 0; i != Ins.size(); i++) {
3664 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3665 if (Flags.isByVal()) return false;
3668 // Non-PIC/GOT tail calls are supported.
3669 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3672 // At the moment we can only do local tail calls (in same module, hidden
3673 // or protected) if we are generating PIC.
3674 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3675 return G->getGlobal()->hasHiddenVisibility()
3676 || G->getGlobal()->hasProtectedVisibility();
3682 /// isCallCompatibleAddress - Return the immediate to use if the specified
3683 /// 32-bit value is representable in the immediate field of a BxA instruction.
3684 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3685 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3686 if (!C) return nullptr;
3688 int Addr = C->getZExtValue();
3689 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3690 SignExtend32<26>(Addr) != Addr)
3691 return nullptr; // Top 6 bits have to be sext of immediate.
3693 return DAG.getConstant((int)C->getZExtValue() >> 2,
3694 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3699 struct TailCallArgumentInfo {
3704 TailCallArgumentInfo() : FrameIdx(0) {}
3709 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3711 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3713 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3714 SmallVectorImpl<SDValue> &MemOpChains,
3716 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3717 SDValue Arg = TailCallArgs[i].Arg;
3718 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3719 int FI = TailCallArgs[i].FrameIdx;
3720 // Store relative to framepointer.
3721 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3722 MachinePointerInfo::getFixedStack(FI),
3727 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3728 /// the appropriate stack slot for the tail call optimized function call.
3729 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3730 MachineFunction &MF,
3739 // Calculate the new stack slot for the return address.
3740 int SlotSize = isPPC64 ? 8 : 4;
3741 const PPCFrameLowering *FL =
3742 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3743 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3744 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3745 NewRetAddrLoc, true);
3746 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3747 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3748 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3749 MachinePointerInfo::getFixedStack(NewRetAddr),
3752 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3753 // slot as the FP is never overwritten.
3755 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3756 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3758 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3759 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3760 MachinePointerInfo::getFixedStack(NewFPIdx),
3767 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3768 /// the position of the argument.
3770 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3771 SDValue Arg, int SPDiff, unsigned ArgOffset,
3772 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3773 int Offset = ArgOffset + SPDiff;
3774 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3775 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3776 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3777 SDValue FIN = DAG.getFrameIndex(FI, VT);
3778 TailCallArgumentInfo Info;
3780 Info.FrameIdxOp = FIN;
3782 TailCallArguments.push_back(Info);
3785 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3786 /// stack slot. Returns the chain as result and the loaded frame pointers in
3787 /// LROpOut/FPOpout. Used when tail calling.
3788 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3796 // Load the LR and FP stack slot for later adjusting.
3797 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3798 LROpOut = getReturnAddrFrameIndex(DAG);
3799 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3800 false, false, false, 0);
3801 Chain = SDValue(LROpOut.getNode(), 1);
3803 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3804 // slot as the FP is never overwritten.
3806 FPOpOut = getFramePointerFrameIndex(DAG);
3807 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3808 false, false, false, 0);
3809 Chain = SDValue(FPOpOut.getNode(), 1);
3815 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3816 /// by "Src" to address "Dst" of size "Size". Alignment information is
3817 /// specified by the specific parameter attribute. The copy will be passed as
3818 /// a byval function parameter.
3819 /// Sometimes what we are copying is the end of a larger object, the part that
3820 /// does not fit in registers.
3822 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3823 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3825 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3826 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3827 false, false, MachinePointerInfo(),
3828 MachinePointerInfo());
3831 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3834 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3835 SDValue Arg, SDValue PtrOff, int SPDiff,
3836 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3837 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3838 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3840 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3845 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3847 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3848 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3849 DAG.getConstant(ArgOffset, PtrVT));
3851 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3852 MachinePointerInfo(), false, false, 0));
3853 // Calculate and remember argument location.
3854 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3859 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3860 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3861 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3862 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3863 MachineFunction &MF = DAG.getMachineFunction();
3865 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3866 // might overwrite each other in case of tail call optimization.
3867 SmallVector<SDValue, 8> MemOpChains2;
3868 // Do not flag preceding copytoreg stuff together with the following stuff.
3870 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3872 if (!MemOpChains2.empty())
3873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3875 // Store the return address to the appropriate stack slot.
3876 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3877 isPPC64, isDarwinABI, dl);
3879 // Emit callseq_end just before tailcall node.
3880 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3881 DAG.getIntPtrConstant(0, true), InFlag, dl);
3882 InFlag = Chain.getValue(1);
3885 // Is this global address that of a function that can be called by name? (as
3886 // opposed to something that must hold a descriptor for an indirect call).
3887 static bool isFunctionGlobalAddress(SDValue Callee) {
3888 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3889 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3890 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3893 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3900 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3901 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3902 bool isTailCall, bool IsPatchPoint,
3903 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3904 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3905 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3907 bool isPPC64 = Subtarget.isPPC64();
3908 bool isSVR4ABI = Subtarget.isSVR4ABI();
3909 bool isELFv2ABI = Subtarget.isELFv2ABI();
3911 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3912 NodeTys.push_back(MVT::Other); // Returns a chain
3913 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3915 unsigned CallOpc = PPCISD::CALL;
3917 bool needIndirectCall = true;
3918 if (!isSVR4ABI || !isPPC64)
3919 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3920 // If this is an absolute destination address, use the munged value.
3921 Callee = SDValue(Dest, 0);
3922 needIndirectCall = false;
3925 if (isFunctionGlobalAddress(Callee)) {
3926 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3927 // A call to a TLS address is actually an indirect call to a
3928 // thread-specific pointer.
3929 unsigned OpFlags = 0;
3930 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3931 (Subtarget.getTargetTriple().isMacOSX() &&
3932 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3933 (G->getGlobal()->isDeclaration() ||
3934 G->getGlobal()->isWeakForLinker())) ||
3935 (Subtarget.isTargetELF() && !isPPC64 &&
3936 !G->getGlobal()->hasLocalLinkage() &&
3937 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3938 // PC-relative references to external symbols should go through $stub,
3939 // unless we're building with the leopard linker or later, which
3940 // automatically synthesizes these stubs.
3941 OpFlags = PPCII::MO_PLT_OR_STUB;
3944 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3945 // every direct call is) turn it into a TargetGlobalAddress /
3946 // TargetExternalSymbol node so that legalize doesn't hack it.
3947 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3948 Callee.getValueType(), 0, OpFlags);
3949 needIndirectCall = false;
3952 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3953 unsigned char OpFlags = 0;
3955 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3956 (Subtarget.getTargetTriple().isMacOSX() &&
3957 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3958 (Subtarget.isTargetELF() && !isPPC64 &&
3959 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3960 // PC-relative references to external symbols should go through $stub,
3961 // unless we're building with the leopard linker or later, which
3962 // automatically synthesizes these stubs.
3963 OpFlags = PPCII::MO_PLT_OR_STUB;
3966 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3968 needIndirectCall = false;
3972 // We'll form an invalid direct call when lowering a patchpoint; the full
3973 // sequence for an indirect call is complicated, and many of the
3974 // instructions introduced might have side effects (and, thus, can't be
3975 // removed later). The call itself will be removed as soon as the
3976 // argument/return lowering is complete, so the fact that it has the wrong
3977 // kind of operands should not really matter.
3978 needIndirectCall = false;
3981 if (needIndirectCall) {
3982 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3983 // to do the call, we can't use PPCISD::CALL.
3984 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3986 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3987 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3988 // entry point, but to the function descriptor (the function entry point
3989 // address is part of the function descriptor though).
3990 // The function descriptor is a three doubleword structure with the
3991 // following fields: function entry point, TOC base address and
3992 // environment pointer.
3993 // Thus for a call through a function pointer, the following actions need
3995 // 1. Save the TOC of the caller in the TOC save area of its stack
3996 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3997 // 2. Load the address of the function entry point from the function
3999 // 3. Load the TOC of the callee from the function descriptor into r2.
4000 // 4. Load the environment pointer from the function descriptor into
4002 // 5. Branch to the function entry point address.
4003 // 6. On return of the callee, the TOC of the caller needs to be
4004 // restored (this is done in FinishCall()).
4006 // The loads are scheduled at the beginning of the call sequence, and the
4007 // register copies are flagged together to ensure that no other
4008 // operations can be scheduled in between. E.g. without flagging the
4009 // copies together, a TOC access in the caller could be scheduled between
4010 // the assignment of the callee TOC and the branch to the callee, which
4011 // results in the TOC access going through the TOC of the callee instead
4012 // of going through the TOC of the caller, which leads to incorrect code.
4014 // Load the address of the function entry point from the function
4016 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4017 if (LDChain.getValueType() == MVT::Glue)
4018 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4020 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4022 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4023 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4024 false, false, LoadsInv, 8);
4026 // Load environment pointer into r11.
4027 SDValue PtrOff = DAG.getIntPtrConstant(16);
4028 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4029 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4030 MPI.getWithOffset(16), false, false,
4033 SDValue TOCOff = DAG.getIntPtrConstant(8);
4034 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4035 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4036 MPI.getWithOffset(8), false, false,
4039 setUsesTOCBasePtr(DAG);
4040 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4042 Chain = TOCVal.getValue(0);
4043 InFlag = TOCVal.getValue(1);
4045 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4048 Chain = EnvVal.getValue(0);
4049 InFlag = EnvVal.getValue(1);
4051 MTCTROps[0] = Chain;
4052 MTCTROps[1] = LoadFuncPtr;
4053 MTCTROps[2] = InFlag;
4056 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4057 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4058 InFlag = Chain.getValue(1);
4061 NodeTys.push_back(MVT::Other);
4062 NodeTys.push_back(MVT::Glue);
4063 Ops.push_back(Chain);
4064 CallOpc = PPCISD::BCTRL;
4065 Callee.setNode(nullptr);
4066 // Add use of X11 (holding environment pointer)
4067 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4068 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4069 // Add CTR register as callee so a bctr can be emitted later.
4071 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4074 // If this is a direct call, pass the chain and the callee.
4075 if (Callee.getNode()) {
4076 Ops.push_back(Chain);
4077 Ops.push_back(Callee);
4079 // If this is a tail call add stack pointer delta.
4081 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4083 // Add argument registers to the end of the list so that they are known live
4085 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4086 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4087 RegsToPass[i].second.getValueType()));
4089 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4091 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4092 setUsesTOCBasePtr(DAG);
4093 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4100 bool isLocalCall(const SDValue &Callee)
4102 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4103 return !G->getGlobal()->isDeclaration() &&
4104 !G->getGlobal()->isWeakForLinker();
4109 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4110 CallingConv::ID CallConv, bool isVarArg,
4111 const SmallVectorImpl<ISD::InputArg> &Ins,
4112 SDLoc dl, SelectionDAG &DAG,
4113 SmallVectorImpl<SDValue> &InVals) const {
4115 SmallVector<CCValAssign, 16> RVLocs;
4116 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4118 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4120 // Copy all of the result registers out of their specified physreg.
4121 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4122 CCValAssign &VA = RVLocs[i];
4123 assert(VA.isRegLoc() && "Can only return in registers!");
4125 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4126 VA.getLocReg(), VA.getLocVT(), InFlag);
4127 Chain = Val.getValue(1);
4128 InFlag = Val.getValue(2);
4130 switch (VA.getLocInfo()) {
4131 default: llvm_unreachable("Unknown loc info!");
4132 case CCValAssign::Full: break;
4133 case CCValAssign::AExt:
4134 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4136 case CCValAssign::ZExt:
4137 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4138 DAG.getValueType(VA.getValVT()));
4139 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4141 case CCValAssign::SExt:
4142 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4143 DAG.getValueType(VA.getValVT()));
4144 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4148 InVals.push_back(Val);
4155 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4156 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4158 SmallVector<std::pair<unsigned, SDValue>, 8>
4160 SDValue InFlag, SDValue Chain,
4161 SDValue CallSeqStart, SDValue &Callee,
4162 int SPDiff, unsigned NumBytes,
4163 const SmallVectorImpl<ISD::InputArg> &Ins,
4164 SmallVectorImpl<SDValue> &InVals,
4165 ImmutableCallSite *CS) const {
4167 std::vector<EVT> NodeTys;
4168 SmallVector<SDValue, 8> Ops;
4169 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4170 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4171 Ops, NodeTys, CS, Subtarget);
4173 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4174 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4175 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4177 // When performing tail call optimization the callee pops its arguments off
4178 // the stack. Account for this here so these bytes can be pushed back on in
4179 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4180 int BytesCalleePops =
4181 (CallConv == CallingConv::Fast &&
4182 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4184 // Add a register mask operand representing the call-preserved registers.
4185 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4186 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
4187 assert(Mask && "Missing call preserved mask for calling convention");
4188 Ops.push_back(DAG.getRegisterMask(Mask));
4190 if (InFlag.getNode())
4191 Ops.push_back(InFlag);
4195 assert(((Callee.getOpcode() == ISD::Register &&
4196 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4197 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4198 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4199 isa<ConstantSDNode>(Callee)) &&
4200 "Expecting an global address, external symbol, absolute value or register");
4202 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4205 // Add a NOP immediately after the branch instruction when using the 64-bit
4206 // SVR4 ABI. At link time, if caller and callee are in a different module and
4207 // thus have a different TOC, the call will be replaced with a call to a stub
4208 // function which saves the current TOC, loads the TOC of the callee and
4209 // branches to the callee. The NOP will be replaced with a load instruction
4210 // which restores the TOC of the caller from the TOC save slot of the current
4211 // stack frame. If caller and callee belong to the same module (and have the
4212 // same TOC), the NOP will remain unchanged.
4214 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4216 if (CallOpc == PPCISD::BCTRL) {
4217 // This is a call through a function pointer.
4218 // Restore the caller TOC from the save area into R2.
4219 // See PrepareCall() for more information about calls through function
4220 // pointers in the 64-bit SVR4 ABI.
4221 // We are using a target-specific load with r2 hard coded, because the
4222 // result of a target-independent load would never go directly into r2,
4223 // since r2 is a reserved register (which prevents the register allocator
4224 // from allocating it), resulting in an additional register being
4225 // allocated and an unnecessary move instruction being generated.
4226 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4228 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4229 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4230 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4231 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4232 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4234 // The address needs to go after the chain input but before the flag (or
4235 // any other variadic arguments).
4236 Ops.insert(std::next(Ops.begin()), AddTOC);
4237 } else if ((CallOpc == PPCISD::CALL) &&
4238 (!isLocalCall(Callee) ||
4239 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4240 // Otherwise insert NOP for non-local calls.
4241 CallOpc = PPCISD::CALL_NOP;
4244 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4245 InFlag = Chain.getValue(1);
4247 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4248 DAG.getIntPtrConstant(BytesCalleePops, true),
4251 InFlag = Chain.getValue(1);
4253 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4254 Ins, dl, DAG, InVals);
4258 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4259 SmallVectorImpl<SDValue> &InVals) const {
4260 SelectionDAG &DAG = CLI.DAG;
4262 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4263 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4264 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4265 SDValue Chain = CLI.Chain;
4266 SDValue Callee = CLI.Callee;
4267 bool &isTailCall = CLI.IsTailCall;
4268 CallingConv::ID CallConv = CLI.CallConv;
4269 bool isVarArg = CLI.IsVarArg;
4270 bool IsPatchPoint = CLI.IsPatchPoint;
4271 ImmutableCallSite *CS = CLI.CS;
4274 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4277 if (!isTailCall && CS && CS->isMustTailCall())
4278 report_fatal_error("failed to perform tail call elimination on a call "
4279 "site marked musttail");
4281 if (Subtarget.isSVR4ABI()) {
4282 if (Subtarget.isPPC64())
4283 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4284 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4285 dl, DAG, InVals, CS);
4287 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4288 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4289 dl, DAG, InVals, CS);
4292 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4293 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4294 dl, DAG, InVals, CS);
4298 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4299 CallingConv::ID CallConv, bool isVarArg,
4300 bool isTailCall, bool IsPatchPoint,
4301 const SmallVectorImpl<ISD::OutputArg> &Outs,
4302 const SmallVectorImpl<SDValue> &OutVals,
4303 const SmallVectorImpl<ISD::InputArg> &Ins,
4304 SDLoc dl, SelectionDAG &DAG,
4305 SmallVectorImpl<SDValue> &InVals,
4306 ImmutableCallSite *CS) const {
4307 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4308 // of the 32-bit SVR4 ABI stack frame layout.
4310 assert((CallConv == CallingConv::C ||
4311 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4313 unsigned PtrByteSize = 4;
4315 MachineFunction &MF = DAG.getMachineFunction();
4317 // Mark this function as potentially containing a function that contains a
4318 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4319 // and restoring the callers stack pointer in this functions epilog. This is
4320 // done because by tail calling the called function might overwrite the value
4321 // in this function's (MF) stack pointer stack slot 0(SP).
4322 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4323 CallConv == CallingConv::Fast)
4324 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4326 // Count how many bytes are to be pushed on the stack, including the linkage
4327 // area, parameter list area and the part of the local variable space which
4328 // contains copies of aggregates which are passed by value.
4330 // Assign locations to all of the outgoing arguments.
4331 SmallVector<CCValAssign, 16> ArgLocs;
4332 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4335 // Reserve space for the linkage area on the stack.
4336 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4340 // Handle fixed and variable vector arguments differently.
4341 // Fixed vector arguments go into registers as long as registers are
4342 // available. Variable vector arguments always go into memory.
4343 unsigned NumArgs = Outs.size();
4345 for (unsigned i = 0; i != NumArgs; ++i) {
4346 MVT ArgVT = Outs[i].VT;
4347 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4350 if (Outs[i].IsFixed) {
4351 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4354 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4360 errs() << "Call operand #" << i << " has unhandled type "
4361 << EVT(ArgVT).getEVTString() << "\n";
4363 llvm_unreachable(nullptr);
4367 // All arguments are treated the same.
4368 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4371 // Assign locations to all of the outgoing aggregate by value arguments.
4372 SmallVector<CCValAssign, 16> ByValArgLocs;
4373 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4374 ByValArgLocs, *DAG.getContext());
4376 // Reserve stack space for the allocations in CCInfo.
4377 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4379 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4381 // Size of the linkage area, parameter list area and the part of the local
4382 // space variable where copies of aggregates which are passed by value are
4384 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4386 // Calculate by how many bytes the stack has to be adjusted in case of tail
4387 // call optimization.
4388 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4390 // Adjust the stack pointer for the new arguments...
4391 // These operations are automatically eliminated by the prolog/epilog pass
4392 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4394 SDValue CallSeqStart = Chain;
4396 // Load the return address and frame pointer so it can be moved somewhere else
4399 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4402 // Set up a copy of the stack pointer for use loading and storing any
4403 // arguments that may not fit in the registers available for argument
4405 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4407 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4408 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4409 SmallVector<SDValue, 8> MemOpChains;
4411 bool seenFloatArg = false;
4412 // Walk the register/memloc assignments, inserting copies/loads.
4413 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4416 CCValAssign &VA = ArgLocs[i];
4417 SDValue Arg = OutVals[i];
4418 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4420 if (Flags.isByVal()) {
4421 // Argument is an aggregate which is passed by value, thus we need to
4422 // create a copy of it in the local variable space of the current stack
4423 // frame (which is the stack frame of the caller) and pass the address of
4424 // this copy to the callee.
4425 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4426 CCValAssign &ByValVA = ByValArgLocs[j++];
4427 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4429 // Memory reserved in the local variable space of the callers stack frame.
4430 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4432 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4433 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4435 // Create a copy of the argument in the local area of the current
4437 SDValue MemcpyCall =
4438 CreateCopyOfByValArgument(Arg, PtrOff,
4439 CallSeqStart.getNode()->getOperand(0),
4442 // This must go outside the CALLSEQ_START..END.
4443 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4444 CallSeqStart.getNode()->getOperand(1),
4446 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4447 NewCallSeqStart.getNode());
4448 Chain = CallSeqStart = NewCallSeqStart;
4450 // Pass the address of the aggregate copy on the stack either in a
4451 // physical register or in the parameter list area of the current stack
4452 // frame to the callee.
4456 if (VA.isRegLoc()) {
4457 if (Arg.getValueType() == MVT::i1)
4458 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4460 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4461 // Put argument in a physical register.
4462 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4464 // Put argument in the parameter list area of the current stack frame.
4465 assert(VA.isMemLoc());
4466 unsigned LocMemOffset = VA.getLocMemOffset();
4469 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4470 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4472 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4473 MachinePointerInfo(),
4476 // Calculate and remember argument location.
4477 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4483 if (!MemOpChains.empty())
4484 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4486 // Build a sequence of copy-to-reg nodes chained together with token chain
4487 // and flag operands which copy the outgoing args into the appropriate regs.
4489 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4490 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4491 RegsToPass[i].second, InFlag);
4492 InFlag = Chain.getValue(1);
4495 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4498 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4499 SDValue Ops[] = { Chain, InFlag };
4501 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4502 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4504 InFlag = Chain.getValue(1);
4508 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4509 false, TailCallArguments);
4511 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4512 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4513 NumBytes, Ins, InVals, CS);
4516 // Copy an argument into memory, being careful to do this outside the
4517 // call sequence for the call to which the argument belongs.
4519 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4520 SDValue CallSeqStart,
4521 ISD::ArgFlagsTy Flags,
4524 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4525 CallSeqStart.getNode()->getOperand(0),
4527 // The MEMCPY must go outside the CALLSEQ_START..END.
4528 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4529 CallSeqStart.getNode()->getOperand(1),
4531 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4532 NewCallSeqStart.getNode());
4533 return NewCallSeqStart;
4537 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4538 CallingConv::ID CallConv, bool isVarArg,
4539 bool isTailCall, bool IsPatchPoint,
4540 const SmallVectorImpl<ISD::OutputArg> &Outs,
4541 const SmallVectorImpl<SDValue> &OutVals,
4542 const SmallVectorImpl<ISD::InputArg> &Ins,
4543 SDLoc dl, SelectionDAG &DAG,
4544 SmallVectorImpl<SDValue> &InVals,
4545 ImmutableCallSite *CS) const {
4547 bool isELFv2ABI = Subtarget.isELFv2ABI();
4548 bool isLittleEndian = Subtarget.isLittleEndian();
4549 unsigned NumOps = Outs.size();
4551 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4552 unsigned PtrByteSize = 8;
4554 MachineFunction &MF = DAG.getMachineFunction();
4556 // Mark this function as potentially containing a function that contains a
4557 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4558 // and restoring the callers stack pointer in this functions epilog. This is
4559 // done because by tail calling the called function might overwrite the value
4560 // in this function's (MF) stack pointer stack slot 0(SP).
4561 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4562 CallConv == CallingConv::Fast)
4563 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4565 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4566 "fastcc not supported on varargs functions");
4568 // Count how many bytes are to be pushed on the stack, including the linkage
4569 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4570 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4571 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4572 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4573 unsigned NumBytes = LinkageSize;
4574 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4575 unsigned &QFPR_idx = FPR_idx;
4577 static const MCPhysReg GPR[] = {
4578 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4579 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4581 static const MCPhysReg *FPR = GetFPR();
4583 static const MCPhysReg VR[] = {
4584 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4585 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4587 static const MCPhysReg VSRH[] = {
4588 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4589 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4592 static const MCPhysReg *QFPR = GetQFPR();
4594 const unsigned NumGPRs = array_lengthof(GPR);
4595 const unsigned NumFPRs = 13;
4596 const unsigned NumVRs = array_lengthof(VR);
4597 const unsigned NumQFPRs = NumFPRs;
4599 // When using the fast calling convention, we don't provide backing for
4600 // arguments that will be in registers.
4601 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4603 // Add up all the space actually used.
4604 for (unsigned i = 0; i != NumOps; ++i) {
4605 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4606 EVT ArgVT = Outs[i].VT;
4607 EVT OrigVT = Outs[i].ArgVT;
4609 if (CallConv == CallingConv::Fast) {
4610 if (Flags.isByVal())
4611 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4613 switch (ArgVT.getSimpleVT().SimpleTy) {
4614 default: llvm_unreachable("Unexpected ValueType for argument!");
4618 if (++NumGPRsUsed <= NumGPRs)
4626 if (++NumVRsUsed <= NumVRs)
4630 // When using QPX, this is handled like a FP register, otherwise, it
4631 // is an Altivec register.
4632 if (Subtarget.hasQPX()) {
4633 if (++NumFPRsUsed <= NumFPRs)
4636 if (++NumVRsUsed <= NumVRs)
4642 case MVT::v4f64: // QPX
4643 case MVT::v4i1: // QPX
4644 if (++NumFPRsUsed <= NumFPRs)
4650 /* Respect alignment of argument on the stack. */
4652 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4653 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4655 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4656 if (Flags.isInConsecutiveRegsLast())
4657 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4660 unsigned NumBytesActuallyUsed = NumBytes;
4662 // The prolog code of the callee may store up to 8 GPR argument registers to
4663 // the stack, allowing va_start to index over them in memory if its varargs.
4664 // Because we cannot tell if this is needed on the caller side, we have to
4665 // conservatively assume that it is needed. As such, make sure we have at
4666 // least enough stack space for the caller to store the 8 GPRs.
4667 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4668 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4670 // Tail call needs the stack to be aligned.
4671 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4672 CallConv == CallingConv::Fast)
4673 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4675 // Calculate by how many bytes the stack has to be adjusted in case of tail
4676 // call optimization.
4677 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4679 // To protect arguments on the stack from being clobbered in a tail call,
4680 // force all the loads to happen before doing any other lowering.
4682 Chain = DAG.getStackArgumentTokenFactor(Chain);
4684 // Adjust the stack pointer for the new arguments...
4685 // These operations are automatically eliminated by the prolog/epilog pass
4686 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4688 SDValue CallSeqStart = Chain;
4690 // Load the return address and frame pointer so it can be move somewhere else
4693 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4696 // Set up a copy of the stack pointer for use loading and storing any
4697 // arguments that may not fit in the registers available for argument
4699 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4701 // Figure out which arguments are going to go in registers, and which in
4702 // memory. Also, if this is a vararg function, floating point operations
4703 // must be stored to our stack, and loaded into integer regs as well, if
4704 // any integer regs are available for argument passing.
4705 unsigned ArgOffset = LinkageSize;
4707 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4708 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4710 SmallVector<SDValue, 8> MemOpChains;
4711 for (unsigned i = 0; i != NumOps; ++i) {
4712 SDValue Arg = OutVals[i];
4713 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4714 EVT ArgVT = Outs[i].VT;
4715 EVT OrigVT = Outs[i].ArgVT;
4717 // PtrOff will be used to store the current argument to the stack if a
4718 // register cannot be found for it.
4721 // We re-align the argument offset for each argument, except when using the
4722 // fast calling convention, when we need to make sure we do that only when
4723 // we'll actually use a stack slot.
4724 auto ComputePtrOff = [&]() {
4725 /* Respect alignment of argument on the stack. */
4727 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4728 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4730 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4732 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4735 if (CallConv != CallingConv::Fast) {
4738 /* Compute GPR index associated with argument offset. */
4739 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4740 GPR_idx = std::min(GPR_idx, NumGPRs);
4743 // Promote integers to 64-bit values.
4744 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4745 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4746 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4747 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4750 // FIXME memcpy is used way more than necessary. Correctness first.
4751 // Note: "by value" is code for passing a structure by value, not
4753 if (Flags.isByVal()) {
4754 // Note: Size includes alignment padding, so
4755 // struct x { short a; char b; }
4756 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4757 // These are the proper values we need for right-justifying the
4758 // aggregate in a parameter register.
4759 unsigned Size = Flags.getByValSize();
4761 // An empty aggregate parameter takes up no storage and no
4766 if (CallConv == CallingConv::Fast)
4769 // All aggregates smaller than 8 bytes must be passed right-justified.
4770 if (Size==1 || Size==2 || Size==4) {
4771 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4772 if (GPR_idx != NumGPRs) {
4773 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4774 MachinePointerInfo(), VT,
4775 false, false, false, 0);
4776 MemOpChains.push_back(Load.getValue(1));
4777 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4779 ArgOffset += PtrByteSize;
4784 if (GPR_idx == NumGPRs && Size < 8) {
4785 SDValue AddPtr = PtrOff;
4786 if (!isLittleEndian) {
4787 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4788 PtrOff.getValueType());
4789 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4791 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4794 ArgOffset += PtrByteSize;
4797 // Copy entire object into memory. There are cases where gcc-generated
4798 // code assumes it is there, even if it could be put entirely into
4799 // registers. (This is not what the doc says.)
4801 // FIXME: The above statement is likely due to a misunderstanding of the
4802 // documents. All arguments must be copied into the parameter area BY
4803 // THE CALLEE in the event that the callee takes the address of any
4804 // formal argument. That has not yet been implemented. However, it is
4805 // reasonable to use the stack area as a staging area for the register
4808 // Skip this for small aggregates, as we will use the same slot for a
4809 // right-justified copy, below.
4811 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4815 // When a register is available, pass a small aggregate right-justified.
4816 if (Size < 8 && GPR_idx != NumGPRs) {
4817 // The easiest way to get this right-justified in a register
4818 // is to copy the structure into the rightmost portion of a
4819 // local variable slot, then load the whole slot into the
4821 // FIXME: The memcpy seems to produce pretty awful code for
4822 // small aggregates, particularly for packed ones.
4823 // FIXME: It would be preferable to use the slot in the
4824 // parameter save area instead of a new local variable.
4825 SDValue AddPtr = PtrOff;
4826 if (!isLittleEndian) {
4827 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4828 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4830 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4834 // Load the slot into the register.
4835 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4836 MachinePointerInfo(),
4837 false, false, false, 0);
4838 MemOpChains.push_back(Load.getValue(1));
4839 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4841 // Done with this argument.
4842 ArgOffset += PtrByteSize;
4846 // For aggregates larger than PtrByteSize, copy the pieces of the
4847 // object that fit into registers from the parameter save area.
4848 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4849 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4850 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4851 if (GPR_idx != NumGPRs) {
4852 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4853 MachinePointerInfo(),
4854 false, false, false, 0);
4855 MemOpChains.push_back(Load.getValue(1));
4856 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4857 ArgOffset += PtrByteSize;
4859 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4866 switch (Arg.getSimpleValueType().SimpleTy) {
4867 default: llvm_unreachable("Unexpected ValueType for argument!");
4871 // These can be scalar arguments or elements of an integer array type
4872 // passed directly. Clang may use those instead of "byval" aggregate
4873 // types to avoid forcing arguments to memory unnecessarily.
4874 if (GPR_idx != NumGPRs) {
4875 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4877 if (CallConv == CallingConv::Fast)
4880 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4881 true, isTailCall, false, MemOpChains,
4882 TailCallArguments, dl);
4883 if (CallConv == CallingConv::Fast)
4884 ArgOffset += PtrByteSize;
4886 if (CallConv != CallingConv::Fast)
4887 ArgOffset += PtrByteSize;
4891 // These can be scalar arguments or elements of a float array type
4892 // passed directly. The latter are used to implement ELFv2 homogenous
4893 // float aggregates.
4895 // Named arguments go into FPRs first, and once they overflow, the
4896 // remaining arguments go into GPRs and then the parameter save area.
4897 // Unnamed arguments for vararg functions always go to GPRs and
4898 // then the parameter save area. For now, put all arguments to vararg
4899 // routines always in both locations (FPR *and* GPR or stack slot).
4900 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4901 bool NeededLoad = false;
4903 // First load the argument into the next available FPR.
4904 if (FPR_idx != NumFPRs)
4905 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4907 // Next, load the argument into GPR or stack slot if needed.
4908 if (!NeedGPROrStack)
4910 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4911 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4912 // once we support fp <-> gpr moves.
4914 // In the non-vararg case, this can only ever happen in the
4915 // presence of f32 array types, since otherwise we never run
4916 // out of FPRs before running out of GPRs.
4919 // Double values are always passed in a single GPR.
4920 if (Arg.getValueType() != MVT::f32) {
4921 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4923 // Non-array float values are extended and passed in a GPR.
4924 } else if (!Flags.isInConsecutiveRegs()) {
4925 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4926 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4928 // If we have an array of floats, we collect every odd element
4929 // together with its predecessor into one GPR.
4930 } else if (ArgOffset % PtrByteSize != 0) {
4932 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4933 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4934 if (!isLittleEndian)
4936 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4938 // The final element, if even, goes into the first half of a GPR.
4939 } else if (Flags.isInConsecutiveRegsLast()) {
4940 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4941 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4942 if (!isLittleEndian)
4943 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4944 DAG.getConstant(32, MVT::i32));
4946 // Non-final even elements are skipped; they will be handled
4947 // together the with subsequent argument on the next go-around.
4951 if (ArgVal.getNode())
4952 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4954 if (CallConv == CallingConv::Fast)
4957 // Single-precision floating-point values are mapped to the
4958 // second (rightmost) word of the stack doubleword.
4959 if (Arg.getValueType() == MVT::f32 &&
4960 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4961 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4962 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4965 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4966 true, isTailCall, false, MemOpChains,
4967 TailCallArguments, dl);
4971 // When passing an array of floats, the array occupies consecutive
4972 // space in the argument area; only round up to the next doubleword
4973 // at the end of the array. Otherwise, each float takes 8 bytes.
4974 if (CallConv != CallingConv::Fast || NeededLoad) {
4975 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4976 Flags.isInConsecutiveRegs()) ? 4 : 8;
4977 if (Flags.isInConsecutiveRegsLast())
4978 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4988 if (!Subtarget.hasQPX()) {
4989 // These can be scalar arguments or elements of a vector array type
4990 // passed directly. The latter are used to implement ELFv2 homogenous
4991 // vector aggregates.
4993 // For a varargs call, named arguments go into VRs or on the stack as
4994 // usual; unnamed arguments always go to the stack or the corresponding
4995 // GPRs when within range. For now, we always put the value in both
4996 // locations (or even all three).
4998 // We could elide this store in the case where the object fits
4999 // entirely in R registers. Maybe later.
5000 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5001 MachinePointerInfo(), false, false, 0);
5002 MemOpChains.push_back(Store);
5003 if (VR_idx != NumVRs) {
5004 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5005 MachinePointerInfo(),
5006 false, false, false, 0);
5007 MemOpChains.push_back(Load.getValue(1));
5009 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5010 Arg.getSimpleValueType() == MVT::v2i64) ?
5011 VSRH[VR_idx] : VR[VR_idx];
5014 RegsToPass.push_back(std::make_pair(VReg, Load));
5017 for (unsigned i=0; i<16; i+=PtrByteSize) {
5018 if (GPR_idx == NumGPRs)
5020 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5021 DAG.getConstant(i, PtrVT));
5022 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5023 false, false, false, 0);
5024 MemOpChains.push_back(Load.getValue(1));
5025 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5030 // Non-varargs Altivec params go into VRs or on the stack.
5031 if (VR_idx != NumVRs) {
5032 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5033 Arg.getSimpleValueType() == MVT::v2i64) ?
5034 VSRH[VR_idx] : VR[VR_idx];
5037 RegsToPass.push_back(std::make_pair(VReg, Arg));
5039 if (CallConv == CallingConv::Fast)
5042 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5043 true, isTailCall, true, MemOpChains,
5044 TailCallArguments, dl);
5045 if (CallConv == CallingConv::Fast)
5049 if (CallConv != CallingConv::Fast)
5054 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5055 "Invalid QPX parameter type");
5060 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5062 // We could elide this store in the case where the object fits
5063 // entirely in R registers. Maybe later.
5064 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5065 MachinePointerInfo(), false, false, 0);
5066 MemOpChains.push_back(Store);
5067 if (QFPR_idx != NumQFPRs) {
5068 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5069 Store, PtrOff, MachinePointerInfo(),
5070 false, false, false, 0);
5071 MemOpChains.push_back(Load.getValue(1));
5072 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5074 ArgOffset += (IsF32 ? 16 : 32);
5075 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5076 if (GPR_idx == NumGPRs)
5078 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5079 DAG.getConstant(i, PtrVT));
5080 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5081 false, false, false, 0);
5082 MemOpChains.push_back(Load.getValue(1));
5083 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5088 // Non-varargs QPX params go into registers or on the stack.
5089 if (QFPR_idx != NumQFPRs) {
5090 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5092 if (CallConv == CallingConv::Fast)
5095 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5096 true, isTailCall, true, MemOpChains,
5097 TailCallArguments, dl);
5098 if (CallConv == CallingConv::Fast)
5099 ArgOffset += (IsF32 ? 16 : 32);
5102 if (CallConv != CallingConv::Fast)
5103 ArgOffset += (IsF32 ? 16 : 32);
5109 assert(NumBytesActuallyUsed == ArgOffset);
5110 (void)NumBytesActuallyUsed;
5112 if (!MemOpChains.empty())
5113 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5115 // Check if this is an indirect call (MTCTR/BCTRL).
5116 // See PrepareCall() for more information about calls through function
5117 // pointers in the 64-bit SVR4 ABI.
5118 if (!isTailCall && !IsPatchPoint &&
5119 !isFunctionGlobalAddress(Callee) &&
5120 !isa<ExternalSymbolSDNode>(Callee)) {
5121 // Load r2 into a virtual register and store it to the TOC save area.
5122 setUsesTOCBasePtr(DAG);
5123 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5124 // TOC save area offset.
5125 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5126 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5127 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5128 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5129 MachinePointerInfo::getStack(TOCSaveOffset),
5131 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5132 // This does not mean the MTCTR instruction must use R12; it's easier
5133 // to model this as an extra parameter, so do that.
5134 if (isELFv2ABI && !IsPatchPoint)
5135 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5138 // Build a sequence of copy-to-reg nodes chained together with token chain
5139 // and flag operands which copy the outgoing args into the appropriate regs.
5141 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5142 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5143 RegsToPass[i].second, InFlag);
5144 InFlag = Chain.getValue(1);
5148 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5149 FPOp, true, TailCallArguments);
5151 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5152 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5153 NumBytes, Ins, InVals, CS);
5157 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5158 CallingConv::ID CallConv, bool isVarArg,
5159 bool isTailCall, bool IsPatchPoint,
5160 const SmallVectorImpl<ISD::OutputArg> &Outs,
5161 const SmallVectorImpl<SDValue> &OutVals,
5162 const SmallVectorImpl<ISD::InputArg> &Ins,
5163 SDLoc dl, SelectionDAG &DAG,
5164 SmallVectorImpl<SDValue> &InVals,
5165 ImmutableCallSite *CS) const {
5167 unsigned NumOps = Outs.size();
5169 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5170 bool isPPC64 = PtrVT == MVT::i64;
5171 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5173 MachineFunction &MF = DAG.getMachineFunction();
5175 // Mark this function as potentially containing a function that contains a
5176 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5177 // and restoring the callers stack pointer in this functions epilog. This is
5178 // done because by tail calling the called function might overwrite the value
5179 // in this function's (MF) stack pointer stack slot 0(SP).
5180 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5181 CallConv == CallingConv::Fast)
5182 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5184 // Count how many bytes are to be pushed on the stack, including the linkage
5185 // area, and parameter passing area. We start with 24/48 bytes, which is
5186 // prereserved space for [SP][CR][LR][3 x unused].
5187 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5188 unsigned NumBytes = LinkageSize;
5190 // Add up all the space actually used.
5191 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5192 // they all go in registers, but we must reserve stack space for them for
5193 // possible use by the caller. In varargs or 64-bit calls, parameters are
5194 // assigned stack space in order, with padding so Altivec parameters are
5196 unsigned nAltivecParamsAtEnd = 0;
5197 for (unsigned i = 0; i != NumOps; ++i) {
5198 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5199 EVT ArgVT = Outs[i].VT;
5200 // Varargs Altivec parameters are padded to a 16 byte boundary.
5201 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5202 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5203 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5204 if (!isVarArg && !isPPC64) {
5205 // Non-varargs Altivec parameters go after all the non-Altivec
5206 // parameters; handle those later so we know how much padding we need.
5207 nAltivecParamsAtEnd++;
5210 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5211 NumBytes = ((NumBytes+15)/16)*16;
5213 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5216 // Allow for Altivec parameters at the end, if needed.
5217 if (nAltivecParamsAtEnd) {
5218 NumBytes = ((NumBytes+15)/16)*16;
5219 NumBytes += 16*nAltivecParamsAtEnd;
5222 // The prolog code of the callee may store up to 8 GPR argument registers to
5223 // the stack, allowing va_start to index over them in memory if its varargs.
5224 // Because we cannot tell if this is needed on the caller side, we have to
5225 // conservatively assume that it is needed. As such, make sure we have at
5226 // least enough stack space for the caller to store the 8 GPRs.
5227 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5229 // Tail call needs the stack to be aligned.
5230 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5231 CallConv == CallingConv::Fast)
5232 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5234 // Calculate by how many bytes the stack has to be adjusted in case of tail
5235 // call optimization.
5236 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5238 // To protect arguments on the stack from being clobbered in a tail call,
5239 // force all the loads to happen before doing any other lowering.
5241 Chain = DAG.getStackArgumentTokenFactor(Chain);
5243 // Adjust the stack pointer for the new arguments...
5244 // These operations are automatically eliminated by the prolog/epilog pass
5245 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5247 SDValue CallSeqStart = Chain;
5249 // Load the return address and frame pointer so it can be move somewhere else
5252 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5255 // Set up a copy of the stack pointer for use loading and storing any
5256 // arguments that may not fit in the registers available for argument
5260 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5262 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5264 // Figure out which arguments are going to go in registers, and which in
5265 // memory. Also, if this is a vararg function, floating point operations
5266 // must be stored to our stack, and loaded into integer regs as well, if
5267 // any integer regs are available for argument passing.
5268 unsigned ArgOffset = LinkageSize;
5269 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5271 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5272 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5273 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5275 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5276 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5277 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5279 static const MCPhysReg *FPR = GetFPR();
5281 static const MCPhysReg VR[] = {
5282 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5283 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5285 const unsigned NumGPRs = array_lengthof(GPR_32);
5286 const unsigned NumFPRs = 13;
5287 const unsigned NumVRs = array_lengthof(VR);
5289 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5291 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5292 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5294 SmallVector<SDValue, 8> MemOpChains;
5295 for (unsigned i = 0; i != NumOps; ++i) {
5296 SDValue Arg = OutVals[i];
5297 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5299 // PtrOff will be used to store the current argument to the stack if a
5300 // register cannot be found for it.
5303 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5305 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5307 // On PPC64, promote integers to 64-bit values.
5308 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5309 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5310 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5311 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5314 // FIXME memcpy is used way more than necessary. Correctness first.
5315 // Note: "by value" is code for passing a structure by value, not
5317 if (Flags.isByVal()) {
5318 unsigned Size = Flags.getByValSize();
5319 // Very small objects are passed right-justified. Everything else is
5320 // passed left-justified.
5321 if (Size==1 || Size==2) {
5322 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5323 if (GPR_idx != NumGPRs) {
5324 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5325 MachinePointerInfo(), VT,
5326 false, false, false, 0);
5327 MemOpChains.push_back(Load.getValue(1));
5328 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5330 ArgOffset += PtrByteSize;
5332 SDValue Const = DAG.getConstant(PtrByteSize - Size,
5333 PtrOff.getValueType());
5334 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5335 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5338 ArgOffset += PtrByteSize;
5342 // Copy entire object into memory. There are cases where gcc-generated
5343 // code assumes it is there, even if it could be put entirely into
5344 // registers. (This is not what the doc says.)
5345 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5349 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5350 // copy the pieces of the object that fit into registers from the
5351 // parameter save area.
5352 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5353 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5354 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5355 if (GPR_idx != NumGPRs) {
5356 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5357 MachinePointerInfo(),
5358 false, false, false, 0);
5359 MemOpChains.push_back(Load.getValue(1));
5360 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5361 ArgOffset += PtrByteSize;
5363 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5370 switch (Arg.getSimpleValueType().SimpleTy) {
5371 default: llvm_unreachable("Unexpected ValueType for argument!");
5375 if (GPR_idx != NumGPRs) {
5376 if (Arg.getValueType() == MVT::i1)
5377 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5379 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5381 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5382 isPPC64, isTailCall, false, MemOpChains,
5383 TailCallArguments, dl);
5385 ArgOffset += PtrByteSize;
5389 if (FPR_idx != NumFPRs) {
5390 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5393 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5394 MachinePointerInfo(), false, false, 0);
5395 MemOpChains.push_back(Store);
5397 // Float varargs are always shadowed in available integer registers
5398 if (GPR_idx != NumGPRs) {
5399 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5400 MachinePointerInfo(), false, false,
5402 MemOpChains.push_back(Load.getValue(1));
5403 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5405 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5406 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5407 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5408 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5409 MachinePointerInfo(),
5410 false, false, false, 0);
5411 MemOpChains.push_back(Load.getValue(1));
5412 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5415 // If we have any FPRs remaining, we may also have GPRs remaining.
5416 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5418 if (GPR_idx != NumGPRs)
5420 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5421 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5425 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5426 isPPC64, isTailCall, false, MemOpChains,
5427 TailCallArguments, dl);
5431 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5438 // These go aligned on the stack, or in the corresponding R registers
5439 // when within range. The Darwin PPC ABI doc claims they also go in
5440 // V registers; in fact gcc does this only for arguments that are
5441 // prototyped, not for those that match the ... We do it for all
5442 // arguments, seems to work.
5443 while (ArgOffset % 16 !=0) {
5444 ArgOffset += PtrByteSize;
5445 if (GPR_idx != NumGPRs)
5448 // We could elide this store in the case where the object fits
5449 // entirely in R registers. Maybe later.
5450 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5451 DAG.getConstant(ArgOffset, PtrVT));
5452 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5453 MachinePointerInfo(), false, false, 0);
5454 MemOpChains.push_back(Store);
5455 if (VR_idx != NumVRs) {
5456 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5457 MachinePointerInfo(),
5458 false, false, false, 0);
5459 MemOpChains.push_back(Load.getValue(1));
5460 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5463 for (unsigned i=0; i<16; i+=PtrByteSize) {
5464 if (GPR_idx == NumGPRs)
5466 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5467 DAG.getConstant(i, PtrVT));
5468 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5469 false, false, false, 0);
5470 MemOpChains.push_back(Load.getValue(1));
5471 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5476 // Non-varargs Altivec params generally go in registers, but have
5477 // stack space allocated at the end.
5478 if (VR_idx != NumVRs) {
5479 // Doesn't have GPR space allocated.
5480 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5481 } else if (nAltivecParamsAtEnd==0) {
5482 // We are emitting Altivec params in order.
5483 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5484 isPPC64, isTailCall, true, MemOpChains,
5485 TailCallArguments, dl);
5491 // If all Altivec parameters fit in registers, as they usually do,
5492 // they get stack space following the non-Altivec parameters. We
5493 // don't track this here because nobody below needs it.
5494 // If there are more Altivec parameters than fit in registers emit
5496 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5498 // Offset is aligned; skip 1st 12 params which go in V registers.
5499 ArgOffset = ((ArgOffset+15)/16)*16;
5501 for (unsigned i = 0; i != NumOps; ++i) {
5502 SDValue Arg = OutVals[i];
5503 EVT ArgType = Outs[i].VT;
5504 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5505 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5508 // We are emitting Altivec params in order.
5509 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5510 isPPC64, isTailCall, true, MemOpChains,
5511 TailCallArguments, dl);
5518 if (!MemOpChains.empty())
5519 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5521 // On Darwin, R12 must contain the address of an indirect callee. This does
5522 // not mean the MTCTR instruction must use R12; it's easier to model this as
5523 // an extra parameter, so do that.
5525 !isFunctionGlobalAddress(Callee) &&
5526 !isa<ExternalSymbolSDNode>(Callee) &&
5527 !isBLACompatibleAddress(Callee, DAG))
5528 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5529 PPC::R12), Callee));
5531 // Build a sequence of copy-to-reg nodes chained together with token chain
5532 // and flag operands which copy the outgoing args into the appropriate regs.
5534 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5535 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5536 RegsToPass[i].second, InFlag);
5537 InFlag = Chain.getValue(1);
5541 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5542 FPOp, true, TailCallArguments);
5544 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5545 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5546 NumBytes, Ins, InVals, CS);
5550 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5551 MachineFunction &MF, bool isVarArg,
5552 const SmallVectorImpl<ISD::OutputArg> &Outs,
5553 LLVMContext &Context) const {
5554 SmallVector<CCValAssign, 16> RVLocs;
5555 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5556 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5560 PPCTargetLowering::LowerReturn(SDValue Chain,
5561 CallingConv::ID CallConv, bool isVarArg,
5562 const SmallVectorImpl<ISD::OutputArg> &Outs,
5563 const SmallVectorImpl<SDValue> &OutVals,
5564 SDLoc dl, SelectionDAG &DAG) const {
5566 SmallVector<CCValAssign, 16> RVLocs;
5567 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5569 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5572 SmallVector<SDValue, 4> RetOps(1, Chain);
5574 // Copy the result values into the output registers.
5575 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5576 CCValAssign &VA = RVLocs[i];
5577 assert(VA.isRegLoc() && "Can only return in registers!");
5579 SDValue Arg = OutVals[i];
5581 switch (VA.getLocInfo()) {
5582 default: llvm_unreachable("Unknown loc info!");
5583 case CCValAssign::Full: break;
5584 case CCValAssign::AExt:
5585 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5587 case CCValAssign::ZExt:
5588 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5590 case CCValAssign::SExt:
5591 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5595 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5596 Flag = Chain.getValue(1);
5597 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5600 RetOps[0] = Chain; // Update chain.
5602 // Add the flag if we have it.
5604 RetOps.push_back(Flag);
5606 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5609 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5610 const PPCSubtarget &Subtarget) const {
5611 // When we pop the dynamic allocation we need to restore the SP link.
5614 // Get the corect type for pointers.
5615 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5617 // Construct the stack pointer operand.
5618 bool isPPC64 = Subtarget.isPPC64();
5619 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5620 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5622 // Get the operands for the STACKRESTORE.
5623 SDValue Chain = Op.getOperand(0);
5624 SDValue SaveSP = Op.getOperand(1);
5626 // Load the old link SP.
5627 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5628 MachinePointerInfo(),
5629 false, false, false, 0);
5631 // Restore the stack pointer.
5632 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5634 // Store the old link SP.
5635 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5642 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5643 MachineFunction &MF = DAG.getMachineFunction();
5644 bool isPPC64 = Subtarget.isPPC64();
5645 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5647 // Get current frame pointer save index. The users of this index will be
5648 // primarily DYNALLOC instructions.
5649 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5650 int RASI = FI->getReturnAddrSaveIndex();
5652 // If the frame pointer save index hasn't been defined yet.
5654 // Find out what the fix offset of the frame pointer save area.
5655 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5656 // Allocate the frame index for frame pointer save area.
5657 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5659 FI->setReturnAddrSaveIndex(RASI);
5661 return DAG.getFrameIndex(RASI, PtrVT);
5665 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5666 MachineFunction &MF = DAG.getMachineFunction();
5667 bool isPPC64 = Subtarget.isPPC64();
5668 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5670 // Get current frame pointer save index. The users of this index will be
5671 // primarily DYNALLOC instructions.
5672 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5673 int FPSI = FI->getFramePointerSaveIndex();
5675 // If the frame pointer save index hasn't been defined yet.
5677 // Find out what the fix offset of the frame pointer save area.
5678 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5679 // Allocate the frame index for frame pointer save area.
5680 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5682 FI->setFramePointerSaveIndex(FPSI);
5684 return DAG.getFrameIndex(FPSI, PtrVT);
5687 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5689 const PPCSubtarget &Subtarget) const {
5691 SDValue Chain = Op.getOperand(0);
5692 SDValue Size = Op.getOperand(1);
5695 // Get the corect type for pointers.
5696 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5698 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5699 DAG.getConstant(0, PtrVT), Size);
5700 // Construct a node for the frame pointer save index.
5701 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5702 // Build a DYNALLOC node.
5703 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5704 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5705 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5708 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5709 SelectionDAG &DAG) const {
5711 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5712 DAG.getVTList(MVT::i32, MVT::Other),
5713 Op.getOperand(0), Op.getOperand(1));
5716 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5717 SelectionDAG &DAG) const {
5719 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5720 Op.getOperand(0), Op.getOperand(1));
5723 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5724 if (Op.getValueType().isVector())
5725 return LowerVectorLoad(Op, DAG);
5727 assert(Op.getValueType() == MVT::i1 &&
5728 "Custom lowering only for i1 loads");
5730 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5733 LoadSDNode *LD = cast<LoadSDNode>(Op);
5735 SDValue Chain = LD->getChain();
5736 SDValue BasePtr = LD->getBasePtr();
5737 MachineMemOperand *MMO = LD->getMemOperand();
5739 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5740 BasePtr, MVT::i8, MMO);
5741 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5743 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5744 return DAG.getMergeValues(Ops, dl);
5747 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5748 if (Op.getOperand(1).getValueType().isVector())
5749 return LowerVectorStore(Op, DAG);
5751 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5752 "Custom lowering only for i1 stores");
5754 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5757 StoreSDNode *ST = cast<StoreSDNode>(Op);
5759 SDValue Chain = ST->getChain();
5760 SDValue BasePtr = ST->getBasePtr();
5761 SDValue Value = ST->getValue();
5762 MachineMemOperand *MMO = ST->getMemOperand();
5764 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5765 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5768 // FIXME: Remove this once the ANDI glue bug is fixed:
5769 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5770 assert(Op.getValueType() == MVT::i1 &&
5771 "Custom lowering only for i1 results");
5774 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5778 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5780 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5781 // Not FP? Not a fsel.
5782 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5783 !Op.getOperand(2).getValueType().isFloatingPoint())
5786 // We might be able to do better than this under some circumstances, but in
5787 // general, fsel-based lowering of select is a finite-math-only optimization.
5788 // For more information, see section F.3 of the 2.06 ISA specification.
5789 if (!DAG.getTarget().Options.NoInfsFPMath ||
5790 !DAG.getTarget().Options.NoNaNsFPMath)
5793 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5795 EVT ResVT = Op.getValueType();
5796 EVT CmpVT = Op.getOperand(0).getValueType();
5797 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5798 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5801 // If the RHS of the comparison is a 0.0, we don't need to do the
5802 // subtraction at all.
5804 if (isFloatingPointZero(RHS))
5806 default: break; // SETUO etc aren't handled by fsel.
5810 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5811 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5812 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5813 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5814 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5815 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5816 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5819 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5822 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5823 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5824 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5827 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5830 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5831 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5832 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5833 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5838 default: break; // SETUO etc aren't handled by fsel.
5842 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5843 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5844 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5845 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5846 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5847 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5848 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5849 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5852 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5853 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5854 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5855 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5858 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5859 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5860 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5861 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5864 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5865 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5866 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5867 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5870 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5871 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5872 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5873 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5878 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5881 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5882 SDValue Src = Op.getOperand(0);
5883 if (Src.getValueType() == MVT::f32)
5884 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5887 switch (Op.getSimpleValueType().SimpleTy) {
5888 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5891 Op.getOpcode() == ISD::FP_TO_SINT
5893 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5897 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5898 "i64 FP_TO_UINT is supported only with FPCVT");
5899 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5905 // Convert the FP value to an int value through memory.
5906 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5907 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5908 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5909 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5910 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5912 // Emit a store to the stack slot.
5915 MachineFunction &MF = DAG.getMachineFunction();
5916 MachineMemOperand *MMO =
5917 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5918 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5919 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5920 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5922 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5923 MPI, false, false, 0);
5925 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5927 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5928 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5929 DAG.getConstant(4, FIPtr.getValueType()));
5930 MPI = MPI.getWithOffset(4);
5938 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5941 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5943 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5944 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5948 // We're trying to insert a regular store, S, and then a load, L. If the
5949 // incoming value, O, is a load, we might just be able to have our load use the
5950 // address used by O. However, we don't know if anything else will store to
5951 // that address before we can load from it. To prevent this situation, we need
5952 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5953 // the same chain operand as O, we create a token factor from the chain results
5954 // of O and L, and we replace all uses of O's chain result with that token
5955 // factor (see spliceIntoChain below for this last part).
5956 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5959 ISD::LoadExtType ET) const {
5961 if (ET == ISD::NON_EXTLOAD &&
5962 (Op.getOpcode() == ISD::FP_TO_UINT ||
5963 Op.getOpcode() == ISD::FP_TO_SINT) &&
5964 isOperationLegalOrCustom(Op.getOpcode(),
5965 Op.getOperand(0).getValueType())) {
5967 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5971 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5972 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5973 LD->isNonTemporal())
5975 if (LD->getMemoryVT() != MemVT)
5978 RLI.Ptr = LD->getBasePtr();
5979 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5980 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5981 "Non-pre-inc AM on PPC?");
5982 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5986 RLI.Chain = LD->getChain();
5987 RLI.MPI = LD->getPointerInfo();
5988 RLI.IsInvariant = LD->isInvariant();
5989 RLI.Alignment = LD->getAlignment();
5990 RLI.AAInfo = LD->getAAInfo();
5991 RLI.Ranges = LD->getRanges();
5993 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5997 // Given the head of the old chain, ResChain, insert a token factor containing
5998 // it and NewResChain, and make users of ResChain now be users of that token
6000 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6001 SDValue NewResChain,
6002 SelectionDAG &DAG) const {
6006 SDLoc dl(NewResChain);
6008 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6009 NewResChain, DAG.getUNDEF(MVT::Other));
6010 assert(TF.getNode() != NewResChain.getNode() &&
6011 "A new TF really is required here");
6013 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6014 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6017 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6018 SelectionDAG &DAG) const {
6021 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6022 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6025 SDValue Value = Op.getOperand(0);
6026 // The values are now known to be -1 (false) or 1 (true). To convert this
6027 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6028 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6029 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6031 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6032 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6033 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6035 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6037 if (Op.getValueType() != MVT::v4f64)
6038 Value = DAG.getNode(ISD::FP_ROUND, dl,
6039 Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6043 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6044 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6047 if (Op.getOperand(0).getValueType() == MVT::i1)
6048 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6049 DAG.getConstantFP(1.0, Op.getValueType()),
6050 DAG.getConstantFP(0.0, Op.getValueType()));
6052 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6053 "UINT_TO_FP is supported only with FPCVT");
6055 // If we have FCFIDS, then use it when converting to single-precision.
6056 // Otherwise, convert to double-precision and then round.
6057 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6058 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6060 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6062 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6066 if (Op.getOperand(0).getValueType() == MVT::i64) {
6067 SDValue SINT = Op.getOperand(0);
6068 // When converting to single-precision, we actually need to convert
6069 // to double-precision first and then round to single-precision.
6070 // To avoid double-rounding effects during that operation, we have
6071 // to prepare the input operand. Bits that might be truncated when
6072 // converting to double-precision are replaced by a bit that won't
6073 // be lost at this stage, but is below the single-precision rounding
6076 // However, if -enable-unsafe-fp-math is in effect, accept double
6077 // rounding to avoid the extra overhead.
6078 if (Op.getValueType() == MVT::f32 &&
6079 !Subtarget.hasFPCVT() &&
6080 !DAG.getTarget().Options.UnsafeFPMath) {
6082 // Twiddle input to make sure the low 11 bits are zero. (If this
6083 // is the case, we are guaranteed the value will fit into the 53 bit
6084 // mantissa of an IEEE double-precision value without rounding.)
6085 // If any of those low 11 bits were not zero originally, make sure
6086 // bit 12 (value 2048) is set instead, so that the final rounding
6087 // to single-precision gets the correct result.
6088 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6089 SINT, DAG.getConstant(2047, MVT::i64));
6090 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6091 Round, DAG.getConstant(2047, MVT::i64));
6092 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6093 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6094 Round, DAG.getConstant(-2048, MVT::i64));
6096 // However, we cannot use that value unconditionally: if the magnitude
6097 // of the input value is small, the bit-twiddling we did above might
6098 // end up visibly changing the output. Fortunately, in that case, we
6099 // don't need to twiddle bits since the original input will convert
6100 // exactly to double-precision floating-point already. Therefore,
6101 // construct a conditional to use the original value if the top 11
6102 // bits are all sign-bit copies, and use the rounded value computed
6104 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6105 SINT, DAG.getConstant(53, MVT::i32));
6106 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6107 Cond, DAG.getConstant(1, MVT::i64));
6108 Cond = DAG.getSetCC(dl, MVT::i32,
6109 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6111 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6117 MachineFunction &MF = DAG.getMachineFunction();
6118 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6119 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6120 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6122 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6123 } else if (Subtarget.hasLFIWAX() &&
6124 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6125 MachineMemOperand *MMO =
6126 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6127 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6128 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6129 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6130 DAG.getVTList(MVT::f64, MVT::Other),
6131 Ops, MVT::i32, MMO);
6132 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6133 } else if (Subtarget.hasFPCVT() &&
6134 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6135 MachineMemOperand *MMO =
6136 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6137 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6138 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6139 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6140 DAG.getVTList(MVT::f64, MVT::Other),
6141 Ops, MVT::i32, MMO);
6142 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6143 } else if (((Subtarget.hasLFIWAX() &&
6144 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6145 (Subtarget.hasFPCVT() &&
6146 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6147 SINT.getOperand(0).getValueType() == MVT::i32) {
6148 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6149 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6151 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6152 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6155 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6156 MachinePointerInfo::getFixedStack(FrameIdx),
6159 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6160 "Expected an i32 store");
6164 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6167 MachineMemOperand *MMO =
6168 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6169 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6170 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6171 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6172 PPCISD::LFIWZX : PPCISD::LFIWAX,
6173 dl, DAG.getVTList(MVT::f64, MVT::Other),
6174 Ops, MVT::i32, MMO);
6176 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6178 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6180 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6181 FP = DAG.getNode(ISD::FP_ROUND, dl,
6182 MVT::f32, FP, DAG.getIntPtrConstant(0));
6186 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6187 "Unhandled INT_TO_FP type in custom expander!");
6188 // Since we only generate this in 64-bit mode, we can take advantage of
6189 // 64-bit registers. In particular, sign extend the input value into the
6190 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6191 // then lfd it and fcfid it.
6192 MachineFunction &MF = DAG.getMachineFunction();
6193 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6194 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6197 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6200 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6202 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6203 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6205 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6206 MachinePointerInfo::getFixedStack(FrameIdx),
6209 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6210 "Expected an i32 store");
6214 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6218 MachineMemOperand *MMO =
6219 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6220 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6221 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6222 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6223 PPCISD::LFIWZX : PPCISD::LFIWAX,
6224 dl, DAG.getVTList(MVT::f64, MVT::Other),
6225 Ops, MVT::i32, MMO);
6227 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6229 assert(Subtarget.isPPC64() &&
6230 "i32->FP without LFIWAX supported only on PPC64");
6232 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6233 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6235 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6238 // STD the extended value into the stack slot.
6239 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6240 MachinePointerInfo::getFixedStack(FrameIdx),
6243 // Load the value as a double.
6244 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6245 MachinePointerInfo::getFixedStack(FrameIdx),
6246 false, false, false, 0);
6249 // FCFID it and return it.
6250 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6251 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6252 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6256 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6257 SelectionDAG &DAG) const {
6260 The rounding mode is in bits 30:31 of FPSR, and has the following
6267 FLT_ROUNDS, on the other hand, expects the following:
6274 To perform the conversion, we do:
6275 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6278 MachineFunction &MF = DAG.getMachineFunction();
6279 EVT VT = Op.getValueType();
6280 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6282 // Save FP Control Word to register
6284 MVT::f64, // return register
6285 MVT::Glue // unused in this context
6287 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6289 // Save FP register to stack slot
6290 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6291 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6292 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6293 StackSlot, MachinePointerInfo(), false, false,0);
6295 // Load FP Control Word from low 32 bits of stack slot.
6296 SDValue Four = DAG.getConstant(4, PtrVT);
6297 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6298 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6299 false, false, false, 0);
6301 // Transform as necessary
6303 DAG.getNode(ISD::AND, dl, MVT::i32,
6304 CWD, DAG.getConstant(3, MVT::i32));
6306 DAG.getNode(ISD::SRL, dl, MVT::i32,
6307 DAG.getNode(ISD::AND, dl, MVT::i32,
6308 DAG.getNode(ISD::XOR, dl, MVT::i32,
6309 CWD, DAG.getConstant(3, MVT::i32)),
6310 DAG.getConstant(3, MVT::i32)),
6311 DAG.getConstant(1, MVT::i32));
6314 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6316 return DAG.getNode((VT.getSizeInBits() < 16 ?
6317 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6320 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6321 EVT VT = Op.getValueType();
6322 unsigned BitWidth = VT.getSizeInBits();
6324 assert(Op.getNumOperands() == 3 &&
6325 VT == Op.getOperand(1).getValueType() &&
6328 // Expand into a bunch of logical ops. Note that these ops
6329 // depend on the PPC behavior for oversized shift amounts.
6330 SDValue Lo = Op.getOperand(0);
6331 SDValue Hi = Op.getOperand(1);
6332 SDValue Amt = Op.getOperand(2);
6333 EVT AmtVT = Amt.getValueType();
6335 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6336 DAG.getConstant(BitWidth, AmtVT), Amt);
6337 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6338 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6339 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6340 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6341 DAG.getConstant(-BitWidth, AmtVT));
6342 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6343 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6344 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6345 SDValue OutOps[] = { OutLo, OutHi };
6346 return DAG.getMergeValues(OutOps, dl);
6349 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6350 EVT VT = Op.getValueType();
6352 unsigned BitWidth = VT.getSizeInBits();
6353 assert(Op.getNumOperands() == 3 &&
6354 VT == Op.getOperand(1).getValueType() &&
6357 // Expand into a bunch of logical ops. Note that these ops
6358 // depend on the PPC behavior for oversized shift amounts.
6359 SDValue Lo = Op.getOperand(0);
6360 SDValue Hi = Op.getOperand(1);
6361 SDValue Amt = Op.getOperand(2);
6362 EVT AmtVT = Amt.getValueType();
6364 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6365 DAG.getConstant(BitWidth, AmtVT), Amt);
6366 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6367 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6368 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6369 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6370 DAG.getConstant(-BitWidth, AmtVT));
6371 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6372 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6373 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6374 SDValue OutOps[] = { OutLo, OutHi };
6375 return DAG.getMergeValues(OutOps, dl);
6378 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6380 EVT VT = Op.getValueType();
6381 unsigned BitWidth = VT.getSizeInBits();
6382 assert(Op.getNumOperands() == 3 &&
6383 VT == Op.getOperand(1).getValueType() &&
6386 // Expand into a bunch of logical ops, followed by a select_cc.
6387 SDValue Lo = Op.getOperand(0);
6388 SDValue Hi = Op.getOperand(1);
6389 SDValue Amt = Op.getOperand(2);
6390 EVT AmtVT = Amt.getValueType();
6392 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6393 DAG.getConstant(BitWidth, AmtVT), Amt);
6394 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6395 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6396 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6397 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6398 DAG.getConstant(-BitWidth, AmtVT));
6399 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6400 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6401 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6402 Tmp4, Tmp6, ISD::SETLE);
6403 SDValue OutOps[] = { OutLo, OutHi };
6404 return DAG.getMergeValues(OutOps, dl);
6407 //===----------------------------------------------------------------------===//
6408 // Vector related lowering.
6411 /// BuildSplatI - Build a canonical splati of Val with an element size of
6412 /// SplatSize. Cast the result to VT.
6413 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6414 SelectionDAG &DAG, SDLoc dl) {
6415 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6417 static const EVT VTys[] = { // canonical VT to use for each size.
6418 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6421 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6423 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6427 EVT CanonicalVT = VTys[SplatSize-1];
6429 // Build a canonical splat for this value.
6430 SDValue Elt = DAG.getConstant(Val, MVT::i32);
6431 SmallVector<SDValue, 8> Ops;
6432 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6433 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6434 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6437 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6438 /// specified intrinsic ID.
6439 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6440 SelectionDAG &DAG, SDLoc dl,
6441 EVT DestVT = MVT::Other) {
6442 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6443 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6444 DAG.getConstant(IID, MVT::i32), Op);
6447 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6448 /// specified intrinsic ID.
6449 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6450 SelectionDAG &DAG, SDLoc dl,
6451 EVT DestVT = MVT::Other) {
6452 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6453 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6454 DAG.getConstant(IID, MVT::i32), LHS, RHS);
6457 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6458 /// specified intrinsic ID.
6459 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6460 SDValue Op2, SelectionDAG &DAG,
6461 SDLoc dl, EVT DestVT = MVT::Other) {
6462 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6463 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6464 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6468 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6469 /// amount. The result has the specified value type.
6470 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6471 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6472 // Force LHS/RHS to be the right type.
6473 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6474 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6477 for (unsigned i = 0; i != 16; ++i)
6479 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6480 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6483 // If this is a case we can't handle, return null and let the default
6484 // expansion code take care of it. If we CAN select this case, and if it
6485 // selects to a single instruction, return Op. Otherwise, if we can codegen
6486 // this case more efficiently than a constant pool load, lower it to the
6487 // sequence of ops that should be used.
6488 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6489 SelectionDAG &DAG) const {
6491 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6492 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6494 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6495 // We first build an i32 vector, load it into a QPX register,
6496 // then convert it to a floating-point vector and compare it
6497 // to a zero vector to get the boolean result.
6498 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6499 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6500 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6501 EVT PtrVT = getPointerTy();
6502 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6504 assert(BVN->getNumOperands() == 4 &&
6505 "BUILD_VECTOR for v4i1 does not have 4 operands");
6507 bool IsConst = true;
6508 for (unsigned i = 0; i < 4; ++i) {
6509 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6510 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6518 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6520 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6522 SmallVector<Constant*, 4> CV(4, NegOne);
6523 for (unsigned i = 0; i < 4; ++i) {
6524 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6525 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6526 else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6527 getConstantIntValue()->isZero())
6533 Constant *CP = ConstantVector::get(CV);
6534 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6535 16 /* alignment */);
6537 SmallVector<SDValue, 2> Ops;
6538 Ops.push_back(DAG.getEntryNode());
6539 Ops.push_back(CPIdx);
6541 SmallVector<EVT, 2> ValueVTs;
6542 ValueVTs.push_back(MVT::v4i1);
6543 ValueVTs.push_back(MVT::Other); // chain
6544 SDVTList VTs = DAG.getVTList(ValueVTs);
6546 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6547 dl, VTs, Ops, MVT::v4f32,
6548 MachinePointerInfo::getConstantPool());
6551 SmallVector<SDValue, 4> Stores;
6552 for (unsigned i = 0; i < 4; ++i) {
6553 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6555 unsigned Offset = 4*i;
6556 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6557 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6559 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6560 if (StoreSize > 4) {
6561 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6562 BVN->getOperand(i), Idx,
6563 PtrInfo.getWithOffset(Offset),
6564 MVT::i32, false, false, 0));
6566 SDValue StoreValue = BVN->getOperand(i);
6568 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6570 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6572 PtrInfo.getWithOffset(Offset),
6578 if (!Stores.empty())
6579 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6581 StoreChain = DAG.getEntryNode();
6583 // Now load from v4i32 into the QPX register; this will extend it to
6584 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6585 // is typed as v4f64 because the QPX register integer states are not
6586 // explicitly represented.
6588 SmallVector<SDValue, 2> Ops;
6589 Ops.push_back(StoreChain);
6590 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6591 Ops.push_back(FIdx);
6593 SmallVector<EVT, 2> ValueVTs;
6594 ValueVTs.push_back(MVT::v4f64);
6595 ValueVTs.push_back(MVT::Other); // chain
6596 SDVTList VTs = DAG.getVTList(ValueVTs);
6598 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6599 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6600 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6601 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6604 SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6605 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6606 FPZeros, FPZeros, FPZeros, FPZeros);
6608 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6611 // All other QPX vectors are handled by generic code.
6612 if (Subtarget.hasQPX())
6615 // Check if this is a splat of a constant value.
6616 APInt APSplatBits, APSplatUndef;
6617 unsigned SplatBitSize;
6619 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6620 HasAnyUndefs, 0, true) || SplatBitSize > 32)
6623 unsigned SplatBits = APSplatBits.getZExtValue();
6624 unsigned SplatUndef = APSplatUndef.getZExtValue();
6625 unsigned SplatSize = SplatBitSize / 8;
6627 // First, handle single instruction cases.
6630 if (SplatBits == 0) {
6631 // Canonicalize all zero vectors to be v4i32.
6632 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6633 SDValue Z = DAG.getConstant(0, MVT::i32);
6634 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6635 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6640 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6641 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6643 if (SextVal >= -16 && SextVal <= 15)
6644 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6647 // Two instruction sequences.
6649 // If this value is in the range [-32,30] and is even, use:
6650 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6651 // If this value is in the range [17,31] and is odd, use:
6652 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6653 // If this value is in the range [-31,-17] and is odd, use:
6654 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6655 // Note the last two are three-instruction sequences.
6656 if (SextVal >= -32 && SextVal <= 31) {
6657 // To avoid having these optimizations undone by constant folding,
6658 // we convert to a pseudo that will be expanded later into one of
6660 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6661 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6662 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6663 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6664 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6665 if (VT == Op.getValueType())
6668 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6671 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6672 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6674 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6675 // Make -1 and vspltisw -1:
6676 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6678 // Make the VSLW intrinsic, computing 0x8000_0000.
6679 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6682 // xor by OnesV to invert it.
6683 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6684 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6687 // The remaining cases assume either big endian element order or
6688 // a splat-size that equates to the element size of the vector
6689 // to be built. An example that doesn't work for little endian is
6690 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6691 // and a vector element size of 16 bits. The code below will
6692 // produce the vector in big endian element order, which for little
6693 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6695 // For now, just avoid these optimizations in that case.
6696 // FIXME: Develop correct optimizations for LE with mismatched
6697 // splat and element sizes.
6699 if (Subtarget.isLittleEndian() &&
6700 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6703 // Check to see if this is a wide variety of vsplti*, binop self cases.
6704 static const signed char SplatCsts[] = {
6705 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6706 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6709 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6710 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6711 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6712 int i = SplatCsts[idx];
6714 // Figure out what shift amount will be used by altivec if shifted by i in
6716 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6718 // vsplti + shl self.
6719 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6720 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6721 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6722 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6723 Intrinsic::ppc_altivec_vslw
6725 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6726 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6729 // vsplti + srl self.
6730 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6731 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6732 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6733 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6734 Intrinsic::ppc_altivec_vsrw
6736 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6737 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6740 // vsplti + sra self.
6741 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6742 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6743 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6744 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6745 Intrinsic::ppc_altivec_vsraw
6747 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6748 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6751 // vsplti + rol self.
6752 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6753 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6754 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6755 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6756 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6757 Intrinsic::ppc_altivec_vrlw
6759 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6760 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6763 // t = vsplti c, result = vsldoi t, t, 1
6764 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6765 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6766 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6768 // t = vsplti c, result = vsldoi t, t, 2
6769 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6770 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6771 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6773 // t = vsplti c, result = vsldoi t, t, 3
6774 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6775 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6776 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6783 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6784 /// the specified operations to build the shuffle.
6785 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6786 SDValue RHS, SelectionDAG &DAG,
6788 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6789 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6790 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6793 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6805 if (OpNum == OP_COPY) {
6806 if (LHSID == (1*9+2)*9+3) return LHS;
6807 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6811 SDValue OpLHS, OpRHS;
6812 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6813 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6817 default: llvm_unreachable("Unknown i32 permute!");
6819 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6820 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6821 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6822 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6825 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6826 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6827 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6828 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6831 for (unsigned i = 0; i != 16; ++i)
6832 ShufIdxs[i] = (i&3)+0;
6835 for (unsigned i = 0; i != 16; ++i)
6836 ShufIdxs[i] = (i&3)+4;
6839 for (unsigned i = 0; i != 16; ++i)
6840 ShufIdxs[i] = (i&3)+8;
6843 for (unsigned i = 0; i != 16; ++i)
6844 ShufIdxs[i] = (i&3)+12;
6847 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6849 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6851 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6853 EVT VT = OpLHS.getValueType();
6854 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6855 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6856 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6857 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6860 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6861 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6862 /// return the code it can be lowered into. Worst case, it can always be
6863 /// lowered into a vperm.
6864 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6865 SelectionDAG &DAG) const {
6867 SDValue V1 = Op.getOperand(0);
6868 SDValue V2 = Op.getOperand(1);
6869 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6870 EVT VT = Op.getValueType();
6871 bool isLittleEndian = Subtarget.isLittleEndian();
6873 if (Subtarget.hasQPX()) {
6874 if (VT.getVectorNumElements() != 4)
6877 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6879 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6880 if (AlignIdx != -1) {
6881 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6882 DAG.getConstant(AlignIdx, MVT::i32));
6883 } else if (SVOp->isSplat()) {
6884 int SplatIdx = SVOp->getSplatIndex();
6885 if (SplatIdx >= 4) {
6890 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6893 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6894 DAG.getConstant(SplatIdx, MVT::i32));
6897 // Lower this into a qvgpci/qvfperm pair.
6899 // Compute the qvgpci literal
6901 for (unsigned i = 0; i < 4; ++i) {
6902 int m = SVOp->getMaskElt(i);
6903 unsigned mm = m >= 0 ? (unsigned) m : i;
6904 idx |= mm << (3-i)*3;
6907 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6908 DAG.getConstant(idx, MVT::i32));
6909 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6912 // Cases that are handled by instructions that take permute immediates
6913 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6914 // selected by the instruction selector.
6915 if (V2.getOpcode() == ISD::UNDEF) {
6916 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6917 PPC::isSplatShuffleMask(SVOp, 2) ||
6918 PPC::isSplatShuffleMask(SVOp, 4) ||
6919 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6920 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6921 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6922 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6923 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6924 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6925 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6926 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6927 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6932 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6933 // and produce a fixed permutation. If any of these match, do not lower to
6935 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6936 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6937 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6938 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6939 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6940 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6941 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6942 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6943 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6944 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6947 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6948 // perfect shuffle table to emit an optimal matching sequence.
6949 ArrayRef<int> PermMask = SVOp->getMask();
6951 unsigned PFIndexes[4];
6952 bool isFourElementShuffle = true;
6953 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6954 unsigned EltNo = 8; // Start out undef.
6955 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6956 if (PermMask[i*4+j] < 0)
6957 continue; // Undef, ignore it.
6959 unsigned ByteSource = PermMask[i*4+j];
6960 if ((ByteSource & 3) != j) {
6961 isFourElementShuffle = false;
6966 EltNo = ByteSource/4;
6967 } else if (EltNo != ByteSource/4) {
6968 isFourElementShuffle = false;
6972 PFIndexes[i] = EltNo;
6975 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6976 // perfect shuffle vector to determine if it is cost effective to do this as
6977 // discrete instructions, or whether we should use a vperm.
6978 // For now, we skip this for little endian until such time as we have a
6979 // little-endian perfect shuffle table.
6980 if (isFourElementShuffle && !isLittleEndian) {
6981 // Compute the index in the perfect shuffle table.
6982 unsigned PFTableIndex =
6983 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6985 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6986 unsigned Cost = (PFEntry >> 30);
6988 // Determining when to avoid vperm is tricky. Many things affect the cost
6989 // of vperm, particularly how many times the perm mask needs to be computed.
6990 // For example, if the perm mask can be hoisted out of a loop or is already
6991 // used (perhaps because there are multiple permutes with the same shuffle
6992 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6993 // the loop requires an extra register.
6995 // As a compromise, we only emit discrete instructions if the shuffle can be
6996 // generated in 3 or fewer operations. When we have loop information
6997 // available, if this block is within a loop, we should avoid using vperm
6998 // for 3-operation perms and use a constant pool load instead.
7000 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7003 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7004 // vector that will get spilled to the constant pool.
7005 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7007 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7008 // that it is in input element units, not in bytes. Convert now.
7010 // For little endian, the order of the input vectors is reversed, and
7011 // the permutation mask is complemented with respect to 31. This is
7012 // necessary to produce proper semantics with the big-endian-biased vperm
7014 EVT EltVT = V1.getValueType().getVectorElementType();
7015 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7017 SmallVector<SDValue, 16> ResultMask;
7018 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7019 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7021 for (unsigned j = 0; j != BytesPerElement; ++j)
7023 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7026 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7030 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7033 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7036 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7040 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7041 /// altivec comparison. If it is, return true and fill in Opc/isDot with
7042 /// information about the intrinsic.
7043 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7045 unsigned IntrinsicID =
7046 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7049 switch (IntrinsicID) {
7050 default: return false;
7051 // Comparison predicates.
7052 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7053 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7054 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7055 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7056 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7057 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7058 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7059 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7060 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7061 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7062 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7063 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7064 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7066 // Normal Comparisons.
7067 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7068 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7069 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7070 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7071 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7072 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7073 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7074 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7075 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7076 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7077 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7078 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7079 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7084 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7085 /// lower, do it, otherwise return null.
7086 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7087 SelectionDAG &DAG) const {
7088 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7089 // opcode number of the comparison.
7093 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
7094 return SDValue(); // Don't custom lower most intrinsics.
7096 // If this is a non-dot comparison, make the VCMP node and we are done.
7098 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7099 Op.getOperand(1), Op.getOperand(2),
7100 DAG.getConstant(CompareOpc, MVT::i32));
7101 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7104 // Create the PPCISD altivec 'dot' comparison node.
7106 Op.getOperand(2), // LHS
7107 Op.getOperand(3), // RHS
7108 DAG.getConstant(CompareOpc, MVT::i32)
7110 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7111 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7113 // Now that we have the comparison, emit a copy from the CR to a GPR.
7114 // This is flagged to the above dot comparison.
7115 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7116 DAG.getRegister(PPC::CR6, MVT::i32),
7117 CompNode.getValue(1));
7119 // Unpack the result based on how the target uses it.
7120 unsigned BitNo; // Bit # of CR6.
7121 bool InvertBit; // Invert result?
7122 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7123 default: // Can't happen, don't crash on invalid number though.
7124 case 0: // Return the value of the EQ bit of CR6.
7125 BitNo = 0; InvertBit = false;
7127 case 1: // Return the inverted value of the EQ bit of CR6.
7128 BitNo = 0; InvertBit = true;
7130 case 2: // Return the value of the LT bit of CR6.
7131 BitNo = 2; InvertBit = false;
7133 case 3: // Return the inverted value of the LT bit of CR6.
7134 BitNo = 2; InvertBit = true;
7138 // Shift the bit into the low position.
7139 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7140 DAG.getConstant(8-(3-BitNo), MVT::i32));
7142 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7143 DAG.getConstant(1, MVT::i32));
7145 // If we are supposed to, toggle the bit.
7147 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7148 DAG.getConstant(1, MVT::i32));
7152 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7153 SelectionDAG &DAG) const {
7155 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7156 // instructions), but for smaller types, we need to first extend up to v2i32
7157 // before doing going farther.
7158 if (Op.getValueType() == MVT::v2i64) {
7159 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7160 if (ExtVT != MVT::v2i32) {
7161 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7162 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7163 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7164 ExtVT.getVectorElementType(), 4)));
7165 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7166 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7167 DAG.getValueType(MVT::v2i32));
7176 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7177 SelectionDAG &DAG) const {
7179 // Create a stack slot that is 16-byte aligned.
7180 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7181 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7182 EVT PtrVT = getPointerTy();
7183 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7185 // Store the input value into Value#0 of the stack slot.
7186 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7187 Op.getOperand(0), FIdx, MachinePointerInfo(),
7190 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7191 false, false, false, 0);
7194 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7195 SelectionDAG &DAG) const {
7197 SDNode *N = Op.getNode();
7199 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7200 "Unknown extract_vector_elt type");
7202 SDValue Value = N->getOperand(0);
7204 // The first part of this is like the store lowering except that we don't
7205 // need to track the chain.
7207 // The values are now known to be -1 (false) or 1 (true). To convert this
7208 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7209 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7210 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7212 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7213 // understand how to form the extending load.
7214 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7215 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7216 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7218 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7220 // Now convert to an integer and store.
7221 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7222 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7225 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7226 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7227 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7228 EVT PtrVT = getPointerTy();
7229 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7231 SDValue StoreChain = DAG.getEntryNode();
7232 SmallVector<SDValue, 2> Ops;
7233 Ops.push_back(StoreChain);
7234 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7235 Ops.push_back(Value);
7236 Ops.push_back(FIdx);
7238 SmallVector<EVT, 2> ValueVTs;
7239 ValueVTs.push_back(MVT::Other); // chain
7240 SDVTList VTs = DAG.getVTList(ValueVTs);
7242 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7243 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7245 // Extract the value requested.
7246 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7247 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7248 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7250 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7251 PtrInfo.getWithOffset(Offset),
7252 false, false, false, 0);
7254 if (!Subtarget.useCRBits())
7257 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7260 /// Lowering for QPX v4i1 loads
7261 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7262 SelectionDAG &DAG) const {
7264 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7265 SDValue LoadChain = LN->getChain();
7266 SDValue BasePtr = LN->getBasePtr();
7268 if (Op.getValueType() == MVT::v4f64 ||
7269 Op.getValueType() == MVT::v4f32) {
7270 EVT MemVT = LN->getMemoryVT();
7271 unsigned Alignment = LN->getAlignment();
7273 // If this load is properly aligned, then it is legal.
7274 if (Alignment >= MemVT.getStoreSize())
7277 EVT ScalarVT = Op.getValueType().getScalarType(),
7278 ScalarMemVT = MemVT.getScalarType();
7279 unsigned Stride = ScalarMemVT.getStoreSize();
7281 SmallVector<SDValue, 8> Vals, LoadChains;
7282 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7284 if (ScalarVT != ScalarMemVT)
7286 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7288 LN->getPointerInfo().getWithOffset(Idx*Stride),
7289 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7290 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7294 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7295 LN->getPointerInfo().getWithOffset(Idx*Stride),
7296 LN->isVolatile(), LN->isNonTemporal(),
7297 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7300 if (Idx == 0 && LN->isIndexed()) {
7301 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7302 "Unknown addressing mode on vector load");
7303 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7304 LN->getAddressingMode());
7307 Vals.push_back(Load);
7308 LoadChains.push_back(Load.getValue(1));
7310 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7311 DAG.getConstant(Stride, BasePtr.getValueType()));
7314 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7315 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7316 Op.getValueType(), Vals);
7318 if (LN->isIndexed()) {
7319 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7320 return DAG.getMergeValues(RetOps, dl);
7323 SDValue RetOps[] = { Value, TF };
7324 return DAG.getMergeValues(RetOps, dl);
7327 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7328 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7330 // To lower v4i1 from a byte array, we load the byte elements of the
7331 // vector and then reuse the BUILD_VECTOR logic.
7333 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7334 for (unsigned i = 0; i < 4; ++i) {
7335 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7336 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7338 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7339 dl, MVT::i32, LoadChain, Idx,
7340 LN->getPointerInfo().getWithOffset(i),
7341 MVT::i8 /* memory type */,
7342 LN->isVolatile(), LN->isNonTemporal(),
7344 1 /* alignment */, LN->getAAInfo()));
7345 VectElmtChains.push_back(VectElmts[i].getValue(1));
7348 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7349 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7351 SDValue RVals[] = { Value, LoadChain };
7352 return DAG.getMergeValues(RVals, dl);
7355 /// Lowering for QPX v4i1 stores
7356 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7357 SelectionDAG &DAG) const {
7359 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7360 SDValue StoreChain = SN->getChain();
7361 SDValue BasePtr = SN->getBasePtr();
7362 SDValue Value = SN->getValue();
7364 if (Value.getValueType() == MVT::v4f64 ||
7365 Value.getValueType() == MVT::v4f32) {
7366 EVT MemVT = SN->getMemoryVT();
7367 unsigned Alignment = SN->getAlignment();
7369 // If this store is properly aligned, then it is legal.
7370 if (Alignment >= MemVT.getStoreSize())
7373 EVT ScalarVT = Value.getValueType().getScalarType(),
7374 ScalarMemVT = MemVT.getScalarType();
7375 unsigned Stride = ScalarMemVT.getStoreSize();
7377 SmallVector<SDValue, 8> Stores;
7378 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7380 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7381 DAG.getConstant(Idx, getVectorIdxTy()));
7383 if (ScalarVT != ScalarMemVT)
7385 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7386 SN->getPointerInfo().getWithOffset(Idx*Stride),
7387 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7388 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7391 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7392 SN->getPointerInfo().getWithOffset(Idx*Stride),
7393 SN->isVolatile(), SN->isNonTemporal(),
7394 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7396 if (Idx == 0 && SN->isIndexed()) {
7397 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7398 "Unknown addressing mode on vector store");
7399 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7400 SN->getAddressingMode());
7403 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7404 DAG.getConstant(Stride, BasePtr.getValueType()));
7405 Stores.push_back(Store);
7408 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7410 if (SN->isIndexed()) {
7411 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7412 return DAG.getMergeValues(RetOps, dl);
7418 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7419 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7421 // The values are now known to be -1 (false) or 1 (true). To convert this
7422 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7423 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7424 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7426 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7427 // understand how to form the extending load.
7428 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7429 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7430 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7432 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7434 // Now convert to an integer and store.
7435 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7436 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7439 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7440 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7441 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7442 EVT PtrVT = getPointerTy();
7443 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7445 SmallVector<SDValue, 2> Ops;
7446 Ops.push_back(StoreChain);
7447 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7448 Ops.push_back(Value);
7449 Ops.push_back(FIdx);
7451 SmallVector<EVT, 2> ValueVTs;
7452 ValueVTs.push_back(MVT::Other); // chain
7453 SDVTList VTs = DAG.getVTList(ValueVTs);
7455 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7456 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7458 // Move data into the byte array.
7459 SmallVector<SDValue, 4> Loads, LoadChains;
7460 for (unsigned i = 0; i < 4; ++i) {
7461 unsigned Offset = 4*i;
7462 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7463 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7465 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7466 PtrInfo.getWithOffset(Offset),
7467 false, false, false, 0));
7468 LoadChains.push_back(Loads[i].getValue(1));
7471 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7473 SmallVector<SDValue, 4> Stores;
7474 for (unsigned i = 0; i < 4; ++i) {
7475 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7476 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7478 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7479 SN->getPointerInfo().getWithOffset(i),
7480 MVT::i8 /* memory type */,
7481 SN->isNonTemporal(), SN->isVolatile(),
7482 1 /* alignment */, SN->getAAInfo()));
7485 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7490 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7492 if (Op.getValueType() == MVT::v4i32) {
7493 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7495 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7496 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7498 SDValue RHSSwap = // = vrlw RHS, 16
7499 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7501 // Shrinkify inputs to v8i16.
7502 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7503 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7504 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7506 // Low parts multiplied together, generating 32-bit results (we ignore the
7508 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7509 LHS, RHS, DAG, dl, MVT::v4i32);
7511 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7512 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7513 // Shift the high parts up 16 bits.
7514 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7516 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7517 } else if (Op.getValueType() == MVT::v8i16) {
7518 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7520 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7522 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7523 LHS, RHS, Zero, DAG, dl);
7524 } else if (Op.getValueType() == MVT::v16i8) {
7525 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7526 bool isLittleEndian = Subtarget.isLittleEndian();
7528 // Multiply the even 8-bit parts, producing 16-bit sums.
7529 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7530 LHS, RHS, DAG, dl, MVT::v8i16);
7531 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7533 // Multiply the odd 8-bit parts, producing 16-bit sums.
7534 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7535 LHS, RHS, DAG, dl, MVT::v8i16);
7536 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7538 // Merge the results together. Because vmuleub and vmuloub are
7539 // instructions with a big-endian bias, we must reverse the
7540 // element numbering and reverse the meaning of "odd" and "even"
7541 // when generating little endian code.
7543 for (unsigned i = 0; i != 8; ++i) {
7544 if (isLittleEndian) {
7546 Ops[i*2+1] = 2*i+16;
7549 Ops[i*2+1] = 2*i+1+16;
7553 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7555 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7557 llvm_unreachable("Unknown mul to lower!");
7561 /// LowerOperation - Provide custom lowering hooks for some operations.
7563 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7564 switch (Op.getOpcode()) {
7565 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7566 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7567 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7568 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7569 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7570 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7571 case ISD::SETCC: return LowerSETCC(Op, DAG);
7572 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7573 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7575 return LowerVASTART(Op, DAG, Subtarget);
7578 return LowerVAARG(Op, DAG, Subtarget);
7581 return LowerVACOPY(Op, DAG, Subtarget);
7583 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7584 case ISD::DYNAMIC_STACKALLOC:
7585 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7587 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7588 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7590 case ISD::LOAD: return LowerLOAD(Op, DAG);
7591 case ISD::STORE: return LowerSTORE(Op, DAG);
7592 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7593 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7594 case ISD::FP_TO_UINT:
7595 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7597 case ISD::UINT_TO_FP:
7598 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7599 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7601 // Lower 64-bit shifts.
7602 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7603 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7604 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7606 // Vector-related lowering.
7607 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7608 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7609 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7610 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7611 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7612 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7613 case ISD::MUL: return LowerMUL(Op, DAG);
7615 // For counter-based loop handling.
7616 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7618 // Frame & Return address.
7619 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7620 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7624 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7625 SmallVectorImpl<SDValue>&Results,
7626 SelectionDAG &DAG) const {
7628 switch (N->getOpcode()) {
7630 llvm_unreachable("Do not know how to custom type legalize this operation!");
7631 case ISD::READCYCLECOUNTER: {
7632 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7633 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7635 Results.push_back(RTB);
7636 Results.push_back(RTB.getValue(1));
7637 Results.push_back(RTB.getValue(2));
7640 case ISD::INTRINSIC_W_CHAIN: {
7641 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7642 Intrinsic::ppc_is_decremented_ctr_nonzero)
7645 assert(N->getValueType(0) == MVT::i1 &&
7646 "Unexpected result type for CTR decrement intrinsic");
7647 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7648 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7649 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7652 Results.push_back(NewInt);
7653 Results.push_back(NewInt.getValue(1));
7657 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7660 EVT VT = N->getValueType(0);
7662 if (VT == MVT::i64) {
7663 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7665 Results.push_back(NewNode);
7666 Results.push_back(NewNode.getValue(1));
7670 case ISD::FP_ROUND_INREG: {
7671 assert(N->getValueType(0) == MVT::ppcf128);
7672 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7673 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7674 MVT::f64, N->getOperand(0),
7675 DAG.getIntPtrConstant(0));
7676 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7677 MVT::f64, N->getOperand(0),
7678 DAG.getIntPtrConstant(1));
7680 // Add the two halves of the long double in round-to-zero mode.
7681 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7683 // We know the low half is about to be thrown away, so just use something
7685 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7689 case ISD::FP_TO_SINT:
7690 // LowerFP_TO_INT() can only handle f32 and f64.
7691 if (N->getOperand(0).getValueType() == MVT::ppcf128)
7693 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7699 //===----------------------------------------------------------------------===//
7700 // Other Lowering Code
7701 //===----------------------------------------------------------------------===//
7703 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7704 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7705 Function *Func = Intrinsic::getDeclaration(M, Id);
7706 return Builder.CreateCall(Func);
7709 // The mappings for emitLeading/TrailingFence is taken from
7710 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7711 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7712 AtomicOrdering Ord, bool IsStore,
7713 bool IsLoad) const {
7714 if (Ord == SequentiallyConsistent)
7715 return callIntrinsic(Builder, Intrinsic::ppc_sync);
7716 else if (isAtLeastRelease(Ord))
7717 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7722 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7723 AtomicOrdering Ord, bool IsStore,
7724 bool IsLoad) const {
7725 if (IsLoad && isAtLeastAcquire(Ord))
7726 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7727 // FIXME: this is too conservative, a dependent branch + isync is enough.
7728 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7729 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7730 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7736 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7737 bool is64bit, unsigned BinOpcode) const {
7738 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7739 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7741 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7742 MachineFunction *F = BB->getParent();
7743 MachineFunction::iterator It = BB;
7746 unsigned dest = MI->getOperand(0).getReg();
7747 unsigned ptrA = MI->getOperand(1).getReg();
7748 unsigned ptrB = MI->getOperand(2).getReg();
7749 unsigned incr = MI->getOperand(3).getReg();
7750 DebugLoc dl = MI->getDebugLoc();
7752 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7753 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7754 F->insert(It, loopMBB);
7755 F->insert(It, exitMBB);
7756 exitMBB->splice(exitMBB->begin(), BB,
7757 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7758 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7760 MachineRegisterInfo &RegInfo = F->getRegInfo();
7761 unsigned TmpReg = (!BinOpcode) ? incr :
7762 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
7763 : &PPC::GPRCRegClass);
7767 // fallthrough --> loopMBB
7768 BB->addSuccessor(loopMBB);
7771 // l[wd]arx dest, ptr
7772 // add r0, dest, incr
7773 // st[wd]cx. r0, ptr
7775 // fallthrough --> exitMBB
7777 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7778 .addReg(ptrA).addReg(ptrB);
7780 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7781 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7782 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7783 BuildMI(BB, dl, TII->get(PPC::BCC))
7784 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7785 BB->addSuccessor(loopMBB);
7786 BB->addSuccessor(exitMBB);
7795 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7796 MachineBasicBlock *BB,
7797 bool is8bit, // operation
7798 unsigned BinOpcode) const {
7799 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7800 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7801 // In 64 bit mode we have to use 64 bits for addresses, even though the
7802 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7803 // registers without caring whether they're 32 or 64, but here we're
7804 // doing actual arithmetic on the addresses.
7805 bool is64bit = Subtarget.isPPC64();
7806 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7808 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7809 MachineFunction *F = BB->getParent();
7810 MachineFunction::iterator It = BB;
7813 unsigned dest = MI->getOperand(0).getReg();
7814 unsigned ptrA = MI->getOperand(1).getReg();
7815 unsigned ptrB = MI->getOperand(2).getReg();
7816 unsigned incr = MI->getOperand(3).getReg();
7817 DebugLoc dl = MI->getDebugLoc();
7819 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7820 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7821 F->insert(It, loopMBB);
7822 F->insert(It, exitMBB);
7823 exitMBB->splice(exitMBB->begin(), BB,
7824 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7825 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7827 MachineRegisterInfo &RegInfo = F->getRegInfo();
7828 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7829 : &PPC::GPRCRegClass;
7830 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7831 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7832 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7833 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7834 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7835 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7836 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7837 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7838 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7839 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7840 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7842 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7846 // fallthrough --> loopMBB
7847 BB->addSuccessor(loopMBB);
7849 // The 4-byte load must be aligned, while a char or short may be
7850 // anywhere in the word. Hence all this nasty bookkeeping code.
7851 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7852 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7853 // xori shift, shift1, 24 [16]
7854 // rlwinm ptr, ptr1, 0, 0, 29
7855 // slw incr2, incr, shift
7856 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7857 // slw mask, mask2, shift
7859 // lwarx tmpDest, ptr
7860 // add tmp, tmpDest, incr2
7861 // andc tmp2, tmpDest, mask
7862 // and tmp3, tmp, mask
7863 // or tmp4, tmp3, tmp2
7866 // fallthrough --> exitMBB
7867 // srw dest, tmpDest, shift
7868 if (ptrA != ZeroReg) {
7869 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7870 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7871 .addReg(ptrA).addReg(ptrB);
7875 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7876 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7877 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7878 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7880 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7881 .addReg(Ptr1Reg).addImm(0).addImm(61);
7883 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7884 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7885 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7886 .addReg(incr).addReg(ShiftReg);
7888 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7890 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7891 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7893 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7894 .addReg(Mask2Reg).addReg(ShiftReg);
7897 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7898 .addReg(ZeroReg).addReg(PtrReg);
7900 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7901 .addReg(Incr2Reg).addReg(TmpDestReg);
7902 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7903 .addReg(TmpDestReg).addReg(MaskReg);
7904 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7905 .addReg(TmpReg).addReg(MaskReg);
7906 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7907 .addReg(Tmp3Reg).addReg(Tmp2Reg);
7908 BuildMI(BB, dl, TII->get(PPC::STWCX))
7909 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7910 BuildMI(BB, dl, TII->get(PPC::BCC))
7911 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7912 BB->addSuccessor(loopMBB);
7913 BB->addSuccessor(exitMBB);
7918 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7923 llvm::MachineBasicBlock*
7924 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7925 MachineBasicBlock *MBB) const {
7926 DebugLoc DL = MI->getDebugLoc();
7927 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7929 MachineFunction *MF = MBB->getParent();
7930 MachineRegisterInfo &MRI = MF->getRegInfo();
7932 const BasicBlock *BB = MBB->getBasicBlock();
7933 MachineFunction::iterator I = MBB;
7937 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7938 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7940 unsigned DstReg = MI->getOperand(0).getReg();
7941 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7942 assert(RC->hasType(MVT::i32) && "Invalid destination!");
7943 unsigned mainDstReg = MRI.createVirtualRegister(RC);
7944 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7946 MVT PVT = getPointerTy();
7947 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7948 "Invalid Pointer Size!");
7949 // For v = setjmp(buf), we generate
7952 // SjLjSetup mainMBB
7958 // buf[LabelOffset] = LR
7962 // v = phi(main, restore)
7965 MachineBasicBlock *thisMBB = MBB;
7966 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7967 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7968 MF->insert(I, mainMBB);
7969 MF->insert(I, sinkMBB);
7971 MachineInstrBuilder MIB;
7973 // Transfer the remainder of BB and its successor edges to sinkMBB.
7974 sinkMBB->splice(sinkMBB->begin(), MBB,
7975 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7976 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7978 // Note that the structure of the jmp_buf used here is not compatible
7979 // with that used by libc, and is not designed to be. Specifically, it
7980 // stores only those 'reserved' registers that LLVM does not otherwise
7981 // understand how to spill. Also, by convention, by the time this
7982 // intrinsic is called, Clang has already stored the frame address in the
7983 // first slot of the buffer and stack address in the third. Following the
7984 // X86 target code, we'll store the jump address in the second slot. We also
7985 // need to save the TOC pointer (R2) to handle jumps between shared
7986 // libraries, and that will be stored in the fourth slot. The thread
7987 // identifier (R13) is not affected.
7990 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7991 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7992 const int64_t BPOffset = 4 * PVT.getStoreSize();
7994 // Prepare IP either in reg.
7995 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7996 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7997 unsigned BufReg = MI->getOperand(1).getReg();
7999 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8000 setUsesTOCBasePtr(*MBB->getParent());
8001 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8005 MIB.setMemRefs(MMOBegin, MMOEnd);
8008 // Naked functions never have a base pointer, and so we use r1. For all
8009 // other functions, this decision must be delayed until during PEI.
8011 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8012 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8014 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8016 MIB = BuildMI(*thisMBB, MI, DL,
8017 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8021 MIB.setMemRefs(MMOBegin, MMOEnd);
8024 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8025 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8026 MIB.addRegMask(TRI->getNoPreservedMask());
8028 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8030 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8032 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8034 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8035 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8040 BuildMI(mainMBB, DL,
8041 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8044 if (Subtarget.isPPC64()) {
8045 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8047 .addImm(LabelOffset)
8050 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8052 .addImm(LabelOffset)
8056 MIB.setMemRefs(MMOBegin, MMOEnd);
8058 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8059 mainMBB->addSuccessor(sinkMBB);
8062 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8063 TII->get(PPC::PHI), DstReg)
8064 .addReg(mainDstReg).addMBB(mainMBB)
8065 .addReg(restoreDstReg).addMBB(thisMBB);
8067 MI->eraseFromParent();
8072 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8073 MachineBasicBlock *MBB) const {
8074 DebugLoc DL = MI->getDebugLoc();
8075 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8077 MachineFunction *MF = MBB->getParent();
8078 MachineRegisterInfo &MRI = MF->getRegInfo();
8081 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8082 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8084 MVT PVT = getPointerTy();
8085 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8086 "Invalid Pointer Size!");
8088 const TargetRegisterClass *RC =
8089 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8090 unsigned Tmp = MRI.createVirtualRegister(RC);
8091 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8092 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8093 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8097 : (Subtarget.isSVR4ABI() &&
8098 MF->getTarget().getRelocationModel() == Reloc::PIC_
8102 MachineInstrBuilder MIB;
8104 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8105 const int64_t SPOffset = 2 * PVT.getStoreSize();
8106 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8107 const int64_t BPOffset = 4 * PVT.getStoreSize();
8109 unsigned BufReg = MI->getOperand(0).getReg();
8111 // Reload FP (the jumped-to function may not have had a
8112 // frame pointer, and if so, then its r31 will be restored
8114 if (PVT == MVT::i64) {
8115 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8119 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8123 MIB.setMemRefs(MMOBegin, MMOEnd);
8126 if (PVT == MVT::i64) {
8127 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8128 .addImm(LabelOffset)
8131 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8132 .addImm(LabelOffset)
8135 MIB.setMemRefs(MMOBegin, MMOEnd);
8138 if (PVT == MVT::i64) {
8139 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8143 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8147 MIB.setMemRefs(MMOBegin, MMOEnd);
8150 if (PVT == MVT::i64) {
8151 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8155 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8159 MIB.setMemRefs(MMOBegin, MMOEnd);
8162 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8163 setUsesTOCBasePtr(*MBB->getParent());
8164 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8168 MIB.setMemRefs(MMOBegin, MMOEnd);
8172 BuildMI(*MBB, MI, DL,
8173 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8174 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8176 MI->eraseFromParent();
8181 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8182 MachineBasicBlock *BB) const {
8183 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8184 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8185 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8186 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8187 // Call lowering should have added an r2 operand to indicate a dependence
8188 // on the TOC base pointer value. It can't however, because there is no
8189 // way to mark the dependence as implicit there, and so the stackmap code
8190 // will confuse it with a regular operand. Instead, add the dependence
8192 setUsesTOCBasePtr(*BB->getParent());
8193 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8196 return emitPatchPoint(MI, BB);
8199 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8200 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8201 return emitEHSjLjSetJmp(MI, BB);
8202 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8203 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8204 return emitEHSjLjLongJmp(MI, BB);
8207 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8209 // To "insert" these instructions we actually have to insert their
8210 // control-flow patterns.
8211 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8212 MachineFunction::iterator It = BB;
8215 MachineFunction *F = BB->getParent();
8217 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8218 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8219 MI->getOpcode() == PPC::SELECT_I4 ||
8220 MI->getOpcode() == PPC::SELECT_I8)) {
8221 SmallVector<MachineOperand, 2> Cond;
8222 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8223 MI->getOpcode() == PPC::SELECT_CC_I8)
8224 Cond.push_back(MI->getOperand(4));
8226 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8227 Cond.push_back(MI->getOperand(1));
8229 DebugLoc dl = MI->getDebugLoc();
8230 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8231 Cond, MI->getOperand(2).getReg(),
8232 MI->getOperand(3).getReg());
8233 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8234 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8235 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8236 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8237 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8238 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8239 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8240 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8241 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8242 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8243 MI->getOpcode() == PPC::SELECT_I4 ||
8244 MI->getOpcode() == PPC::SELECT_I8 ||
8245 MI->getOpcode() == PPC::SELECT_F4 ||
8246 MI->getOpcode() == PPC::SELECT_F8 ||
8247 MI->getOpcode() == PPC::SELECT_QFRC ||
8248 MI->getOpcode() == PPC::SELECT_QSRC ||
8249 MI->getOpcode() == PPC::SELECT_QBRC ||
8250 MI->getOpcode() == PPC::SELECT_VRRC ||
8251 MI->getOpcode() == PPC::SELECT_VSFRC ||
8252 MI->getOpcode() == PPC::SELECT_VSRC) {
8253 // The incoming instruction knows the destination vreg to set, the
8254 // condition code register to branch on, the true/false values to
8255 // select between, and a branch opcode to use.
8260 // cmpTY ccX, r1, r2
8262 // fallthrough --> copy0MBB
8263 MachineBasicBlock *thisMBB = BB;
8264 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8265 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8266 DebugLoc dl = MI->getDebugLoc();
8267 F->insert(It, copy0MBB);
8268 F->insert(It, sinkMBB);
8270 // Transfer the remainder of BB and its successor edges to sinkMBB.
8271 sinkMBB->splice(sinkMBB->begin(), BB,
8272 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8273 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8275 // Next, add the true and fallthrough blocks as its successors.
8276 BB->addSuccessor(copy0MBB);
8277 BB->addSuccessor(sinkMBB);
8279 if (MI->getOpcode() == PPC::SELECT_I4 ||
8280 MI->getOpcode() == PPC::SELECT_I8 ||
8281 MI->getOpcode() == PPC::SELECT_F4 ||
8282 MI->getOpcode() == PPC::SELECT_F8 ||
8283 MI->getOpcode() == PPC::SELECT_QFRC ||
8284 MI->getOpcode() == PPC::SELECT_QSRC ||
8285 MI->getOpcode() == PPC::SELECT_QBRC ||
8286 MI->getOpcode() == PPC::SELECT_VRRC ||
8287 MI->getOpcode() == PPC::SELECT_VSFRC ||
8288 MI->getOpcode() == PPC::SELECT_VSRC) {
8289 BuildMI(BB, dl, TII->get(PPC::BC))
8290 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8292 unsigned SelectPred = MI->getOperand(4).getImm();
8293 BuildMI(BB, dl, TII->get(PPC::BCC))
8294 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8298 // %FalseValue = ...
8299 // # fallthrough to sinkMBB
8302 // Update machine-CFG edges
8303 BB->addSuccessor(sinkMBB);
8306 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8309 BuildMI(*BB, BB->begin(), dl,
8310 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8311 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8312 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8313 } else if (MI->getOpcode() == PPC::ReadTB) {
8314 // To read the 64-bit time-base register on a 32-bit target, we read the
8315 // two halves. Should the counter have wrapped while it was being read, we
8316 // need to try again.
8319 // mfspr Rx,TBU # load from TBU
8320 // mfspr Ry,TB # load from TB
8321 // mfspr Rz,TBU # load from TBU
8322 // cmpw crX,Rx,Rz # check if ‘old’=’new’
8323 // bne readLoop # branch if they're not equal
8326 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8327 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8328 DebugLoc dl = MI->getDebugLoc();
8329 F->insert(It, readMBB);
8330 F->insert(It, sinkMBB);
8332 // Transfer the remainder of BB and its successor edges to sinkMBB.
8333 sinkMBB->splice(sinkMBB->begin(), BB,
8334 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8335 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8337 BB->addSuccessor(readMBB);
8340 MachineRegisterInfo &RegInfo = F->getRegInfo();
8341 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8342 unsigned LoReg = MI->getOperand(0).getReg();
8343 unsigned HiReg = MI->getOperand(1).getReg();
8345 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8346 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8347 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8349 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8351 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8352 .addReg(HiReg).addReg(ReadAgainReg);
8353 BuildMI(BB, dl, TII->get(PPC::BCC))
8354 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8356 BB->addSuccessor(readMBB);
8357 BB->addSuccessor(sinkMBB);
8359 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8360 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8361 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8362 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8363 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8364 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
8365 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8366 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
8368 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8369 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8370 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8371 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8372 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8373 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
8374 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8375 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
8377 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8378 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8379 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8380 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8381 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8382 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
8383 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8384 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
8386 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8387 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8388 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8389 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8390 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8391 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
8392 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8393 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
8395 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8396 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8397 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8398 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8399 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8400 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
8401 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8402 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
8404 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8405 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8406 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8407 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8408 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8409 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
8410 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8411 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
8413 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8414 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8415 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8416 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8417 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8418 BB = EmitAtomicBinary(MI, BB, false, 0);
8419 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8420 BB = EmitAtomicBinary(MI, BB, true, 0);
8422 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8423 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
8424 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8426 unsigned dest = MI->getOperand(0).getReg();
8427 unsigned ptrA = MI->getOperand(1).getReg();
8428 unsigned ptrB = MI->getOperand(2).getReg();
8429 unsigned oldval = MI->getOperand(3).getReg();
8430 unsigned newval = MI->getOperand(4).getReg();
8431 DebugLoc dl = MI->getDebugLoc();
8433 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8434 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8435 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8436 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8437 F->insert(It, loop1MBB);
8438 F->insert(It, loop2MBB);
8439 F->insert(It, midMBB);
8440 F->insert(It, exitMBB);
8441 exitMBB->splice(exitMBB->begin(), BB,
8442 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8443 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8447 // fallthrough --> loopMBB
8448 BB->addSuccessor(loop1MBB);
8451 // l[wd]arx dest, ptr
8452 // cmp[wd] dest, oldval
8455 // st[wd]cx. newval, ptr
8459 // st[wd]cx. dest, ptr
8462 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
8463 .addReg(ptrA).addReg(ptrB);
8464 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8465 .addReg(oldval).addReg(dest);
8466 BuildMI(BB, dl, TII->get(PPC::BCC))
8467 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8468 BB->addSuccessor(loop2MBB);
8469 BB->addSuccessor(midMBB);
8472 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8473 .addReg(newval).addReg(ptrA).addReg(ptrB);
8474 BuildMI(BB, dl, TII->get(PPC::BCC))
8475 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8476 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8477 BB->addSuccessor(loop1MBB);
8478 BB->addSuccessor(exitMBB);
8481 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8482 .addReg(dest).addReg(ptrA).addReg(ptrB);
8483 BB->addSuccessor(exitMBB);
8488 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8489 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8490 // We must use 64-bit registers for addresses when targeting 64-bit,
8491 // since we're actually doing arithmetic on them. Other registers
8493 bool is64bit = Subtarget.isPPC64();
8494 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8496 unsigned dest = MI->getOperand(0).getReg();
8497 unsigned ptrA = MI->getOperand(1).getReg();
8498 unsigned ptrB = MI->getOperand(2).getReg();
8499 unsigned oldval = MI->getOperand(3).getReg();
8500 unsigned newval = MI->getOperand(4).getReg();
8501 DebugLoc dl = MI->getDebugLoc();
8503 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8504 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8505 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8506 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8507 F->insert(It, loop1MBB);
8508 F->insert(It, loop2MBB);
8509 F->insert(It, midMBB);
8510 F->insert(It, exitMBB);
8511 exitMBB->splice(exitMBB->begin(), BB,
8512 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8513 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8515 MachineRegisterInfo &RegInfo = F->getRegInfo();
8516 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8517 : &PPC::GPRCRegClass;
8518 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8519 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8520 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8521 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8522 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8523 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8524 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8525 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8526 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8527 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8528 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8529 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8530 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8532 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8533 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8536 // fallthrough --> loopMBB
8537 BB->addSuccessor(loop1MBB);
8539 // The 4-byte load must be aligned, while a char or short may be
8540 // anywhere in the word. Hence all this nasty bookkeeping code.
8541 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8542 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8543 // xori shift, shift1, 24 [16]
8544 // rlwinm ptr, ptr1, 0, 0, 29
8545 // slw newval2, newval, shift
8546 // slw oldval2, oldval,shift
8547 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8548 // slw mask, mask2, shift
8549 // and newval3, newval2, mask
8550 // and oldval3, oldval2, mask
8552 // lwarx tmpDest, ptr
8553 // and tmp, tmpDest, mask
8554 // cmpw tmp, oldval3
8557 // andc tmp2, tmpDest, mask
8558 // or tmp4, tmp2, newval3
8563 // stwcx. tmpDest, ptr
8565 // srw dest, tmpDest, shift
8566 if (ptrA != ZeroReg) {
8567 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8568 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8569 .addReg(ptrA).addReg(ptrB);
8573 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8574 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8575 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8576 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8578 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8579 .addReg(Ptr1Reg).addImm(0).addImm(61);
8581 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8582 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8583 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8584 .addReg(newval).addReg(ShiftReg);
8585 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8586 .addReg(oldval).addReg(ShiftReg);
8588 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8590 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8591 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8592 .addReg(Mask3Reg).addImm(65535);
8594 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8595 .addReg(Mask2Reg).addReg(ShiftReg);
8596 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8597 .addReg(NewVal2Reg).addReg(MaskReg);
8598 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8599 .addReg(OldVal2Reg).addReg(MaskReg);
8602 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8603 .addReg(ZeroReg).addReg(PtrReg);
8604 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8605 .addReg(TmpDestReg).addReg(MaskReg);
8606 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8607 .addReg(TmpReg).addReg(OldVal3Reg);
8608 BuildMI(BB, dl, TII->get(PPC::BCC))
8609 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8610 BB->addSuccessor(loop2MBB);
8611 BB->addSuccessor(midMBB);
8614 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8615 .addReg(TmpDestReg).addReg(MaskReg);
8616 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8617 .addReg(Tmp2Reg).addReg(NewVal3Reg);
8618 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8619 .addReg(ZeroReg).addReg(PtrReg);
8620 BuildMI(BB, dl, TII->get(PPC::BCC))
8621 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8622 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8623 BB->addSuccessor(loop1MBB);
8624 BB->addSuccessor(exitMBB);
8627 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8628 .addReg(ZeroReg).addReg(PtrReg);
8629 BB->addSuccessor(exitMBB);
8634 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8636 } else if (MI->getOpcode() == PPC::FADDrtz) {
8637 // This pseudo performs an FADD with rounding mode temporarily forced
8638 // to round-to-zero. We emit this via custom inserter since the FPSCR
8639 // is not modeled at the SelectionDAG level.
8640 unsigned Dest = MI->getOperand(0).getReg();
8641 unsigned Src1 = MI->getOperand(1).getReg();
8642 unsigned Src2 = MI->getOperand(2).getReg();
8643 DebugLoc dl = MI->getDebugLoc();
8645 MachineRegisterInfo &RegInfo = F->getRegInfo();
8646 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8648 // Save FPSCR value.
8649 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8651 // Set rounding mode to round-to-zero.
8652 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8653 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8655 // Perform addition.
8656 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8658 // Restore FPSCR value.
8659 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8660 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8661 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8662 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8663 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8664 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8665 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8666 PPC::ANDIo8 : PPC::ANDIo;
8667 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8668 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8670 MachineRegisterInfo &RegInfo = F->getRegInfo();
8671 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8672 &PPC::GPRCRegClass :
8673 &PPC::G8RCRegClass);
8675 DebugLoc dl = MI->getDebugLoc();
8676 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8677 .addReg(MI->getOperand(1).getReg()).addImm(1);
8678 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8679 MI->getOperand(0).getReg())
8680 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8682 llvm_unreachable("Unexpected instr type to insert");
8685 MI->eraseFromParent(); // The pseudo instruction is gone now.
8689 //===----------------------------------------------------------------------===//
8690 // Target Optimization Hooks
8691 //===----------------------------------------------------------------------===//
8693 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8694 DAGCombinerInfo &DCI,
8695 unsigned &RefinementSteps,
8696 bool &UseOneConstNR) const {
8697 EVT VT = Operand.getValueType();
8698 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8699 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8700 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8701 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8702 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8703 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8704 // Convergence is quadratic, so we essentially double the number of digits
8705 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8706 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8707 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8708 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8709 if (VT.getScalarType() == MVT::f64)
8711 UseOneConstNR = true;
8712 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8717 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8718 DAGCombinerInfo &DCI,
8719 unsigned &RefinementSteps) const {
8720 EVT VT = Operand.getValueType();
8721 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8722 (VT == MVT::f64 && Subtarget.hasFRE()) ||
8723 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8724 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8725 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8726 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8727 // Convergence is quadratic, so we essentially double the number of digits
8728 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8729 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8730 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8731 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8732 if (VT.getScalarType() == MVT::f64)
8734 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8739 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8740 // Note: This functionality is used only when unsafe-fp-math is enabled, and
8741 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8742 // enabled for division), this functionality is redundant with the default
8743 // combiner logic (once the division -> reciprocal/multiply transformation
8744 // has taken place). As a result, this matters more for older cores than for
8747 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8748 // reciprocal if there are two or more FDIVs (for embedded cores with only
8749 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8750 switch (Subtarget.getDarwinDirective()) {
8752 return NumUsers > 2;
8755 case PPC::DIR_E500mc:
8756 case PPC::DIR_E5500:
8757 return NumUsers > 1;
8761 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8762 unsigned Bytes, int Dist,
8763 SelectionDAG &DAG) {
8764 if (VT.getSizeInBits() / 8 != Bytes)
8767 SDValue BaseLoc = Base->getBasePtr();
8768 if (Loc.getOpcode() == ISD::FrameIndex) {
8769 if (BaseLoc.getOpcode() != ISD::FrameIndex)
8771 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8772 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
8773 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8774 int FS = MFI->getObjectSize(FI);
8775 int BFS = MFI->getObjectSize(BFI);
8776 if (FS != BFS || FS != (int)Bytes) return false;
8777 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8781 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8782 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8785 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8786 const GlobalValue *GV1 = nullptr;
8787 const GlobalValue *GV2 = nullptr;
8788 int64_t Offset1 = 0;
8789 int64_t Offset2 = 0;
8790 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8791 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8792 if (isGA1 && isGA2 && GV1 == GV2)
8793 return Offset1 == (Offset2 + Dist*Bytes);
8797 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8798 // not enforce equality of the chain operands.
8799 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8800 unsigned Bytes, int Dist,
8801 SelectionDAG &DAG) {
8802 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8803 EVT VT = LS->getMemoryVT();
8804 SDValue Loc = LS->getBasePtr();
8805 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8808 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8810 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8811 default: return false;
8812 case Intrinsic::ppc_qpx_qvlfd:
8813 case Intrinsic::ppc_qpx_qvlfda:
8816 case Intrinsic::ppc_qpx_qvlfs:
8817 case Intrinsic::ppc_qpx_qvlfsa:
8820 case Intrinsic::ppc_qpx_qvlfcd:
8821 case Intrinsic::ppc_qpx_qvlfcda:
8824 case Intrinsic::ppc_qpx_qvlfcs:
8825 case Intrinsic::ppc_qpx_qvlfcsa:
8828 case Intrinsic::ppc_qpx_qvlfiwa:
8829 case Intrinsic::ppc_qpx_qvlfiwz:
8830 case Intrinsic::ppc_altivec_lvx:
8831 case Intrinsic::ppc_altivec_lvxl:
8832 case Intrinsic::ppc_vsx_lxvw4x:
8835 case Intrinsic::ppc_vsx_lxvd2x:
8838 case Intrinsic::ppc_altivec_lvebx:
8841 case Intrinsic::ppc_altivec_lvehx:
8844 case Intrinsic::ppc_altivec_lvewx:
8849 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8852 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8854 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8855 default: return false;
8856 case Intrinsic::ppc_qpx_qvstfd:
8857 case Intrinsic::ppc_qpx_qvstfda:
8860 case Intrinsic::ppc_qpx_qvstfs:
8861 case Intrinsic::ppc_qpx_qvstfsa:
8864 case Intrinsic::ppc_qpx_qvstfcd:
8865 case Intrinsic::ppc_qpx_qvstfcda:
8868 case Intrinsic::ppc_qpx_qvstfcs:
8869 case Intrinsic::ppc_qpx_qvstfcsa:
8872 case Intrinsic::ppc_qpx_qvstfiw:
8873 case Intrinsic::ppc_qpx_qvstfiwa:
8874 case Intrinsic::ppc_altivec_stvx:
8875 case Intrinsic::ppc_altivec_stvxl:
8876 case Intrinsic::ppc_vsx_stxvw4x:
8879 case Intrinsic::ppc_vsx_stxvd2x:
8882 case Intrinsic::ppc_altivec_stvebx:
8885 case Intrinsic::ppc_altivec_stvehx:
8888 case Intrinsic::ppc_altivec_stvewx:
8893 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8899 // Return true is there is a nearyby consecutive load to the one provided
8900 // (regardless of alignment). We search up and down the chain, looking though
8901 // token factors and other loads (but nothing else). As a result, a true result
8902 // indicates that it is safe to create a new consecutive load adjacent to the
8904 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8905 SDValue Chain = LD->getChain();
8906 EVT VT = LD->getMemoryVT();
8908 SmallSet<SDNode *, 16> LoadRoots;
8909 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8910 SmallSet<SDNode *, 16> Visited;
8912 // First, search up the chain, branching to follow all token-factor operands.
8913 // If we find a consecutive load, then we're done, otherwise, record all
8914 // nodes just above the top-level loads and token factors.
8915 while (!Queue.empty()) {
8916 SDNode *ChainNext = Queue.pop_back_val();
8917 if (!Visited.insert(ChainNext).second)
8920 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8921 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8924 if (!Visited.count(ChainLD->getChain().getNode()))
8925 Queue.push_back(ChainLD->getChain().getNode());
8926 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8927 for (const SDUse &O : ChainNext->ops())
8928 if (!Visited.count(O.getNode()))
8929 Queue.push_back(O.getNode());
8931 LoadRoots.insert(ChainNext);
8934 // Second, search down the chain, starting from the top-level nodes recorded
8935 // in the first phase. These top-level nodes are the nodes just above all
8936 // loads and token factors. Starting with their uses, recursively look though
8937 // all loads (just the chain uses) and token factors to find a consecutive
8942 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8943 IE = LoadRoots.end(); I != IE; ++I) {
8944 Queue.push_back(*I);
8946 while (!Queue.empty()) {
8947 SDNode *LoadRoot = Queue.pop_back_val();
8948 if (!Visited.insert(LoadRoot).second)
8951 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8952 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8955 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8956 UE = LoadRoot->use_end(); UI != UE; ++UI)
8957 if (((isa<MemSDNode>(*UI) &&
8958 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8959 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8960 Queue.push_back(*UI);
8967 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8968 DAGCombinerInfo &DCI) const {
8969 SelectionDAG &DAG = DCI.DAG;
8972 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8973 // If we're tracking CR bits, we need to be careful that we don't have:
8974 // trunc(binary-ops(zext(x), zext(y)))
8976 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8977 // such that we're unnecessarily moving things into GPRs when it would be
8978 // better to keep them in CR bits.
8980 // Note that trunc here can be an actual i1 trunc, or can be the effective
8981 // truncation that comes from a setcc or select_cc.
8982 if (N->getOpcode() == ISD::TRUNCATE &&
8983 N->getValueType(0) != MVT::i1)
8986 if (N->getOperand(0).getValueType() != MVT::i32 &&
8987 N->getOperand(0).getValueType() != MVT::i64)
8990 if (N->getOpcode() == ISD::SETCC ||
8991 N->getOpcode() == ISD::SELECT_CC) {
8992 // If we're looking at a comparison, then we need to make sure that the
8993 // high bits (all except for the first) don't matter the result.
8995 cast<CondCodeSDNode>(N->getOperand(
8996 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8997 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8999 if (ISD::isSignedIntSetCC(CC)) {
9000 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9001 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9003 } else if (ISD::isUnsignedIntSetCC(CC)) {
9004 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9005 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9006 !DAG.MaskedValueIsZero(N->getOperand(1),
9007 APInt::getHighBitsSet(OpBits, OpBits-1)))
9010 // This is neither a signed nor an unsigned comparison, just make sure
9011 // that the high bits are equal.
9012 APInt Op1Zero, Op1One;
9013 APInt Op2Zero, Op2One;
9014 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9015 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9017 // We don't really care about what is known about the first bit (if
9018 // anything), so clear it in all masks prior to comparing them.
9019 Op1Zero.clearBit(0); Op1One.clearBit(0);
9020 Op2Zero.clearBit(0); Op2One.clearBit(0);
9022 if (Op1Zero != Op2Zero || Op1One != Op2One)
9027 // We now know that the higher-order bits are irrelevant, we just need to
9028 // make sure that all of the intermediate operations are bit operations, and
9029 // all inputs are extensions.
9030 if (N->getOperand(0).getOpcode() != ISD::AND &&
9031 N->getOperand(0).getOpcode() != ISD::OR &&
9032 N->getOperand(0).getOpcode() != ISD::XOR &&
9033 N->getOperand(0).getOpcode() != ISD::SELECT &&
9034 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9035 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9036 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9037 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9038 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9041 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9042 N->getOperand(1).getOpcode() != ISD::AND &&
9043 N->getOperand(1).getOpcode() != ISD::OR &&
9044 N->getOperand(1).getOpcode() != ISD::XOR &&
9045 N->getOperand(1).getOpcode() != ISD::SELECT &&
9046 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9047 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9048 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9049 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9050 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9053 SmallVector<SDValue, 4> Inputs;
9054 SmallVector<SDValue, 8> BinOps, PromOps;
9055 SmallPtrSet<SDNode *, 16> Visited;
9057 for (unsigned i = 0; i < 2; ++i) {
9058 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9059 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9060 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9061 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9062 isa<ConstantSDNode>(N->getOperand(i)))
9063 Inputs.push_back(N->getOperand(i));
9065 BinOps.push_back(N->getOperand(i));
9067 if (N->getOpcode() == ISD::TRUNCATE)
9071 // Visit all inputs, collect all binary operations (and, or, xor and
9072 // select) that are all fed by extensions.
9073 while (!BinOps.empty()) {
9074 SDValue BinOp = BinOps.back();
9077 if (!Visited.insert(BinOp.getNode()).second)
9080 PromOps.push_back(BinOp);
9082 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9083 // The condition of the select is not promoted.
9084 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9086 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9089 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9090 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9091 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9092 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9093 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9094 Inputs.push_back(BinOp.getOperand(i));
9095 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9096 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9097 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9098 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9099 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9100 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9101 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9102 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9103 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9104 BinOps.push_back(BinOp.getOperand(i));
9106 // We have an input that is not an extension or another binary
9107 // operation; we'll abort this transformation.
9113 // Make sure that this is a self-contained cluster of operations (which
9114 // is not quite the same thing as saying that everything has only one
9116 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9117 if (isa<ConstantSDNode>(Inputs[i]))
9120 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9121 UE = Inputs[i].getNode()->use_end();
9124 if (User != N && !Visited.count(User))
9127 // Make sure that we're not going to promote the non-output-value
9128 // operand(s) or SELECT or SELECT_CC.
9129 // FIXME: Although we could sometimes handle this, and it does occur in
9130 // practice that one of the condition inputs to the select is also one of
9131 // the outputs, we currently can't deal with this.
9132 if (User->getOpcode() == ISD::SELECT) {
9133 if (User->getOperand(0) == Inputs[i])
9135 } else if (User->getOpcode() == ISD::SELECT_CC) {
9136 if (User->getOperand(0) == Inputs[i] ||
9137 User->getOperand(1) == Inputs[i])
9143 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9144 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9145 UE = PromOps[i].getNode()->use_end();
9148 if (User != N && !Visited.count(User))
9151 // Make sure that we're not going to promote the non-output-value
9152 // operand(s) or SELECT or SELECT_CC.
9153 // FIXME: Although we could sometimes handle this, and it does occur in
9154 // practice that one of the condition inputs to the select is also one of
9155 // the outputs, we currently can't deal with this.
9156 if (User->getOpcode() == ISD::SELECT) {
9157 if (User->getOperand(0) == PromOps[i])
9159 } else if (User->getOpcode() == ISD::SELECT_CC) {
9160 if (User->getOperand(0) == PromOps[i] ||
9161 User->getOperand(1) == PromOps[i])
9167 // Replace all inputs with the extension operand.
9168 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9169 // Constants may have users outside the cluster of to-be-promoted nodes,
9170 // and so we need to replace those as we do the promotions.
9171 if (isa<ConstantSDNode>(Inputs[i]))
9174 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9177 // Replace all operations (these are all the same, but have a different
9178 // (i1) return type). DAG.getNode will validate that the types of
9179 // a binary operator match, so go through the list in reverse so that
9180 // we've likely promoted both operands first. Any intermediate truncations or
9181 // extensions disappear.
9182 while (!PromOps.empty()) {
9183 SDValue PromOp = PromOps.back();
9186 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9187 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9188 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9189 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9190 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9191 PromOp.getOperand(0).getValueType() != MVT::i1) {
9192 // The operand is not yet ready (see comment below).
9193 PromOps.insert(PromOps.begin(), PromOp);
9197 SDValue RepValue = PromOp.getOperand(0);
9198 if (isa<ConstantSDNode>(RepValue))
9199 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9201 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9206 switch (PromOp.getOpcode()) {
9207 default: C = 0; break;
9208 case ISD::SELECT: C = 1; break;
9209 case ISD::SELECT_CC: C = 2; break;
9212 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9213 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9214 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9215 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9216 // The to-be-promoted operands of this node have not yet been
9217 // promoted (this should be rare because we're going through the
9218 // list backward, but if one of the operands has several users in
9219 // this cluster of to-be-promoted nodes, it is possible).
9220 PromOps.insert(PromOps.begin(), PromOp);
9224 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9225 PromOp.getNode()->op_end());
9227 // If there are any constant inputs, make sure they're replaced now.
9228 for (unsigned i = 0; i < 2; ++i)
9229 if (isa<ConstantSDNode>(Ops[C+i]))
9230 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9232 DAG.ReplaceAllUsesOfValueWith(PromOp,
9233 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9236 // Now we're left with the initial truncation itself.
9237 if (N->getOpcode() == ISD::TRUNCATE)
9238 return N->getOperand(0);
9240 // Otherwise, this is a comparison. The operands to be compared have just
9241 // changed type (to i1), but everything else is the same.
9242 return SDValue(N, 0);
9245 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9246 DAGCombinerInfo &DCI) const {
9247 SelectionDAG &DAG = DCI.DAG;
9250 // If we're tracking CR bits, we need to be careful that we don't have:
9251 // zext(binary-ops(trunc(x), trunc(y)))
9253 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9254 // such that we're unnecessarily moving things into CR bits that can more
9255 // efficiently stay in GPRs. Note that if we're not certain that the high
9256 // bits are set as required by the final extension, we still may need to do
9257 // some masking to get the proper behavior.
9259 // This same functionality is important on PPC64 when dealing with
9260 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9261 // the return values of functions. Because it is so similar, it is handled
9264 if (N->getValueType(0) != MVT::i32 &&
9265 N->getValueType(0) != MVT::i64)
9268 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9269 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9272 if (N->getOperand(0).getOpcode() != ISD::AND &&
9273 N->getOperand(0).getOpcode() != ISD::OR &&
9274 N->getOperand(0).getOpcode() != ISD::XOR &&
9275 N->getOperand(0).getOpcode() != ISD::SELECT &&
9276 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9279 SmallVector<SDValue, 4> Inputs;
9280 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9281 SmallPtrSet<SDNode *, 16> Visited;
9283 // Visit all inputs, collect all binary operations (and, or, xor and
9284 // select) that are all fed by truncations.
9285 while (!BinOps.empty()) {
9286 SDValue BinOp = BinOps.back();
9289 if (!Visited.insert(BinOp.getNode()).second)
9292 PromOps.push_back(BinOp);
9294 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9295 // The condition of the select is not promoted.
9296 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9298 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9301 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9302 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9303 Inputs.push_back(BinOp.getOperand(i));
9304 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9305 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9306 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9307 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9308 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9309 BinOps.push_back(BinOp.getOperand(i));
9311 // We have an input that is not a truncation or another binary
9312 // operation; we'll abort this transformation.
9318 // The operands of a select that must be truncated when the select is
9319 // promoted because the operand is actually part of the to-be-promoted set.
9320 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9322 // Make sure that this is a self-contained cluster of operations (which
9323 // is not quite the same thing as saying that everything has only one
9325 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9326 if (isa<ConstantSDNode>(Inputs[i]))
9329 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9330 UE = Inputs[i].getNode()->use_end();
9333 if (User != N && !Visited.count(User))
9336 // If we're going to promote the non-output-value operand(s) or SELECT or
9337 // SELECT_CC, record them for truncation.
9338 if (User->getOpcode() == ISD::SELECT) {
9339 if (User->getOperand(0) == Inputs[i])
9340 SelectTruncOp[0].insert(std::make_pair(User,
9341 User->getOperand(0).getValueType()));
9342 } else if (User->getOpcode() == ISD::SELECT_CC) {
9343 if (User->getOperand(0) == Inputs[i])
9344 SelectTruncOp[0].insert(std::make_pair(User,
9345 User->getOperand(0).getValueType()));
9346 if (User->getOperand(1) == Inputs[i])
9347 SelectTruncOp[1].insert(std::make_pair(User,
9348 User->getOperand(1).getValueType()));
9353 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9354 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9355 UE = PromOps[i].getNode()->use_end();
9358 if (User != N && !Visited.count(User))
9361 // If we're going to promote the non-output-value operand(s) or SELECT or
9362 // SELECT_CC, record them for truncation.
9363 if (User->getOpcode() == ISD::SELECT) {
9364 if (User->getOperand(0) == PromOps[i])
9365 SelectTruncOp[0].insert(std::make_pair(User,
9366 User->getOperand(0).getValueType()));
9367 } else if (User->getOpcode() == ISD::SELECT_CC) {
9368 if (User->getOperand(0) == PromOps[i])
9369 SelectTruncOp[0].insert(std::make_pair(User,
9370 User->getOperand(0).getValueType()));
9371 if (User->getOperand(1) == PromOps[i])
9372 SelectTruncOp[1].insert(std::make_pair(User,
9373 User->getOperand(1).getValueType()));
9378 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9379 bool ReallyNeedsExt = false;
9380 if (N->getOpcode() != ISD::ANY_EXTEND) {
9381 // If all of the inputs are not already sign/zero extended, then
9382 // we'll still need to do that at the end.
9383 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9384 if (isa<ConstantSDNode>(Inputs[i]))
9388 Inputs[i].getOperand(0).getValueSizeInBits();
9389 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9391 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9392 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9393 APInt::getHighBitsSet(OpBits,
9394 OpBits-PromBits))) ||
9395 (N->getOpcode() == ISD::SIGN_EXTEND &&
9396 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9397 (OpBits-(PromBits-1)))) {
9398 ReallyNeedsExt = true;
9404 // Replace all inputs, either with the truncation operand, or a
9405 // truncation or extension to the final output type.
9406 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9407 // Constant inputs need to be replaced with the to-be-promoted nodes that
9408 // use them because they might have users outside of the cluster of
9410 if (isa<ConstantSDNode>(Inputs[i]))
9413 SDValue InSrc = Inputs[i].getOperand(0);
9414 if (Inputs[i].getValueType() == N->getValueType(0))
9415 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9416 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9417 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9418 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9419 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9420 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9421 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9423 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9424 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9427 // Replace all operations (these are all the same, but have a different
9428 // (promoted) return type). DAG.getNode will validate that the types of
9429 // a binary operator match, so go through the list in reverse so that
9430 // we've likely promoted both operands first.
9431 while (!PromOps.empty()) {
9432 SDValue PromOp = PromOps.back();
9436 switch (PromOp.getOpcode()) {
9437 default: C = 0; break;
9438 case ISD::SELECT: C = 1; break;
9439 case ISD::SELECT_CC: C = 2; break;
9442 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9443 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9444 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9445 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9446 // The to-be-promoted operands of this node have not yet been
9447 // promoted (this should be rare because we're going through the
9448 // list backward, but if one of the operands has several users in
9449 // this cluster of to-be-promoted nodes, it is possible).
9450 PromOps.insert(PromOps.begin(), PromOp);
9454 // For SELECT and SELECT_CC nodes, we do a similar check for any
9455 // to-be-promoted comparison inputs.
9456 if (PromOp.getOpcode() == ISD::SELECT ||
9457 PromOp.getOpcode() == ISD::SELECT_CC) {
9458 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9459 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9460 (SelectTruncOp[1].count(PromOp.getNode()) &&
9461 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9462 PromOps.insert(PromOps.begin(), PromOp);
9467 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9468 PromOp.getNode()->op_end());
9470 // If this node has constant inputs, then they'll need to be promoted here.
9471 for (unsigned i = 0; i < 2; ++i) {
9472 if (!isa<ConstantSDNode>(Ops[C+i]))
9474 if (Ops[C+i].getValueType() == N->getValueType(0))
9477 if (N->getOpcode() == ISD::SIGN_EXTEND)
9478 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9479 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9480 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9482 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9485 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9486 // truncate them again to the original value type.
9487 if (PromOp.getOpcode() == ISD::SELECT ||
9488 PromOp.getOpcode() == ISD::SELECT_CC) {
9489 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9490 if (SI0 != SelectTruncOp[0].end())
9491 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9492 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9493 if (SI1 != SelectTruncOp[1].end())
9494 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9497 DAG.ReplaceAllUsesOfValueWith(PromOp,
9498 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9501 // Now we're left with the initial extension itself.
9502 if (!ReallyNeedsExt)
9503 return N->getOperand(0);
9505 // To zero extend, just mask off everything except for the first bit (in the
9507 if (N->getOpcode() == ISD::ZERO_EXTEND)
9508 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9509 DAG.getConstant(APInt::getLowBitsSet(
9510 N->getValueSizeInBits(0), PromBits),
9511 N->getValueType(0)));
9513 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9514 "Invalid extension type");
9515 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9517 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9518 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
9519 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9520 N->getOperand(0), ShiftCst), ShiftCst);
9523 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9524 DAGCombinerInfo &DCI) const {
9525 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9526 N->getOpcode() == ISD::UINT_TO_FP) &&
9527 "Need an int -> FP conversion node here");
9529 if (!Subtarget.has64BitSupport())
9532 SelectionDAG &DAG = DCI.DAG;
9536 // Don't handle ppc_fp128 here or i1 conversions.
9537 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9539 if (Op.getOperand(0).getValueType() == MVT::i1)
9542 // For i32 intermediate values, unfortunately, the conversion functions
9543 // leave the upper 32 bits of the value are undefined. Within the set of
9544 // scalar instructions, we have no method for zero- or sign-extending the
9545 // value. Thus, we cannot handle i32 intermediate values here.
9546 if (Op.getOperand(0).getValueType() == MVT::i32)
9549 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9550 "UINT_TO_FP is supported only with FPCVT");
9552 // If we have FCFIDS, then use it when converting to single-precision.
9553 // Otherwise, convert to double-precision and then round.
9554 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9555 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9557 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9559 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9563 // If we're converting from a float, to an int, and back to a float again,
9564 // then we don't need the store/load pair at all.
9565 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9566 Subtarget.hasFPCVT()) ||
9567 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9568 SDValue Src = Op.getOperand(0).getOperand(0);
9569 if (Src.getValueType() == MVT::f32) {
9570 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9571 DCI.AddToWorklist(Src.getNode());
9575 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9578 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9579 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9581 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9582 FP = DAG.getNode(ISD::FP_ROUND, dl,
9583 MVT::f32, FP, DAG.getIntPtrConstant(0));
9584 DCI.AddToWorklist(FP.getNode());
9593 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9594 // builtins) into loads with swaps.
9595 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9596 DAGCombinerInfo &DCI) const {
9597 SelectionDAG &DAG = DCI.DAG;
9601 MachineMemOperand *MMO;
9603 switch (N->getOpcode()) {
9605 llvm_unreachable("Unexpected opcode for little endian VSX load");
9607 LoadSDNode *LD = cast<LoadSDNode>(N);
9608 Chain = LD->getChain();
9609 Base = LD->getBasePtr();
9610 MMO = LD->getMemOperand();
9611 // If the MMO suggests this isn't a load of a full vector, leave
9612 // things alone. For a built-in, we have to make the change for
9613 // correctness, so if there is a size problem that will be a bug.
9614 if (MMO->getSize() < 16)
9618 case ISD::INTRINSIC_W_CHAIN: {
9619 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9620 Chain = Intrin->getChain();
9621 Base = Intrin->getBasePtr();
9622 MMO = Intrin->getMemOperand();
9627 MVT VecTy = N->getValueType(0).getSimpleVT();
9628 SDValue LoadOps[] = { Chain, Base };
9629 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9630 DAG.getVTList(VecTy, MVT::Other),
9631 LoadOps, VecTy, MMO);
9632 DCI.AddToWorklist(Load.getNode());
9633 Chain = Load.getValue(1);
9634 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9635 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9636 DCI.AddToWorklist(Swap.getNode());
9640 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9641 // builtins) into stores with swaps.
9642 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9643 DAGCombinerInfo &DCI) const {
9644 SelectionDAG &DAG = DCI.DAG;
9649 MachineMemOperand *MMO;
9651 switch (N->getOpcode()) {
9653 llvm_unreachable("Unexpected opcode for little endian VSX store");
9655 StoreSDNode *ST = cast<StoreSDNode>(N);
9656 Chain = ST->getChain();
9657 Base = ST->getBasePtr();
9658 MMO = ST->getMemOperand();
9660 // If the MMO suggests this isn't a store of a full vector, leave
9661 // things alone. For a built-in, we have to make the change for
9662 // correctness, so if there is a size problem that will be a bug.
9663 if (MMO->getSize() < 16)
9667 case ISD::INTRINSIC_VOID: {
9668 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9669 Chain = Intrin->getChain();
9670 // Intrin->getBasePtr() oddly does not get what we want.
9671 Base = Intrin->getOperand(3);
9672 MMO = Intrin->getMemOperand();
9678 SDValue Src = N->getOperand(SrcOpnd);
9679 MVT VecTy = Src.getValueType().getSimpleVT();
9680 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9681 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9682 DCI.AddToWorklist(Swap.getNode());
9683 Chain = Swap.getValue(1);
9684 SDValue StoreOps[] = { Chain, Swap, Base };
9685 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9686 DAG.getVTList(MVT::Other),
9687 StoreOps, VecTy, MMO);
9688 DCI.AddToWorklist(Store.getNode());
9692 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9693 DAGCombinerInfo &DCI) const {
9694 SelectionDAG &DAG = DCI.DAG;
9696 switch (N->getOpcode()) {
9699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9700 if (C->isNullValue()) // 0 << V -> 0.
9701 return N->getOperand(0);
9705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9706 if (C->isNullValue()) // 0 >>u V -> 0.
9707 return N->getOperand(0);
9711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9712 if (C->isNullValue() || // 0 >>s V -> 0.
9713 C->isAllOnesValue()) // -1 >>s V -> -1.
9714 return N->getOperand(0);
9717 case ISD::SIGN_EXTEND:
9718 case ISD::ZERO_EXTEND:
9719 case ISD::ANY_EXTEND:
9720 return DAGCombineExtBoolTrunc(N, DCI);
9723 case ISD::SELECT_CC:
9724 return DAGCombineTruncBoolExt(N, DCI);
9725 case ISD::SINT_TO_FP:
9726 case ISD::UINT_TO_FP:
9727 return combineFPToIntToFP(N, DCI);
9729 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9730 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9731 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9732 N->getOperand(1).getValueType() == MVT::i32 &&
9733 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9734 SDValue Val = N->getOperand(1).getOperand(0);
9735 if (Val.getValueType() == MVT::f32) {
9736 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9737 DCI.AddToWorklist(Val.getNode());
9739 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9740 DCI.AddToWorklist(Val.getNode());
9743 N->getOperand(0), Val, N->getOperand(2),
9744 DAG.getValueType(N->getOperand(1).getValueType())
9747 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9748 DAG.getVTList(MVT::Other), Ops,
9749 cast<StoreSDNode>(N)->getMemoryVT(),
9750 cast<StoreSDNode>(N)->getMemOperand());
9751 DCI.AddToWorklist(Val.getNode());
9755 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9756 if (cast<StoreSDNode>(N)->isUnindexed() &&
9757 N->getOperand(1).getOpcode() == ISD::BSWAP &&
9758 N->getOperand(1).getNode()->hasOneUse() &&
9759 (N->getOperand(1).getValueType() == MVT::i32 ||
9760 N->getOperand(1).getValueType() == MVT::i16 ||
9761 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9762 N->getOperand(1).getValueType() == MVT::i64))) {
9763 SDValue BSwapOp = N->getOperand(1).getOperand(0);
9764 // Do an any-extend to 32-bits if this is a half-word input.
9765 if (BSwapOp.getValueType() == MVT::i16)
9766 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9769 N->getOperand(0), BSwapOp, N->getOperand(2),
9770 DAG.getValueType(N->getOperand(1).getValueType())
9773 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9774 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9775 cast<StoreSDNode>(N)->getMemOperand());
9778 // For little endian, VSX stores require generating xxswapd/lxvd2x.
9779 EVT VT = N->getOperand(1).getValueType();
9780 if (VT.isSimple()) {
9781 MVT StoreVT = VT.getSimpleVT();
9782 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9783 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9784 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9785 return expandVSXStoreForLE(N, DCI);
9790 LoadSDNode *LD = cast<LoadSDNode>(N);
9791 EVT VT = LD->getValueType(0);
9793 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9794 if (VT.isSimple()) {
9795 MVT LoadVT = VT.getSimpleVT();
9796 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9797 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9798 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9799 return expandVSXLoadForLE(N, DCI);
9802 EVT MemVT = LD->getMemoryVT();
9803 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9804 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9805 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9806 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9807 if (LD->isUnindexed() && VT.isVector() &&
9808 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9809 // P8 and later hardware should just use LOAD.
9810 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9811 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9812 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9813 LD->getAlignment() >= ScalarABIAlignment)) &&
9814 LD->getAlignment() < ABIAlignment) {
9815 // This is a type-legal unaligned Altivec or QPX load.
9816 SDValue Chain = LD->getChain();
9817 SDValue Ptr = LD->getBasePtr();
9818 bool isLittleEndian = Subtarget.isLittleEndian();
9820 // This implements the loading of unaligned vectors as described in
9821 // the venerable Apple Velocity Engine overview. Specifically:
9822 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9823 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9825 // The general idea is to expand a sequence of one or more unaligned
9826 // loads into an alignment-based permutation-control instruction (lvsl
9827 // or lvsr), a series of regular vector loads (which always truncate
9828 // their input address to an aligned address), and a series of
9829 // permutations. The results of these permutations are the requested
9830 // loaded values. The trick is that the last "extra" load is not taken
9831 // from the address you might suspect (sizeof(vector) bytes after the
9832 // last requested load), but rather sizeof(vector) - 1 bytes after the
9833 // last requested vector. The point of this is to avoid a page fault if
9834 // the base address happened to be aligned. This works because if the
9835 // base address is aligned, then adding less than a full vector length
9836 // will cause the last vector in the sequence to be (re)loaded.
9837 // Otherwise, the next vector will be fetched as you might suspect was
9840 // We might be able to reuse the permutation generation from
9841 // a different base address offset from this one by an aligned amount.
9842 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9843 // optimization later.
9844 Intrinsic::ID Intr, IntrLD, IntrPerm;
9845 MVT PermCntlTy, PermTy, LDTy;
9846 if (Subtarget.hasAltivec()) {
9847 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
9848 Intrinsic::ppc_altivec_lvsl;
9849 IntrLD = Intrinsic::ppc_altivec_lvx;
9850 IntrPerm = Intrinsic::ppc_altivec_vperm;
9851 PermCntlTy = MVT::v16i8;
9852 PermTy = MVT::v4i32;
9855 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9856 Intrinsic::ppc_qpx_qvlpcls;
9857 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9858 Intrinsic::ppc_qpx_qvlfs;
9859 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9860 PermCntlTy = MVT::v4f64;
9861 PermTy = MVT::v4f64;
9862 LDTy = MemVT.getSimpleVT();
9865 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9867 // Create the new MMO for the new base load. It is like the original MMO,
9868 // but represents an area in memory almost twice the vector size centered
9869 // on the original address. If the address is unaligned, we might start
9870 // reading up to (sizeof(vector)-1) bytes below the address of the
9871 // original unaligned load.
9872 MachineFunction &MF = DAG.getMachineFunction();
9873 MachineMemOperand *BaseMMO =
9874 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9875 2*MemVT.getStoreSize()-1);
9877 // Create the new base load.
9878 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9879 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9881 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9882 DAG.getVTList(PermTy, MVT::Other),
9883 BaseLoadOps, LDTy, BaseMMO);
9885 // Note that the value of IncOffset (which is provided to the next
9886 // load's pointer info offset value, and thus used to calculate the
9887 // alignment), and the value of IncValue (which is actually used to
9888 // increment the pointer value) are different! This is because we
9889 // require the next load to appear to be aligned, even though it
9890 // is actually offset from the base pointer by a lesser amount.
9891 int IncOffset = VT.getSizeInBits() / 8;
9892 int IncValue = IncOffset;
9894 // Walk (both up and down) the chain looking for another load at the real
9895 // (aligned) offset (the alignment of the other load does not matter in
9896 // this case). If found, then do not use the offset reduction trick, as
9897 // that will prevent the loads from being later combined (as they would
9898 // otherwise be duplicates).
9899 if (!findConsecutiveLoad(LD, DAG))
9902 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9903 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9905 MachineMemOperand *ExtraMMO =
9906 MF.getMachineMemOperand(LD->getMemOperand(),
9907 1, 2*MemVT.getStoreSize()-1);
9908 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9910 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9911 DAG.getVTList(PermTy, MVT::Other),
9912 ExtraLoadOps, LDTy, ExtraMMO);
9914 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9915 BaseLoad.getValue(1), ExtraLoad.getValue(1));
9917 // Because vperm has a big-endian bias, we must reverse the order
9918 // of the input vectors and complement the permute control vector
9919 // when generating little endian code. We have already handled the
9920 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9921 // and ExtraLoad here.
9924 Perm = BuildIntrinsicOp(IntrPerm,
9925 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9927 Perm = BuildIntrinsicOp(IntrPerm,
9928 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9931 Perm = Subtarget.hasAltivec() ?
9932 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
9933 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
9934 DAG.getTargetConstant(1, MVT::i64));
9935 // second argument is 1 because this rounding
9938 // The output of the permutation is our loaded result, the TokenFactor is
9940 DCI.CombineTo(N, Perm, TF);
9941 return SDValue(N, 0);
9945 case ISD::INTRINSIC_WO_CHAIN: {
9946 bool isLittleEndian = Subtarget.isLittleEndian();
9947 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9948 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9949 : Intrinsic::ppc_altivec_lvsl);
9951 IID == Intrinsic::ppc_qpx_qvlpcld ||
9952 IID == Intrinsic::ppc_qpx_qvlpcls) &&
9953 N->getOperand(1)->getOpcode() == ISD::ADD) {
9954 SDValue Add = N->getOperand(1);
9956 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
9957 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
9959 if (DAG.MaskedValueIsZero(
9961 APInt::getAllOnesValue(Bits /* alignment */)
9963 Add.getValueType().getScalarType().getSizeInBits()))) {
9964 SDNode *BasePtr = Add->getOperand(0).getNode();
9965 for (SDNode::use_iterator UI = BasePtr->use_begin(),
9966 UE = BasePtr->use_end();
9968 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9969 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
9970 // We've found another LVSL/LVSR, and this address is an aligned
9971 // multiple of that one. The results will be the same, so use the
9972 // one we've just found instead.
9974 return SDValue(*UI, 0);
9979 if (isa<ConstantSDNode>(Add->getOperand(1))) {
9980 SDNode *BasePtr = Add->getOperand(0).getNode();
9981 for (SDNode::use_iterator UI = BasePtr->use_begin(),
9982 UE = BasePtr->use_end(); UI != UE; ++UI) {
9983 if (UI->getOpcode() == ISD::ADD &&
9984 isa<ConstantSDNode>(UI->getOperand(1)) &&
9985 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
9986 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
9987 (1ULL << Bits) == 0) {
9988 SDNode *OtherAdd = *UI;
9989 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
9990 VE = OtherAdd->use_end(); VI != VE; ++VI) {
9991 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9992 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
9993 return SDValue(*VI, 0);
10003 case ISD::INTRINSIC_W_CHAIN: {
10004 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10005 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10006 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10009 case Intrinsic::ppc_vsx_lxvw4x:
10010 case Intrinsic::ppc_vsx_lxvd2x:
10011 return expandVSXLoadForLE(N, DCI);
10016 case ISD::INTRINSIC_VOID: {
10017 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10018 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10019 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10022 case Intrinsic::ppc_vsx_stxvw4x:
10023 case Intrinsic::ppc_vsx_stxvd2x:
10024 return expandVSXStoreForLE(N, DCI);
10030 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10031 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10032 N->getOperand(0).hasOneUse() &&
10033 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10034 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10035 N->getValueType(0) == MVT::i64))) {
10036 SDValue Load = N->getOperand(0);
10037 LoadSDNode *LD = cast<LoadSDNode>(Load);
10038 // Create the byte-swapping load.
10040 LD->getChain(), // Chain
10041 LD->getBasePtr(), // Ptr
10042 DAG.getValueType(N->getValueType(0)) // VT
10045 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10046 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10047 MVT::i64 : MVT::i32, MVT::Other),
10048 Ops, LD->getMemoryVT(), LD->getMemOperand());
10050 // If this is an i16 load, insert the truncate.
10051 SDValue ResVal = BSLoad;
10052 if (N->getValueType(0) == MVT::i16)
10053 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10055 // First, combine the bswap away. This makes the value produced by the
10057 DCI.CombineTo(N, ResVal);
10059 // Next, combine the load away, we give it a bogus result value but a real
10060 // chain result. The result value is dead because the bswap is dead.
10061 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10063 // Return N so it doesn't get rechecked!
10064 return SDValue(N, 0);
10068 case PPCISD::VCMP: {
10069 // If a VCMPo node already exists with exactly the same operands as this
10070 // node, use its result instead of this node (VCMPo computes both a CR6 and
10071 // a normal output).
10073 if (!N->getOperand(0).hasOneUse() &&
10074 !N->getOperand(1).hasOneUse() &&
10075 !N->getOperand(2).hasOneUse()) {
10077 // Scan all of the users of the LHS, looking for VCMPo's that match.
10078 SDNode *VCMPoNode = nullptr;
10080 SDNode *LHSN = N->getOperand(0).getNode();
10081 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10083 if (UI->getOpcode() == PPCISD::VCMPo &&
10084 UI->getOperand(1) == N->getOperand(1) &&
10085 UI->getOperand(2) == N->getOperand(2) &&
10086 UI->getOperand(0) == N->getOperand(0)) {
10091 // If there is no VCMPo node, or if the flag value has a single use, don't
10093 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10096 // Look at the (necessarily single) use of the flag value. If it has a
10097 // chain, this transformation is more complex. Note that multiple things
10098 // could use the value result, which we should ignore.
10099 SDNode *FlagUser = nullptr;
10100 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10101 FlagUser == nullptr; ++UI) {
10102 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10103 SDNode *User = *UI;
10104 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10105 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10112 // If the user is a MFOCRF instruction, we know this is safe.
10113 // Otherwise we give up for right now.
10114 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10115 return SDValue(VCMPoNode, 0);
10119 case ISD::BRCOND: {
10120 SDValue Cond = N->getOperand(1);
10121 SDValue Target = N->getOperand(2);
10123 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10124 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10125 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10127 // We now need to make the intrinsic dead (it cannot be instruction
10129 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10130 assert(Cond.getNode()->hasOneUse() &&
10131 "Counter decrement has more than one use");
10133 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10134 N->getOperand(0), Target);
10139 // If this is a branch on an altivec predicate comparison, lower this so
10140 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10141 // lowering is done pre-legalize, because the legalizer lowers the predicate
10142 // compare down to code that is difficult to reassemble.
10143 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10144 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10146 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10147 // value. If so, pass-through the AND to get to the intrinsic.
10148 if (LHS.getOpcode() == ISD::AND &&
10149 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10150 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10151 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10152 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10153 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10155 LHS = LHS.getOperand(0);
10157 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10158 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10159 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10160 isa<ConstantSDNode>(RHS)) {
10161 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10162 "Counter decrement comparison is not EQ or NE");
10164 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10165 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10166 (CC == ISD::SETNE && !Val);
10168 // We now need to make the intrinsic dead (it cannot be instruction
10170 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10171 assert(LHS.getNode()->hasOneUse() &&
10172 "Counter decrement has more than one use");
10174 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10175 N->getOperand(0), N->getOperand(4));
10181 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10182 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10183 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
10184 assert(isDot && "Can't compare against a vector result!");
10186 // If this is a comparison against something other than 0/1, then we know
10187 // that the condition is never/always true.
10188 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10189 if (Val != 0 && Val != 1) {
10190 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10191 return N->getOperand(0);
10192 // Always !=, turn it into an unconditional branch.
10193 return DAG.getNode(ISD::BR, dl, MVT::Other,
10194 N->getOperand(0), N->getOperand(4));
10197 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10199 // Create the PPCISD altivec 'dot' comparison node.
10201 LHS.getOperand(2), // LHS of compare
10202 LHS.getOperand(3), // RHS of compare
10203 DAG.getConstant(CompareOpc, MVT::i32)
10205 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10206 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10208 // Unpack the result based on how the target uses it.
10209 PPC::Predicate CompOpc;
10210 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10211 default: // Can't happen, don't crash on invalid number though.
10212 case 0: // Branch on the value of the EQ bit of CR6.
10213 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10215 case 1: // Branch on the inverted value of the EQ bit of CR6.
10216 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10218 case 2: // Branch on the value of the LT bit of CR6.
10219 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10221 case 3: // Branch on the inverted value of the LT bit of CR6.
10222 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10226 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10227 DAG.getConstant(CompOpc, MVT::i32),
10228 DAG.getRegister(PPC::CR6, MVT::i32),
10229 N->getOperand(4), CompNode.getValue(1));
10239 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10241 std::vector<SDNode *> *Created) const {
10242 // fold (sdiv X, pow2)
10243 EVT VT = N->getValueType(0);
10244 if (VT == MVT::i64 && !Subtarget.isPPC64())
10246 if ((VT != MVT::i32 && VT != MVT::i64) ||
10247 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10251 SDValue N0 = N->getOperand(0);
10253 bool IsNegPow2 = (-Divisor).isPowerOf2();
10254 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10255 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10257 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10259 Created->push_back(Op.getNode());
10262 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10264 Created->push_back(Op.getNode());
10270 //===----------------------------------------------------------------------===//
10271 // Inline Assembly Support
10272 //===----------------------------------------------------------------------===//
10274 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10277 const SelectionDAG &DAG,
10278 unsigned Depth) const {
10279 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10280 switch (Op.getOpcode()) {
10282 case PPCISD::LBRX: {
10283 // lhbrx is known to have the top bits cleared out.
10284 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10285 KnownZero = 0xFFFF0000;
10288 case ISD::INTRINSIC_WO_CHAIN: {
10289 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10291 case Intrinsic::ppc_altivec_vcmpbfp_p:
10292 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10293 case Intrinsic::ppc_altivec_vcmpequb_p:
10294 case Intrinsic::ppc_altivec_vcmpequh_p:
10295 case Intrinsic::ppc_altivec_vcmpequw_p:
10296 case Intrinsic::ppc_altivec_vcmpgefp_p:
10297 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10298 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10299 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10300 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10301 case Intrinsic::ppc_altivec_vcmpgtub_p:
10302 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10303 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10304 KnownZero = ~1U; // All bits but the low one are known to be zero.
10311 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10312 switch (Subtarget.getDarwinDirective()) {
10315 case PPC::DIR_PWR4:
10316 case PPC::DIR_PWR5:
10317 case PPC::DIR_PWR5X:
10318 case PPC::DIR_PWR6:
10319 case PPC::DIR_PWR6X:
10320 case PPC::DIR_PWR7:
10321 case PPC::DIR_PWR8: {
10325 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10327 // For small loops (between 5 and 8 instructions), align to a 32-byte
10328 // boundary so that the entire loop fits in one instruction-cache line.
10329 uint64_t LoopSize = 0;
10330 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10331 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10332 LoopSize += TII->GetInstSizeInBytes(J);
10334 if (LoopSize > 16 && LoopSize <= 32)
10341 return TargetLowering::getPrefLoopAlignment(ML);
10344 /// getConstraintType - Given a constraint, return the type of
10345 /// constraint it is for this target.
10346 PPCTargetLowering::ConstraintType
10347 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10348 if (Constraint.size() == 1) {
10349 switch (Constraint[0]) {
10356 return C_RegisterClass;
10358 // FIXME: While Z does indicate a memory constraint, it specifically
10359 // indicates an r+r address (used in conjunction with the 'y' modifier
10360 // in the replacement string). Currently, we're forcing the base
10361 // register to be r0 in the asm printer (which is interpreted as zero)
10362 // and forming the complete address in the second register. This is
10366 } else if (Constraint == "wc") { // individual CR bits.
10367 return C_RegisterClass;
10368 } else if (Constraint == "wa" || Constraint == "wd" ||
10369 Constraint == "wf" || Constraint == "ws") {
10370 return C_RegisterClass; // VSX registers.
10372 return TargetLowering::getConstraintType(Constraint);
10375 /// Examine constraint type and operand type and determine a weight value.
10376 /// This object must already have been set up with the operand type
10377 /// and the current alternative constraint selected.
10378 TargetLowering::ConstraintWeight
10379 PPCTargetLowering::getSingleConstraintMatchWeight(
10380 AsmOperandInfo &info, const char *constraint) const {
10381 ConstraintWeight weight = CW_Invalid;
10382 Value *CallOperandVal = info.CallOperandVal;
10383 // If we don't have a value, we can't do a match,
10384 // but allow it at the lowest weight.
10385 if (!CallOperandVal)
10387 Type *type = CallOperandVal->getType();
10389 // Look at the constraint type.
10390 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10391 return CW_Register; // an individual CR bit.
10392 else if ((StringRef(constraint) == "wa" ||
10393 StringRef(constraint) == "wd" ||
10394 StringRef(constraint) == "wf") &&
10395 type->isVectorTy())
10396 return CW_Register;
10397 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10398 return CW_Register;
10400 switch (*constraint) {
10402 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10405 if (type->isIntegerTy())
10406 weight = CW_Register;
10409 if (type->isFloatTy())
10410 weight = CW_Register;
10413 if (type->isDoubleTy())
10414 weight = CW_Register;
10417 if (type->isVectorTy())
10418 weight = CW_Register;
10421 weight = CW_Register;
10424 weight = CW_Memory;
10430 std::pair<unsigned, const TargetRegisterClass*>
10431 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10433 if (Constraint.size() == 1) {
10434 // GCC RS6000 Constraint Letters
10435 switch (Constraint[0]) {
10436 case 'b': // R1-R31
10437 if (VT == MVT::i64 && Subtarget.isPPC64())
10438 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10439 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10440 case 'r': // R0-R31
10441 if (VT == MVT::i64 && Subtarget.isPPC64())
10442 return std::make_pair(0U, &PPC::G8RCRegClass);
10443 return std::make_pair(0U, &PPC::GPRCRegClass);
10445 if (VT == MVT::f32 || VT == MVT::i32)
10446 return std::make_pair(0U, &PPC::F4RCRegClass);
10447 if (VT == MVT::f64 || VT == MVT::i64)
10448 return std::make_pair(0U, &PPC::F8RCRegClass);
10449 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10450 return std::make_pair(0U, &PPC::QFRCRegClass);
10451 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10452 return std::make_pair(0U, &PPC::QSRCRegClass);
10455 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10456 return std::make_pair(0U, &PPC::QFRCRegClass);
10457 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10458 return std::make_pair(0U, &PPC::QSRCRegClass);
10459 return std::make_pair(0U, &PPC::VRRCRegClass);
10461 return std::make_pair(0U, &PPC::CRRCRegClass);
10463 } else if (Constraint == "wc") { // an individual CR bit.
10464 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10465 } else if (Constraint == "wa" || Constraint == "wd" ||
10466 Constraint == "wf") {
10467 return std::make_pair(0U, &PPC::VSRCRegClass);
10468 } else if (Constraint == "ws") {
10469 return std::make_pair(0U, &PPC::VSFRCRegClass);
10472 std::pair<unsigned, const TargetRegisterClass*> R =
10473 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10475 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10476 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10477 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10479 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10480 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10481 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10482 PPC::GPRCRegClass.contains(R.first)) {
10483 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10484 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10485 PPC::sub_32, &PPC::G8RCRegClass),
10486 &PPC::G8RCRegClass);
10489 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10490 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10491 R.first = PPC::CR0;
10492 R.second = &PPC::CRRCRegClass;
10499 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10500 /// vector. If it is invalid, don't add anything to Ops.
10501 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10502 std::string &Constraint,
10503 std::vector<SDValue>&Ops,
10504 SelectionDAG &DAG) const {
10507 // Only support length 1 constraints.
10508 if (Constraint.length() > 1) return;
10510 char Letter = Constraint[0];
10521 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10522 if (!CST) return; // Must be an immediate to match.
10523 int64_t Value = CST->getSExtValue();
10524 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10525 // numbers are printed as such.
10527 default: llvm_unreachable("Unknown constraint letter!");
10528 case 'I': // "I" is a signed 16-bit constant.
10529 if (isInt<16>(Value))
10530 Result = DAG.getTargetConstant(Value, TCVT);
10532 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
10533 if (isShiftedUInt<16, 16>(Value))
10534 Result = DAG.getTargetConstant(Value, TCVT);
10536 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
10537 if (isShiftedInt<16, 16>(Value))
10538 Result = DAG.getTargetConstant(Value, TCVT);
10540 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
10541 if (isUInt<16>(Value))
10542 Result = DAG.getTargetConstant(Value, TCVT);
10544 case 'M': // "M" is a constant that is greater than 31.
10546 Result = DAG.getTargetConstant(Value, TCVT);
10548 case 'N': // "N" is a positive constant that is an exact power of two.
10549 if (Value > 0 && isPowerOf2_64(Value))
10550 Result = DAG.getTargetConstant(Value, TCVT);
10552 case 'O': // "O" is the constant zero.
10554 Result = DAG.getTargetConstant(Value, TCVT);
10556 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
10557 if (isInt<16>(-Value))
10558 Result = DAG.getTargetConstant(Value, TCVT);
10565 if (Result.getNode()) {
10566 Ops.push_back(Result);
10570 // Handle standard constraint letters.
10571 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10574 // isLegalAddressingMode - Return true if the addressing mode represented
10575 // by AM is legal for this target, for a load/store of the specified type.
10576 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10578 // PPC does not allow r+i addressing modes for vectors!
10579 if (Ty->isVectorTy() && AM.BaseOffs != 0)
10582 // PPC allows a sign-extended 16-bit immediate field.
10583 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10586 // No global is ever allowed as a base.
10590 // PPC only support r+r,
10591 switch (AM.Scale) {
10592 case 0: // "r+i" or just "i", depending on HasBaseReg.
10595 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
10597 // Otherwise we have r+r or r+i.
10600 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
10602 // Allow 2*r as r+r.
10605 // No other scales are supported.
10612 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10613 SelectionDAG &DAG) const {
10614 MachineFunction &MF = DAG.getMachineFunction();
10615 MachineFrameInfo *MFI = MF.getFrameInfo();
10616 MFI->setReturnAddressIsTaken(true);
10618 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10622 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10624 // Make sure the function does not optimize away the store of the RA to
10626 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10627 FuncInfo->setLRStoreRequired();
10628 bool isPPC64 = Subtarget.isPPC64();
10631 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10633 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10634 isPPC64 ? MVT::i64 : MVT::i32);
10635 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10636 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10637 FrameAddr, Offset),
10638 MachinePointerInfo(), false, false, false, 0);
10641 // Just load the return address off the stack.
10642 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10643 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10644 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10647 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10648 SelectionDAG &DAG) const {
10650 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10652 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10653 bool isPPC64 = PtrVT == MVT::i64;
10655 MachineFunction &MF = DAG.getMachineFunction();
10656 MachineFrameInfo *MFI = MF.getFrameInfo();
10657 MFI->setFrameAddressIsTaken(true);
10659 // Naked functions never have a frame pointer, and so we use r1. For all
10660 // other functions, this decision must be delayed until during PEI.
10662 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10663 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10665 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10667 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10670 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10671 FrameAddr, MachinePointerInfo(), false, false,
10676 // FIXME? Maybe this could be a TableGen attribute on some registers and
10677 // this table could be generated automatically from RegInfo.
10678 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10680 bool isPPC64 = Subtarget.isPPC64();
10681 bool isDarwinABI = Subtarget.isDarwinABI();
10683 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10684 (!isPPC64 && VT != MVT::i32))
10685 report_fatal_error("Invalid register global variable type");
10687 bool is64Bit = isPPC64 && VT == MVT::i64;
10688 unsigned Reg = StringSwitch<unsigned>(RegName)
10689 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10690 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10691 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10692 (is64Bit ? PPC::X13 : PPC::R13))
10697 report_fatal_error("Invalid register name global variable");
10701 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10702 // The PowerPC target isn't yet aware of offsets.
10706 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10708 unsigned Intrinsic) const {
10710 switch (Intrinsic) {
10711 case Intrinsic::ppc_qpx_qvlfd:
10712 case Intrinsic::ppc_qpx_qvlfs:
10713 case Intrinsic::ppc_qpx_qvlfcd:
10714 case Intrinsic::ppc_qpx_qvlfcs:
10715 case Intrinsic::ppc_qpx_qvlfiwa:
10716 case Intrinsic::ppc_qpx_qvlfiwz:
10717 case Intrinsic::ppc_altivec_lvx:
10718 case Intrinsic::ppc_altivec_lvxl:
10719 case Intrinsic::ppc_altivec_lvebx:
10720 case Intrinsic::ppc_altivec_lvehx:
10721 case Intrinsic::ppc_altivec_lvewx:
10722 case Intrinsic::ppc_vsx_lxvd2x:
10723 case Intrinsic::ppc_vsx_lxvw4x: {
10725 switch (Intrinsic) {
10726 case Intrinsic::ppc_altivec_lvebx:
10729 case Intrinsic::ppc_altivec_lvehx:
10732 case Intrinsic::ppc_altivec_lvewx:
10735 case Intrinsic::ppc_vsx_lxvd2x:
10738 case Intrinsic::ppc_qpx_qvlfd:
10741 case Intrinsic::ppc_qpx_qvlfs:
10744 case Intrinsic::ppc_qpx_qvlfcd:
10747 case Intrinsic::ppc_qpx_qvlfcs:
10755 Info.opc = ISD::INTRINSIC_W_CHAIN;
10757 Info.ptrVal = I.getArgOperand(0);
10758 Info.offset = -VT.getStoreSize()+1;
10759 Info.size = 2*VT.getStoreSize()-1;
10762 Info.readMem = true;
10763 Info.writeMem = false;
10766 case Intrinsic::ppc_qpx_qvlfda:
10767 case Intrinsic::ppc_qpx_qvlfsa:
10768 case Intrinsic::ppc_qpx_qvlfcda:
10769 case Intrinsic::ppc_qpx_qvlfcsa:
10770 case Intrinsic::ppc_qpx_qvlfiwaa:
10771 case Intrinsic::ppc_qpx_qvlfiwza: {
10773 switch (Intrinsic) {
10774 case Intrinsic::ppc_qpx_qvlfda:
10777 case Intrinsic::ppc_qpx_qvlfsa:
10780 case Intrinsic::ppc_qpx_qvlfcda:
10783 case Intrinsic::ppc_qpx_qvlfcsa:
10791 Info.opc = ISD::INTRINSIC_W_CHAIN;
10793 Info.ptrVal = I.getArgOperand(0);
10795 Info.size = VT.getStoreSize();
10798 Info.readMem = true;
10799 Info.writeMem = false;
10802 case Intrinsic::ppc_qpx_qvstfd:
10803 case Intrinsic::ppc_qpx_qvstfs:
10804 case Intrinsic::ppc_qpx_qvstfcd:
10805 case Intrinsic::ppc_qpx_qvstfcs:
10806 case Intrinsic::ppc_qpx_qvstfiw:
10807 case Intrinsic::ppc_altivec_stvx:
10808 case Intrinsic::ppc_altivec_stvxl:
10809 case Intrinsic::ppc_altivec_stvebx:
10810 case Intrinsic::ppc_altivec_stvehx:
10811 case Intrinsic::ppc_altivec_stvewx:
10812 case Intrinsic::ppc_vsx_stxvd2x:
10813 case Intrinsic::ppc_vsx_stxvw4x: {
10815 switch (Intrinsic) {
10816 case Intrinsic::ppc_altivec_stvebx:
10819 case Intrinsic::ppc_altivec_stvehx:
10822 case Intrinsic::ppc_altivec_stvewx:
10825 case Intrinsic::ppc_vsx_stxvd2x:
10828 case Intrinsic::ppc_qpx_qvstfd:
10831 case Intrinsic::ppc_qpx_qvstfs:
10834 case Intrinsic::ppc_qpx_qvstfcd:
10837 case Intrinsic::ppc_qpx_qvstfcs:
10845 Info.opc = ISD::INTRINSIC_VOID;
10847 Info.ptrVal = I.getArgOperand(1);
10848 Info.offset = -VT.getStoreSize()+1;
10849 Info.size = 2*VT.getStoreSize()-1;
10852 Info.readMem = false;
10853 Info.writeMem = true;
10856 case Intrinsic::ppc_qpx_qvstfda:
10857 case Intrinsic::ppc_qpx_qvstfsa:
10858 case Intrinsic::ppc_qpx_qvstfcda:
10859 case Intrinsic::ppc_qpx_qvstfcsa:
10860 case Intrinsic::ppc_qpx_qvstfiwa: {
10862 switch (Intrinsic) {
10863 case Intrinsic::ppc_qpx_qvstfda:
10866 case Intrinsic::ppc_qpx_qvstfsa:
10869 case Intrinsic::ppc_qpx_qvstfcda:
10872 case Intrinsic::ppc_qpx_qvstfcsa:
10880 Info.opc = ISD::INTRINSIC_VOID;
10882 Info.ptrVal = I.getArgOperand(1);
10884 Info.size = VT.getStoreSize();
10887 Info.readMem = false;
10888 Info.writeMem = true;
10898 /// getOptimalMemOpType - Returns the target specific optimal type for load
10899 /// and store operations as a result of memset, memcpy, and memmove
10900 /// lowering. If DstAlign is zero that means it's safe to destination
10901 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
10902 /// means there isn't a need to check it against alignment requirement,
10903 /// probably because the source does not need to be loaded. If 'IsMemset' is
10904 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
10905 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
10906 /// source is constant so it does not need to be loaded.
10907 /// It returns EVT::Other if the type should be determined using generic
10908 /// target-independent logic.
10909 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
10910 unsigned DstAlign, unsigned SrcAlign,
10911 bool IsMemset, bool ZeroMemset,
10913 MachineFunction &MF) const {
10914 if (Subtarget.isPPC64()) {
10921 /// \brief Returns true if it is beneficial to convert a load of a constant
10922 /// to just the constant itself.
10923 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10925 assert(Ty->isIntegerTy());
10927 unsigned BitSize = Ty->getPrimitiveSizeInBits();
10928 if (BitSize == 0 || BitSize > 64)
10933 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10934 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10936 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10937 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10938 return NumBits1 == 64 && NumBits2 == 32;
10941 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10942 if (!VT1.isInteger() || !VT2.isInteger())
10944 unsigned NumBits1 = VT1.getSizeInBits();
10945 unsigned NumBits2 = VT2.getSizeInBits();
10946 return NumBits1 == 64 && NumBits2 == 32;
10949 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10950 // Generally speaking, zexts are not free, but they are free when they can be
10951 // folded with other operations.
10952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
10953 EVT MemVT = LD->getMemoryVT();
10954 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
10955 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
10956 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
10957 LD->getExtensionType() == ISD::ZEXTLOAD))
10961 // FIXME: Add other cases...
10962 // - 32-bit shifts with a zext to i64
10963 // - zext after ctlz, bswap, etc.
10964 // - zext after and by a constant mask
10966 return TargetLowering::isZExtFree(Val, VT2);
10969 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
10970 assert(VT.isFloatingPoint());
10974 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10975 return isInt<16>(Imm) || isUInt<16>(Imm);
10978 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10979 return isInt<16>(Imm) || isUInt<16>(Imm);
10982 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10985 bool *Fast) const {
10986 if (DisablePPCUnaligned)
10989 // PowerPC supports unaligned memory access for simple non-vector types.
10990 // Although accessing unaligned addresses is not as efficient as accessing
10991 // aligned addresses, it is generally more efficient than manual expansion,
10992 // and generally only traps for software emulation when crossing page
10995 if (!VT.isSimple())
10998 if (VT.getSimpleVT().isVector()) {
10999 if (Subtarget.hasVSX()) {
11000 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11001 VT != MVT::v4f32 && VT != MVT::v4i32)
11008 if (VT == MVT::ppcf128)
11017 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11018 VT = VT.getScalarType();
11020 if (!VT.isSimple())
11023 switch (VT.getSimpleVT().SimpleTy) {
11035 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11036 // LR is a callee-save register, but we must treat it as clobbered by any call
11037 // site. Hence we include LR in the scratch registers, which are in turn added
11038 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11039 // to CTR, which is used by any indirect call.
11040 static const MCPhysReg ScratchRegs[] = {
11041 PPC::X12, PPC::LR8, PPC::CTR8, 0
11044 return ScratchRegs;
11048 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11049 EVT VT , unsigned DefinedValues) const {
11050 if (VT == MVT::v2i64)
11053 if (Subtarget.hasQPX()) {
11054 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11058 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11061 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11062 if (DisableILPPref || Subtarget.enableMachineScheduler())
11063 return TargetLowering::getSchedulingPreference(N);
11068 // Create a fast isel object.
11070 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11071 const TargetLibraryInfo *LibInfo) const {
11072 return PPC::createFastISel(FuncInfo, LibInfo);