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 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
97 if (Subtarget.useCRBits()) {
98 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
100 if (isPPC64 || Subtarget.hasFPCVT()) {
101 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
102 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
103 isPPC64 ? MVT::i64 : MVT::i32);
104 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
108 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
109 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
112 // PowerPC does not support direct load / store of condition registers
113 setOperationAction(ISD::LOAD, MVT::i1, Custom);
114 setOperationAction(ISD::STORE, MVT::i1, Custom);
116 // FIXME: Remove this once the ANDI glue bug is fixed:
118 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
120 for (MVT VT : MVT::integer_valuetypes()) {
121 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
122 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
123 setTruncStoreAction(VT, MVT::i1, Expand);
126 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
129 // This is used in the ppcf128->int sequence. Note it has different semantics
130 // from FP_ROUND: that rounds to nearest, this rounds to zero.
131 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
133 // We do not currently implement these libm ops for PowerPC.
134 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
141 // PowerPC has no SREM/UREM instructions
142 setOperationAction(ISD::SREM, MVT::i32, Expand);
143 setOperationAction(ISD::UREM, MVT::i32, Expand);
144 setOperationAction(ISD::SREM, MVT::i64, Expand);
145 setOperationAction(ISD::UREM, MVT::i64, Expand);
147 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
148 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
149 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
150 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
151 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
152 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
153 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
154 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
155 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
157 // We don't support sin/cos/sqrt/fmod/pow
158 setOperationAction(ISD::FSIN , MVT::f64, Expand);
159 setOperationAction(ISD::FCOS , MVT::f64, Expand);
160 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
161 setOperationAction(ISD::FREM , MVT::f64, Expand);
162 setOperationAction(ISD::FPOW , MVT::f64, Expand);
163 setOperationAction(ISD::FMA , MVT::f64, Legal);
164 setOperationAction(ISD::FSIN , MVT::f32, Expand);
165 setOperationAction(ISD::FCOS , MVT::f32, Expand);
166 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
167 setOperationAction(ISD::FREM , MVT::f32, Expand);
168 setOperationAction(ISD::FPOW , MVT::f32, Expand);
169 setOperationAction(ISD::FMA , MVT::f32, Legal);
171 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
173 // If we're enabling GP optimizations, use hardware square root
174 if (!Subtarget.hasFSQRT() &&
175 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
177 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
179 if (!Subtarget.hasFSQRT() &&
180 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
181 Subtarget.hasFRES()))
182 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
184 if (Subtarget.hasFCPSGN()) {
185 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
186 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
189 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
192 if (Subtarget.hasFPRND()) {
193 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
194 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
195 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
196 setOperationAction(ISD::FROUND, MVT::f64, Legal);
198 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
199 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
200 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
201 setOperationAction(ISD::FROUND, MVT::f32, Legal);
204 // PowerPC does not have BSWAP, CTPOP or CTTZ
205 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
206 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
207 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
208 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
209 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
214 if (Subtarget.hasPOPCNTD()) {
215 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
216 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
218 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
219 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
222 // PowerPC does not have ROTR
223 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
224 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
226 if (!Subtarget.useCRBits()) {
227 // PowerPC does not have Select
228 setOperationAction(ISD::SELECT, MVT::i32, Expand);
229 setOperationAction(ISD::SELECT, MVT::i64, Expand);
230 setOperationAction(ISD::SELECT, MVT::f32, Expand);
231 setOperationAction(ISD::SELECT, MVT::f64, Expand);
234 // PowerPC wants to turn select_cc of FP into fsel when possible.
235 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
236 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
238 // PowerPC wants to optimize integer setcc a bit
239 if (!Subtarget.useCRBits())
240 setOperationAction(ISD::SETCC, MVT::i32, Custom);
242 // PowerPC does not have BRCOND which requires SetCC
243 if (!Subtarget.useCRBits())
244 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
246 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
248 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
249 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
251 // PowerPC does not have [U|S]INT_TO_FP
252 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
253 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
256 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
257 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
258 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
260 // We cannot sextinreg(i1). Expand to shifts.
261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
263 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
264 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
265 // support continuation, user-level threading, and etc.. As a result, no
266 // other SjLj exception interfaces are implemented and please don't build
267 // your own exception handling based on them.
268 // LLVM/Clang supports zero-cost DWARF exception handling.
269 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
270 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
272 // We want to legalize GlobalAddress and ConstantPool nodes into the
273 // appropriate instructions to materialize the address.
274 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
275 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
276 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
277 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
278 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
280 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
281 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
282 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
283 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
286 setOperationAction(ISD::TRAP, MVT::Other, Legal);
288 // TRAMPOLINE is custom lowered.
289 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
290 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
292 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
293 setOperationAction(ISD::VASTART , MVT::Other, Custom);
295 if (Subtarget.isSVR4ABI()) {
297 // VAARG always uses double-word chunks, so promote anything smaller.
298 setOperationAction(ISD::VAARG, MVT::i1, Promote);
299 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
300 setOperationAction(ISD::VAARG, MVT::i8, Promote);
301 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
302 setOperationAction(ISD::VAARG, MVT::i16, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i32, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::Other, Expand);
308 // VAARG is custom lowered with the 32-bit SVR4 ABI.
309 setOperationAction(ISD::VAARG, MVT::Other, Custom);
310 setOperationAction(ISD::VAARG, MVT::i64, Custom);
313 setOperationAction(ISD::VAARG, MVT::Other, Expand);
315 if (Subtarget.isSVR4ABI() && !isPPC64)
316 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
317 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
319 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
321 // Use the default implementation.
322 setOperationAction(ISD::VAEND , MVT::Other, Expand);
323 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
324 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
328 // We want to custom lower some of our intrinsics.
329 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
331 // To handle counter-based loop conditions.
332 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
334 // Comparisons that require checking two conditions.
335 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
336 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
337 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
338 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
339 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
348 if (Subtarget.has64BitSupport()) {
349 // They also have instructions for converting between i64 and fp.
350 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
351 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
352 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
353 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
354 // This is just the low 32 bits of a (signed) fp->i64 conversion.
355 // We cannot do this with Promote because i64 is not a legal type.
356 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
358 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
359 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
361 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
362 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
365 // With the instructions enabled under FPCVT, we can do everything.
366 if (Subtarget.hasFPCVT()) {
367 if (Subtarget.has64BitSupport()) {
368 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
369 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
370 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
371 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
374 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
375 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
380 if (Subtarget.use64BitRegs()) {
381 // 64-bit PowerPC implementations can support i64 types directly
382 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
383 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
384 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
385 // 64-bit PowerPC wants to expand i128 shifts itself.
386 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
387 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
388 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
390 // 32-bit PowerPC wants to expand i64 shifts itself.
391 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
392 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
393 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
396 if (Subtarget.hasAltivec()) {
397 // First set operation action for all vector types to expand. Then we
398 // will selectively turn on ones that can be effectively codegen'd.
399 for (MVT VT : MVT::vector_valuetypes()) {
400 // add/sub are legal for all supported vector VT's.
401 setOperationAction(ISD::ADD , VT, Legal);
402 setOperationAction(ISD::SUB , VT, Legal);
404 // We promote all shuffles to v16i8.
405 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
406 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
408 // We promote all non-typed operations to v4i32.
409 setOperationAction(ISD::AND , VT, Promote);
410 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
411 setOperationAction(ISD::OR , VT, Promote);
412 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
413 setOperationAction(ISD::XOR , VT, Promote);
414 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
415 setOperationAction(ISD::LOAD , VT, Promote);
416 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
417 setOperationAction(ISD::SELECT, VT, Promote);
418 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
419 setOperationAction(ISD::STORE, VT, Promote);
420 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
422 // No other operations are legal.
423 setOperationAction(ISD::MUL , VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
428 setOperationAction(ISD::FDIV, VT, Expand);
429 setOperationAction(ISD::FREM, VT, Expand);
430 setOperationAction(ISD::FNEG, VT, Expand);
431 setOperationAction(ISD::FSQRT, VT, Expand);
432 setOperationAction(ISD::FLOG, VT, Expand);
433 setOperationAction(ISD::FLOG10, VT, Expand);
434 setOperationAction(ISD::FLOG2, VT, Expand);
435 setOperationAction(ISD::FEXP, VT, Expand);
436 setOperationAction(ISD::FEXP2, VT, Expand);
437 setOperationAction(ISD::FSIN, VT, Expand);
438 setOperationAction(ISD::FCOS, VT, Expand);
439 setOperationAction(ISD::FABS, VT, Expand);
440 setOperationAction(ISD::FPOWI, VT, Expand);
441 setOperationAction(ISD::FFLOOR, VT, Expand);
442 setOperationAction(ISD::FCEIL, VT, Expand);
443 setOperationAction(ISD::FTRUNC, VT, Expand);
444 setOperationAction(ISD::FRINT, VT, Expand);
445 setOperationAction(ISD::FNEARBYINT, VT, Expand);
446 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
447 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
448 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
449 setOperationAction(ISD::MULHU, VT, Expand);
450 setOperationAction(ISD::MULHS, VT, Expand);
451 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
452 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
453 setOperationAction(ISD::UDIVREM, VT, Expand);
454 setOperationAction(ISD::SDIVREM, VT, Expand);
455 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
456 setOperationAction(ISD::FPOW, VT, Expand);
457 setOperationAction(ISD::BSWAP, VT, Expand);
458 setOperationAction(ISD::CTPOP, VT, Expand);
459 setOperationAction(ISD::CTLZ, VT, Expand);
460 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
461 setOperationAction(ISD::CTTZ, VT, Expand);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
463 setOperationAction(ISD::VSELECT, VT, Expand);
464 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
466 for (MVT InnerVT : MVT::vector_valuetypes()) {
467 setTruncStoreAction(VT, InnerVT, Expand);
468 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
469 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
470 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
474 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
475 // with merges, splats, etc.
476 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
478 setOperationAction(ISD::AND , MVT::v4i32, Legal);
479 setOperationAction(ISD::OR , MVT::v4i32, Legal);
480 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
481 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
482 setOperationAction(ISD::SELECT, MVT::v4i32,
483 Subtarget.useCRBits() ? Legal : Expand);
484 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
485 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
486 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
487 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
488 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
489 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
490 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
491 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
492 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
494 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
495 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
496 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
497 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
499 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
500 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
502 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
503 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
504 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
507 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
508 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
509 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
511 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
512 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
514 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
515 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
516 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
517 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
519 // Altivec does not contain unordered floating-point compare instructions
520 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
521 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
522 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
523 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
525 if (Subtarget.hasVSX()) {
526 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
527 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
529 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
530 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
531 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
532 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
533 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
535 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
537 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
538 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
540 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
541 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
543 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
544 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
545 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
546 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
547 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
549 // Share the Altivec comparison restrictions.
550 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
551 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
552 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
553 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
555 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
556 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
558 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
560 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
562 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
563 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
565 // VSX v2i64 only supports non-arithmetic operations.
566 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
567 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
569 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
570 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
571 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
573 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
575 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
576 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
577 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
578 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
580 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
582 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
584 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
585 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
587 // Vector operation legalization checks the result type of
588 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
589 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
590 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
591 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
592 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
594 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
598 if (Subtarget.has64BitSupport())
599 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
601 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
604 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
605 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
608 setBooleanContents(ZeroOrOneBooleanContent);
609 // Altivec instructions set fields to all zeros or all ones.
610 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
613 // These libcalls are not available in 32-bit.
614 setLibcallName(RTLIB::SHL_I128, nullptr);
615 setLibcallName(RTLIB::SRL_I128, nullptr);
616 setLibcallName(RTLIB::SRA_I128, nullptr);
620 setStackPointerRegisterToSaveRestore(PPC::X1);
621 setExceptionPointerRegister(PPC::X3);
622 setExceptionSelectorRegister(PPC::X4);
624 setStackPointerRegisterToSaveRestore(PPC::R1);
625 setExceptionPointerRegister(PPC::R3);
626 setExceptionSelectorRegister(PPC::R4);
629 // We have target-specific dag combine patterns for the following nodes:
630 setTargetDAGCombine(ISD::SINT_TO_FP);
631 if (Subtarget.hasFPCVT())
632 setTargetDAGCombine(ISD::UINT_TO_FP);
633 setTargetDAGCombine(ISD::LOAD);
634 setTargetDAGCombine(ISD::STORE);
635 setTargetDAGCombine(ISD::BR_CC);
636 if (Subtarget.useCRBits())
637 setTargetDAGCombine(ISD::BRCOND);
638 setTargetDAGCombine(ISD::BSWAP);
639 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
640 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
641 setTargetDAGCombine(ISD::INTRINSIC_VOID);
643 setTargetDAGCombine(ISD::SIGN_EXTEND);
644 setTargetDAGCombine(ISD::ZERO_EXTEND);
645 setTargetDAGCombine(ISD::ANY_EXTEND);
647 if (Subtarget.useCRBits()) {
648 setTargetDAGCombine(ISD::TRUNCATE);
649 setTargetDAGCombine(ISD::SETCC);
650 setTargetDAGCombine(ISD::SELECT_CC);
653 // Use reciprocal estimates.
654 if (TM.Options.UnsafeFPMath) {
655 setTargetDAGCombine(ISD::FDIV);
656 setTargetDAGCombine(ISD::FSQRT);
659 // Darwin long double math library functions have $LDBL128 appended.
660 if (Subtarget.isDarwin()) {
661 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
662 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
663 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
664 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
665 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
666 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
667 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
668 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
669 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
670 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
673 // With 32 condition bits, we don't need to sink (and duplicate) compares
674 // aggressively in CodeGenPrep.
675 if (Subtarget.useCRBits())
676 setHasMultipleConditionRegisters();
678 setMinFunctionAlignment(2);
679 if (Subtarget.isDarwin())
680 setPrefFunctionAlignment(4);
682 switch (Subtarget.getDarwinDirective()) {
686 case PPC::DIR_E500mc:
695 setPrefFunctionAlignment(4);
696 setPrefLoopAlignment(4);
700 setInsertFencesForAtomic(true);
702 if (Subtarget.enableMachineScheduler())
703 setSchedulingPreference(Sched::Source);
705 setSchedulingPreference(Sched::Hybrid);
707 computeRegisterProperties();
709 // The Freescale cores do better with aggressive inlining of memcpy and
710 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
711 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
712 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
713 MaxStoresPerMemset = 32;
714 MaxStoresPerMemsetOptSize = 16;
715 MaxStoresPerMemcpy = 32;
716 MaxStoresPerMemcpyOptSize = 8;
717 MaxStoresPerMemmove = 32;
718 MaxStoresPerMemmoveOptSize = 8;
722 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
723 /// the desired ByVal argument alignment.
724 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
725 unsigned MaxMaxAlign) {
726 if (MaxAlign == MaxMaxAlign)
728 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
729 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
731 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
733 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
734 unsigned EltAlign = 0;
735 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
736 if (EltAlign > MaxAlign)
738 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
739 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
740 unsigned EltAlign = 0;
741 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
742 if (EltAlign > MaxAlign)
744 if (MaxAlign == MaxMaxAlign)
750 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
751 /// function arguments in the caller parameter area.
752 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
753 // Darwin passes everything on 4 byte boundary.
754 if (Subtarget.isDarwin())
757 // 16byte and wider vectors are passed on 16byte boundary.
758 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
759 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
760 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
761 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
765 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
767 default: return nullptr;
768 case PPCISD::FSEL: return "PPCISD::FSEL";
769 case PPCISD::FCFID: return "PPCISD::FCFID";
770 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
771 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
772 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
773 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
774 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
775 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
776 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
777 case PPCISD::FRE: return "PPCISD::FRE";
778 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
779 case PPCISD::STFIWX: return "PPCISD::STFIWX";
780 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
781 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
782 case PPCISD::VPERM: return "PPCISD::VPERM";
783 case PPCISD::CMPB: return "PPCISD::CMPB";
784 case PPCISD::Hi: return "PPCISD::Hi";
785 case PPCISD::Lo: return "PPCISD::Lo";
786 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
787 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
788 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
789 case PPCISD::SRL: return "PPCISD::SRL";
790 case PPCISD::SRA: return "PPCISD::SRA";
791 case PPCISD::SHL: return "PPCISD::SHL";
792 case PPCISD::CALL: return "PPCISD::CALL";
793 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
794 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS";
795 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS";
796 case PPCISD::MTCTR: return "PPCISD::MTCTR";
797 case PPCISD::BCTRL: return "PPCISD::BCTRL";
798 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
799 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
800 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
801 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
802 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
803 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
804 case PPCISD::VCMP: return "PPCISD::VCMP";
805 case PPCISD::VCMPo: return "PPCISD::VCMPo";
806 case PPCISD::LBRX: return "PPCISD::LBRX";
807 case PPCISD::STBRX: return "PPCISD::STBRX";
808 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
809 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
810 case PPCISD::LARX: return "PPCISD::LARX";
811 case PPCISD::STCX: return "PPCISD::STCX";
812 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
813 case PPCISD::BDNZ: return "PPCISD::BDNZ";
814 case PPCISD::BDZ: return "PPCISD::BDZ";
815 case PPCISD::MFFS: return "PPCISD::MFFS";
816 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
817 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
818 case PPCISD::CR6SET: return "PPCISD::CR6SET";
819 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
820 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
821 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
822 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
823 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
824 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
825 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
826 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
827 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
828 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
829 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
830 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
831 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
832 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
833 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
834 case PPCISD::SC: return "PPCISD::SC";
838 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
840 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
841 return VT.changeVectorElementTypeToInteger();
844 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
845 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
849 //===----------------------------------------------------------------------===//
850 // Node matching predicates, for use by the tblgen matching code.
851 //===----------------------------------------------------------------------===//
853 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
854 static bool isFloatingPointZero(SDValue Op) {
855 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
856 return CFP->getValueAPF().isZero();
857 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
858 // Maybe this has already been legalized into the constant pool?
859 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
860 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
861 return CFP->getValueAPF().isZero();
866 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
867 /// true if Op is undef or if it matches the specified value.
868 static bool isConstantOrUndef(int Op, int Val) {
869 return Op < 0 || Op == Val;
872 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
873 /// VPKUHUM instruction.
874 /// The ShuffleKind distinguishes between big-endian operations with
875 /// two different inputs (0), either-endian operations with two identical
876 /// inputs (1), and little-endian operantion with two different inputs (2).
877 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
878 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
880 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
881 if (ShuffleKind == 0) {
884 for (unsigned i = 0; i != 16; ++i)
885 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
887 } else if (ShuffleKind == 2) {
890 for (unsigned i = 0; i != 16; ++i)
891 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
893 } else if (ShuffleKind == 1) {
894 unsigned j = IsLE ? 0 : 1;
895 for (unsigned i = 0; i != 8; ++i)
896 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
897 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
903 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
904 /// VPKUWUM instruction.
905 /// The ShuffleKind distinguishes between big-endian operations with
906 /// two different inputs (0), either-endian operations with two identical
907 /// inputs (1), and little-endian operantion with two different inputs (2).
908 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
909 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
911 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
912 if (ShuffleKind == 0) {
915 for (unsigned i = 0; i != 16; i += 2)
916 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
917 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
919 } else if (ShuffleKind == 2) {
922 for (unsigned i = 0; i != 16; i += 2)
923 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
924 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
926 } else if (ShuffleKind == 1) {
927 unsigned j = IsLE ? 0 : 2;
928 for (unsigned i = 0; i != 8; i += 2)
929 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
930 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
931 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
932 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
938 /// isVMerge - Common function, used to match vmrg* shuffles.
940 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
941 unsigned LHSStart, unsigned RHSStart) {
942 if (N->getValueType(0) != MVT::v16i8)
944 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
945 "Unsupported merge size!");
947 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
948 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
949 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
950 LHSStart+j+i*UnitSize) ||
951 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
952 RHSStart+j+i*UnitSize))
958 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
959 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
960 /// The ShuffleKind distinguishes between big-endian merges with two
961 /// different inputs (0), either-endian merges with two identical inputs (1),
962 /// and little-endian merges with two different inputs (2). For the latter,
963 /// the input operands are swapped (see PPCInstrAltivec.td).
964 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
965 unsigned ShuffleKind, SelectionDAG &DAG) {
966 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
967 if (ShuffleKind == 1) // unary
968 return isVMerge(N, UnitSize, 0, 0);
969 else if (ShuffleKind == 2) // swapped
970 return isVMerge(N, UnitSize, 0, 16);
974 if (ShuffleKind == 1) // unary
975 return isVMerge(N, UnitSize, 8, 8);
976 else if (ShuffleKind == 0) // normal
977 return isVMerge(N, UnitSize, 8, 24);
983 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
984 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
985 /// The ShuffleKind distinguishes between big-endian merges with two
986 /// different inputs (0), either-endian merges with two identical inputs (1),
987 /// and little-endian merges with two different inputs (2). For the latter,
988 /// the input operands are swapped (see PPCInstrAltivec.td).
989 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
990 unsigned ShuffleKind, SelectionDAG &DAG) {
991 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
992 if (ShuffleKind == 1) // unary
993 return isVMerge(N, UnitSize, 8, 8);
994 else if (ShuffleKind == 2) // swapped
995 return isVMerge(N, UnitSize, 8, 24);
999 if (ShuffleKind == 1) // unary
1000 return isVMerge(N, UnitSize, 0, 0);
1001 else if (ShuffleKind == 0) // normal
1002 return isVMerge(N, UnitSize, 0, 16);
1009 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1010 /// amount, otherwise return -1.
1011 /// The ShuffleKind distinguishes between big-endian operations with two
1012 /// different inputs (0), either-endian operations with two identical inputs
1013 /// (1), and little-endian operations with two different inputs (2). For the
1014 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1015 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1016 SelectionDAG &DAG) {
1017 if (N->getValueType(0) != MVT::v16i8)
1020 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1022 // Find the first non-undef value in the shuffle mask.
1024 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1027 if (i == 16) return -1; // all undef.
1029 // Otherwise, check to see if the rest of the elements are consecutively
1030 // numbered from this value.
1031 unsigned ShiftAmt = SVOp->getMaskElt(i);
1032 if (ShiftAmt < i) return -1;
1035 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1037 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1038 // Check the rest of the elements to see if they are consecutive.
1039 for (++i; i != 16; ++i)
1040 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1042 } else if (ShuffleKind == 1) {
1043 // Check the rest of the elements to see if they are consecutive.
1044 for (++i; i != 16; ++i)
1045 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1050 if (ShuffleKind == 2 && isLE)
1051 ShiftAmt = 16 - ShiftAmt;
1056 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1057 /// specifies a splat of a single element that is suitable for input to
1058 /// VSPLTB/VSPLTH/VSPLTW.
1059 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1060 assert(N->getValueType(0) == MVT::v16i8 &&
1061 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1063 // This is a splat operation if each element of the permute is the same, and
1064 // if the value doesn't reference the second vector.
1065 unsigned ElementBase = N->getMaskElt(0);
1067 // FIXME: Handle UNDEF elements too!
1068 if (ElementBase >= 16)
1071 // Check that the indices are consecutive, in the case of a multi-byte element
1072 // splatted with a v16i8 mask.
1073 for (unsigned i = 1; i != EltSize; ++i)
1074 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1077 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1078 if (N->getMaskElt(i) < 0) continue;
1079 for (unsigned j = 0; j != EltSize; ++j)
1080 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1086 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1088 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1089 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1091 APInt APVal, APUndef;
1095 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1096 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1097 return CFP->getValueAPF().isNegZero();
1102 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1103 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1104 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1105 SelectionDAG &DAG) {
1106 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1107 assert(isSplatShuffleMask(SVOp, EltSize));
1108 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1109 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1111 return SVOp->getMaskElt(0) / EltSize;
1114 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1115 /// by using a vspltis[bhw] instruction of the specified element size, return
1116 /// the constant being splatted. The ByteSize field indicates the number of
1117 /// bytes of each element [124] -> [bhw].
1118 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1119 SDValue OpVal(nullptr, 0);
1121 // If ByteSize of the splat is bigger than the element size of the
1122 // build_vector, then we have a case where we are checking for a splat where
1123 // multiple elements of the buildvector are folded together into a single
1124 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1125 unsigned EltSize = 16/N->getNumOperands();
1126 if (EltSize < ByteSize) {
1127 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1128 SDValue UniquedVals[4];
1129 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1131 // See if all of the elements in the buildvector agree across.
1132 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1133 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1134 // If the element isn't a constant, bail fully out.
1135 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1138 if (!UniquedVals[i&(Multiple-1)].getNode())
1139 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1140 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1141 return SDValue(); // no match.
1144 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1145 // either constant or undef values that are identical for each chunk. See
1146 // if these chunks can form into a larger vspltis*.
1148 // Check to see if all of the leading entries are either 0 or -1. If
1149 // neither, then this won't fit into the immediate field.
1150 bool LeadingZero = true;
1151 bool LeadingOnes = true;
1152 for (unsigned i = 0; i != Multiple-1; ++i) {
1153 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1155 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1156 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1158 // Finally, check the least significant entry.
1160 if (!UniquedVals[Multiple-1].getNode())
1161 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1162 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1164 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1167 if (!UniquedVals[Multiple-1].getNode())
1168 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1169 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1170 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1171 return DAG.getTargetConstant(Val, MVT::i32);
1177 // Check to see if this buildvec has a single non-undef value in its elements.
1178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1179 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1180 if (!OpVal.getNode())
1181 OpVal = N->getOperand(i);
1182 else if (OpVal != N->getOperand(i))
1186 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1188 unsigned ValSizeInBytes = EltSize;
1190 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1191 Value = CN->getZExtValue();
1192 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1193 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1194 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1197 // If the splat value is larger than the element value, then we can never do
1198 // this splat. The only case that we could fit the replicated bits into our
1199 // immediate field for would be zero, and we prefer to use vxor for it.
1200 if (ValSizeInBytes < ByteSize) return SDValue();
1202 // If the element value is larger than the splat value, cut it in half and
1203 // check to see if the two halves are equal. Continue doing this until we
1204 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1205 while (ValSizeInBytes > ByteSize) {
1206 ValSizeInBytes >>= 1;
1208 // If the top half equals the bottom half, we're still ok.
1209 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1210 (Value & ((1 << (8*ValSizeInBytes))-1)))
1214 // Properly sign extend the value.
1215 int MaskVal = SignExtend32(Value, ByteSize * 8);
1217 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1218 if (MaskVal == 0) return SDValue();
1220 // Finally, if this value fits in a 5 bit sext field, return it
1221 if (SignExtend32<5>(MaskVal) == MaskVal)
1222 return DAG.getTargetConstant(MaskVal, MVT::i32);
1226 //===----------------------------------------------------------------------===//
1227 // Addressing Mode Selection
1228 //===----------------------------------------------------------------------===//
1230 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1231 /// or 64-bit immediate, and if the value can be accurately represented as a
1232 /// sign extension from a 16-bit value. If so, this returns true and the
1234 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1235 if (!isa<ConstantSDNode>(N))
1238 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1239 if (N->getValueType(0) == MVT::i32)
1240 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1242 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1244 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1245 return isIntS16Immediate(Op.getNode(), Imm);
1249 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1250 /// can be represented as an indexed [r+r] operation. Returns false if it
1251 /// can be more efficiently represented with [r+imm].
1252 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1254 SelectionDAG &DAG) const {
1256 if (N.getOpcode() == ISD::ADD) {
1257 if (isIntS16Immediate(N.getOperand(1), imm))
1258 return false; // r+i
1259 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1260 return false; // r+i
1262 Base = N.getOperand(0);
1263 Index = N.getOperand(1);
1265 } else if (N.getOpcode() == ISD::OR) {
1266 if (isIntS16Immediate(N.getOperand(1), imm))
1267 return false; // r+i can fold it if we can.
1269 // If this is an or of disjoint bitfields, we can codegen this as an add
1270 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1272 APInt LHSKnownZero, LHSKnownOne;
1273 APInt RHSKnownZero, RHSKnownOne;
1274 DAG.computeKnownBits(N.getOperand(0),
1275 LHSKnownZero, LHSKnownOne);
1277 if (LHSKnownZero.getBoolValue()) {
1278 DAG.computeKnownBits(N.getOperand(1),
1279 RHSKnownZero, RHSKnownOne);
1280 // If all of the bits are known zero on the LHS or RHS, the add won't
1282 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1283 Base = N.getOperand(0);
1284 Index = N.getOperand(1);
1293 // If we happen to be doing an i64 load or store into a stack slot that has
1294 // less than a 4-byte alignment, then the frame-index elimination may need to
1295 // use an indexed load or store instruction (because the offset may not be a
1296 // multiple of 4). The extra register needed to hold the offset comes from the
1297 // register scavenger, and it is possible that the scavenger will need to use
1298 // an emergency spill slot. As a result, we need to make sure that a spill slot
1299 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1301 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1302 // FIXME: This does not handle the LWA case.
1306 // NOTE: We'll exclude negative FIs here, which come from argument
1307 // lowering, because there are no known test cases triggering this problem
1308 // using packed structures (or similar). We can remove this exclusion if
1309 // we find such a test case. The reason why this is so test-case driven is
1310 // because this entire 'fixup' is only to prevent crashes (from the
1311 // register scavenger) on not-really-valid inputs. For example, if we have:
1313 // %b = bitcast i1* %a to i64*
1314 // store i64* a, i64 b
1315 // then the store should really be marked as 'align 1', but is not. If it
1316 // were marked as 'align 1' then the indexed form would have been
1317 // instruction-selected initially, and the problem this 'fixup' is preventing
1318 // won't happen regardless.
1322 MachineFunction &MF = DAG.getMachineFunction();
1323 MachineFrameInfo *MFI = MF.getFrameInfo();
1325 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1329 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1330 FuncInfo->setHasNonRISpills();
1333 /// Returns true if the address N can be represented by a base register plus
1334 /// a signed 16-bit displacement [r+imm], and if it is not better
1335 /// represented as reg+reg. If Aligned is true, only accept displacements
1336 /// suitable for STD and friends, i.e. multiples of 4.
1337 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1340 bool Aligned) const {
1341 // FIXME dl should come from parent load or store, not from address
1343 // If this can be more profitably realized as r+r, fail.
1344 if (SelectAddressRegReg(N, Disp, Base, DAG))
1347 if (N.getOpcode() == ISD::ADD) {
1349 if (isIntS16Immediate(N.getOperand(1), imm) &&
1350 (!Aligned || (imm & 3) == 0)) {
1351 Disp = DAG.getTargetConstant(imm, N.getValueType());
1352 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1353 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1354 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1356 Base = N.getOperand(0);
1358 return true; // [r+i]
1359 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1360 // Match LOAD (ADD (X, Lo(G))).
1361 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1362 && "Cannot handle constant offsets yet!");
1363 Disp = N.getOperand(1).getOperand(0); // The global address.
1364 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1365 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1366 Disp.getOpcode() == ISD::TargetConstantPool ||
1367 Disp.getOpcode() == ISD::TargetJumpTable);
1368 Base = N.getOperand(0);
1369 return true; // [&g+r]
1371 } else if (N.getOpcode() == ISD::OR) {
1373 if (isIntS16Immediate(N.getOperand(1), imm) &&
1374 (!Aligned || (imm & 3) == 0)) {
1375 // If this is an or of disjoint bitfields, we can codegen this as an add
1376 // (for better address arithmetic) if the LHS and RHS of the OR are
1377 // provably disjoint.
1378 APInt LHSKnownZero, LHSKnownOne;
1379 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1381 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1382 // If all of the bits are known zero on the LHS or RHS, the add won't
1384 if (FrameIndexSDNode *FI =
1385 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1386 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1387 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1389 Base = N.getOperand(0);
1391 Disp = DAG.getTargetConstant(imm, N.getValueType());
1395 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1396 // Loading from a constant address.
1398 // If this address fits entirely in a 16-bit sext immediate field, codegen
1401 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1402 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1403 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1404 CN->getValueType(0));
1408 // Handle 32-bit sext immediates with LIS + addr mode.
1409 if ((CN->getValueType(0) == MVT::i32 ||
1410 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1411 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1412 int Addr = (int)CN->getZExtValue();
1414 // Otherwise, break this down into an LIS + disp.
1415 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1417 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1418 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1419 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1424 Disp = DAG.getTargetConstant(0, getPointerTy());
1425 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1426 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1427 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1430 return true; // [r+0]
1433 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1434 /// represented as an indexed [r+r] operation.
1435 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1437 SelectionDAG &DAG) const {
1438 // Check to see if we can easily represent this as an [r+r] address. This
1439 // will fail if it thinks that the address is more profitably represented as
1440 // reg+imm, e.g. where imm = 0.
1441 if (SelectAddressRegReg(N, Base, Index, DAG))
1444 // If the operand is an addition, always emit this as [r+r], since this is
1445 // better (for code size, and execution, as the memop does the add for free)
1446 // than emitting an explicit add.
1447 if (N.getOpcode() == ISD::ADD) {
1448 Base = N.getOperand(0);
1449 Index = N.getOperand(1);
1453 // Otherwise, do it the hard way, using R0 as the base register.
1454 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1460 /// getPreIndexedAddressParts - returns true by value, base pointer and
1461 /// offset pointer and addressing mode by reference if the node's address
1462 /// can be legally represented as pre-indexed load / store address.
1463 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1465 ISD::MemIndexedMode &AM,
1466 SelectionDAG &DAG) const {
1467 if (DisablePPCPreinc) return false;
1473 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1474 Ptr = LD->getBasePtr();
1475 VT = LD->getMemoryVT();
1476 Alignment = LD->getAlignment();
1477 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1478 Ptr = ST->getBasePtr();
1479 VT = ST->getMemoryVT();
1480 Alignment = ST->getAlignment();
1485 // PowerPC doesn't have preinc load/store instructions for vectors.
1489 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1491 // Common code will reject creating a pre-inc form if the base pointer
1492 // is a frame index, or if N is a store and the base pointer is either
1493 // the same as or a predecessor of the value being stored. Check for
1494 // those situations here, and try with swapped Base/Offset instead.
1497 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1500 SDValue Val = cast<StoreSDNode>(N)->getValue();
1501 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1506 std::swap(Base, Offset);
1512 // LDU/STU can only handle immediates that are a multiple of 4.
1513 if (VT != MVT::i64) {
1514 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1517 // LDU/STU need an address with at least 4-byte alignment.
1521 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1525 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1526 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1527 // sext i32 to i64 when addr mode is r+i.
1528 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1529 LD->getExtensionType() == ISD::SEXTLOAD &&
1530 isa<ConstantSDNode>(Offset))
1538 //===----------------------------------------------------------------------===//
1539 // LowerOperation implementation
1540 //===----------------------------------------------------------------------===//
1542 /// GetLabelAccessInfo - Return true if we should reference labels using a
1543 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1544 static bool GetLabelAccessInfo(const TargetMachine &TM,
1545 const PPCSubtarget &Subtarget,
1546 unsigned &HiOpFlags, unsigned &LoOpFlags,
1547 const GlobalValue *GV = nullptr) {
1548 HiOpFlags = PPCII::MO_HA;
1549 LoOpFlags = PPCII::MO_LO;
1551 // Don't use the pic base if not in PIC relocation model.
1552 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1555 HiOpFlags |= PPCII::MO_PIC_FLAG;
1556 LoOpFlags |= PPCII::MO_PIC_FLAG;
1559 // If this is a reference to a global value that requires a non-lazy-ptr, make
1560 // sure that instruction lowering adds it.
1561 if (GV && Subtarget.hasLazyResolverStub(GV, TM)) {
1562 HiOpFlags |= PPCII::MO_NLP_FLAG;
1563 LoOpFlags |= PPCII::MO_NLP_FLAG;
1565 if (GV->hasHiddenVisibility()) {
1566 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1567 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1574 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1575 SelectionDAG &DAG) {
1576 EVT PtrVT = HiPart.getValueType();
1577 SDValue Zero = DAG.getConstant(0, PtrVT);
1580 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1581 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1583 // With PIC, the first instruction is actually "GR+hi(&G)".
1585 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1586 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1588 // Generate non-pic code that has direct accesses to the constant pool.
1589 // The address of the global is just (hi(&g)+lo(&g)).
1590 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1593 static void setUsesTOCBasePtr(MachineFunction &MF) {
1594 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1595 FuncInfo->setUsesTOCBasePtr();
1598 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1599 setUsesTOCBasePtr(DAG.getMachineFunction());
1602 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1603 SelectionDAG &DAG) const {
1604 EVT PtrVT = Op.getValueType();
1605 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1606 const Constant *C = CP->getConstVal();
1608 // 64-bit SVR4 ABI code is always position-independent.
1609 // The actual address of the GlobalValue is stored in the TOC.
1610 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1611 setUsesTOCBasePtr(DAG);
1612 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1613 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1614 DAG.getRegister(PPC::X2, MVT::i64));
1617 unsigned MOHiFlag, MOLoFlag;
1619 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1621 if (isPIC && Subtarget.isSVR4ABI()) {
1622 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1623 PPCII::MO_PIC_FLAG);
1625 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1626 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1630 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1632 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1633 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1636 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1637 EVT PtrVT = Op.getValueType();
1638 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1640 // 64-bit SVR4 ABI code is always position-independent.
1641 // The actual address of the GlobalValue is stored in the TOC.
1642 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1643 setUsesTOCBasePtr(DAG);
1644 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1645 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1646 DAG.getRegister(PPC::X2, MVT::i64));
1649 unsigned MOHiFlag, MOLoFlag;
1651 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1653 if (isPIC && Subtarget.isSVR4ABI()) {
1654 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1655 PPCII::MO_PIC_FLAG);
1657 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1658 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1661 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1662 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1663 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1666 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1667 SelectionDAG &DAG) const {
1668 EVT PtrVT = Op.getValueType();
1669 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1670 const BlockAddress *BA = BASDN->getBlockAddress();
1672 // 64-bit SVR4 ABI code is always position-independent.
1673 // The actual BlockAddress is stored in the TOC.
1674 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1675 setUsesTOCBasePtr(DAG);
1676 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1677 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1678 DAG.getRegister(PPC::X2, MVT::i64));
1681 unsigned MOHiFlag, MOLoFlag;
1683 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1684 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1685 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1686 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1689 // Generate a call to __tls_get_addr for the given GOT entry Op.
1690 std::pair<SDValue,SDValue>
1691 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1692 SelectionDAG &DAG) const {
1694 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1695 TargetLowering::ArgListTy Args;
1696 TargetLowering::ArgListEntry Entry;
1698 Entry.Ty = IntPtrTy;
1699 Args.push_back(Entry);
1701 TargetLowering::CallLoweringInfo CLI(DAG);
1702 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1703 .setCallee(CallingConv::C, IntPtrTy,
1704 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1705 std::move(Args), 0);
1707 return LowerCallTo(CLI);
1710 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1711 SelectionDAG &DAG) const {
1713 // FIXME: TLS addresses currently use medium model code sequences,
1714 // which is the most useful form. Eventually support for small and
1715 // large models could be added if users need it, at the cost of
1716 // additional complexity.
1717 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1719 const GlobalValue *GV = GA->getGlobal();
1720 EVT PtrVT = getPointerTy();
1721 bool is64bit = Subtarget.isPPC64();
1722 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1723 PICLevel::Level picLevel = M->getPICLevel();
1725 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1727 if (Model == TLSModel::LocalExec) {
1728 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1729 PPCII::MO_TPREL_HA);
1730 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1731 PPCII::MO_TPREL_LO);
1732 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1733 is64bit ? MVT::i64 : MVT::i32);
1734 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1735 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1738 if (Model == TLSModel::InitialExec) {
1739 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1740 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1744 setUsesTOCBasePtr(DAG);
1745 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1746 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1747 PtrVT, GOTReg, TGA);
1749 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1750 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1751 PtrVT, TGA, GOTPtr);
1752 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1755 if (Model == TLSModel::GeneralDynamic) {
1756 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1760 setUsesTOCBasePtr(DAG);
1761 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1762 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1765 if (picLevel == PICLevel::Small)
1766 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1768 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1770 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1772 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1773 return CallResult.first;
1776 if (Model == TLSModel::LocalDynamic) {
1777 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1781 setUsesTOCBasePtr(DAG);
1782 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1783 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1786 if (picLevel == PICLevel::Small)
1787 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1789 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1791 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1793 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1794 SDValue TLSAddr = CallResult.first;
1795 SDValue Chain = CallResult.second;
1796 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1797 Chain, TLSAddr, TGA);
1798 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1801 llvm_unreachable("Unknown TLS model!");
1804 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1805 SelectionDAG &DAG) const {
1806 EVT PtrVT = Op.getValueType();
1807 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1809 const GlobalValue *GV = GSDN->getGlobal();
1811 // 64-bit SVR4 ABI code is always position-independent.
1812 // The actual address of the GlobalValue is stored in the TOC.
1813 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1814 setUsesTOCBasePtr(DAG);
1815 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1816 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1817 DAG.getRegister(PPC::X2, MVT::i64));
1820 unsigned MOHiFlag, MOLoFlag;
1822 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
1824 if (isPIC && Subtarget.isSVR4ABI()) {
1825 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1827 PPCII::MO_PIC_FLAG);
1828 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1829 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1833 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1835 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1837 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1839 // If the global reference is actually to a non-lazy-pointer, we have to do an
1840 // extra load to get the address of the global.
1841 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1842 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1843 false, false, false, 0);
1847 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1848 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1851 if (Op.getValueType() == MVT::v2i64) {
1852 // When the operands themselves are v2i64 values, we need to do something
1853 // special because VSX has no underlying comparison operations for these.
1854 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1855 // Equality can be handled by casting to the legal type for Altivec
1856 // comparisons, everything else needs to be expanded.
1857 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1858 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1859 DAG.getSetCC(dl, MVT::v4i32,
1860 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1861 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1868 // We handle most of these in the usual way.
1872 // If we're comparing for equality to zero, expose the fact that this is
1873 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1874 // fold the new nodes.
1875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1876 if (C->isNullValue() && CC == ISD::SETEQ) {
1877 EVT VT = Op.getOperand(0).getValueType();
1878 SDValue Zext = Op.getOperand(0);
1879 if (VT.bitsLT(MVT::i32)) {
1881 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1883 unsigned Log2b = Log2_32(VT.getSizeInBits());
1884 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1885 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1886 DAG.getConstant(Log2b, MVT::i32));
1887 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1889 // Leave comparisons against 0 and -1 alone for now, since they're usually
1890 // optimized. FIXME: revisit this when we can custom lower all setcc
1892 if (C->isAllOnesValue() || C->isNullValue())
1896 // If we have an integer seteq/setne, turn it into a compare against zero
1897 // by xor'ing the rhs with the lhs, which is faster than setting a
1898 // condition register, reading it back out, and masking the correct bit. The
1899 // normal approach here uses sub to do this instead of xor. Using xor exposes
1900 // the result to other bit-twiddling opportunities.
1901 EVT LHSVT = Op.getOperand(0).getValueType();
1902 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1903 EVT VT = Op.getValueType();
1904 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1906 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1911 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1912 const PPCSubtarget &Subtarget) const {
1913 SDNode *Node = Op.getNode();
1914 EVT VT = Node->getValueType(0);
1915 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1916 SDValue InChain = Node->getOperand(0);
1917 SDValue VAListPtr = Node->getOperand(1);
1918 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1921 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1924 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1925 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1926 false, false, false, 0);
1927 InChain = GprIndex.getValue(1);
1929 if (VT == MVT::i64) {
1930 // Check if GprIndex is even
1931 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1932 DAG.getConstant(1, MVT::i32));
1933 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1934 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1935 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1936 DAG.getConstant(1, MVT::i32));
1937 // Align GprIndex to be even if it isn't
1938 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1942 // fpr index is 1 byte after gpr
1943 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1944 DAG.getConstant(1, MVT::i32));
1947 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1948 FprPtr, MachinePointerInfo(SV), MVT::i8,
1949 false, false, false, 0);
1950 InChain = FprIndex.getValue(1);
1952 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1953 DAG.getConstant(8, MVT::i32));
1955 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1956 DAG.getConstant(4, MVT::i32));
1959 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1960 MachinePointerInfo(), false, false,
1962 InChain = OverflowArea.getValue(1);
1964 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1965 MachinePointerInfo(), false, false,
1967 InChain = RegSaveArea.getValue(1);
1969 // select overflow_area if index > 8
1970 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1971 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1973 // adjustment constant gpr_index * 4/8
1974 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1975 VT.isInteger() ? GprIndex : FprIndex,
1976 DAG.getConstant(VT.isInteger() ? 4 : 8,
1979 // OurReg = RegSaveArea + RegConstant
1980 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1983 // Floating types are 32 bytes into RegSaveArea
1984 if (VT.isFloatingPoint())
1985 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1986 DAG.getConstant(32, MVT::i32));
1988 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1989 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1990 VT.isInteger() ? GprIndex : FprIndex,
1991 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1994 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1995 VT.isInteger() ? VAListPtr : FprPtr,
1996 MachinePointerInfo(SV),
1997 MVT::i8, false, false, 0);
1999 // determine if we should load from reg_save_area or overflow_area
2000 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2002 // increase overflow_area by 4/8 if gpr/fpr > 8
2003 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2004 DAG.getConstant(VT.isInteger() ? 4 : 8,
2007 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2010 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2012 MachinePointerInfo(),
2013 MVT::i32, false, false, 0);
2015 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2016 false, false, false, 0);
2019 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2020 const PPCSubtarget &Subtarget) const {
2021 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2023 // We have to copy the entire va_list struct:
2024 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2025 return DAG.getMemcpy(Op.getOperand(0), Op,
2026 Op.getOperand(1), Op.getOperand(2),
2027 DAG.getConstant(12, MVT::i32), 8, false, true,
2028 MachinePointerInfo(), MachinePointerInfo());
2031 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2032 SelectionDAG &DAG) const {
2033 return Op.getOperand(0);
2036 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2037 SelectionDAG &DAG) const {
2038 SDValue Chain = Op.getOperand(0);
2039 SDValue Trmp = Op.getOperand(1); // trampoline
2040 SDValue FPtr = Op.getOperand(2); // nested function
2041 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2044 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2045 bool isPPC64 = (PtrVT == MVT::i64);
2047 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2050 TargetLowering::ArgListTy Args;
2051 TargetLowering::ArgListEntry Entry;
2053 Entry.Ty = IntPtrTy;
2054 Entry.Node = Trmp; Args.push_back(Entry);
2056 // TrampSize == (isPPC64 ? 48 : 40);
2057 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2058 isPPC64 ? MVT::i64 : MVT::i32);
2059 Args.push_back(Entry);
2061 Entry.Node = FPtr; Args.push_back(Entry);
2062 Entry.Node = Nest; Args.push_back(Entry);
2064 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2065 TargetLowering::CallLoweringInfo CLI(DAG);
2066 CLI.setDebugLoc(dl).setChain(Chain)
2067 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2068 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2069 std::move(Args), 0);
2071 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2072 return CallResult.second;
2075 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2076 const PPCSubtarget &Subtarget) const {
2077 MachineFunction &MF = DAG.getMachineFunction();
2078 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2082 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2083 // vastart just stores the address of the VarArgsFrameIndex slot into the
2084 // memory location argument.
2085 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2086 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2087 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2088 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2089 MachinePointerInfo(SV),
2093 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2094 // We suppose the given va_list is already allocated.
2097 // char gpr; /* index into the array of 8 GPRs
2098 // * stored in the register save area
2099 // * gpr=0 corresponds to r3,
2100 // * gpr=1 to r4, etc.
2102 // char fpr; /* index into the array of 8 FPRs
2103 // * stored in the register save area
2104 // * fpr=0 corresponds to f1,
2105 // * fpr=1 to f2, etc.
2107 // char *overflow_arg_area;
2108 // /* location on stack that holds
2109 // * the next overflow argument
2111 // char *reg_save_area;
2112 // /* where r3:r10 and f1:f8 (if saved)
2118 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2119 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2122 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2124 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2126 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2129 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2130 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2132 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2133 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2135 uint64_t FPROffset = 1;
2136 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2138 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2140 // Store first byte : number of int regs
2141 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2143 MachinePointerInfo(SV),
2144 MVT::i8, false, false, 0);
2145 uint64_t nextOffset = FPROffset;
2146 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2149 // Store second byte : number of float regs
2150 SDValue secondStore =
2151 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2152 MachinePointerInfo(SV, nextOffset), MVT::i8,
2154 nextOffset += StackOffset;
2155 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2157 // Store second word : arguments given on stack
2158 SDValue thirdStore =
2159 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2160 MachinePointerInfo(SV, nextOffset),
2162 nextOffset += FrameOffset;
2163 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2165 // Store third word : arguments given in registers
2166 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2167 MachinePointerInfo(SV, nextOffset),
2172 #include "PPCGenCallingConv.inc"
2174 // Function whose sole purpose is to kill compiler warnings
2175 // stemming from unused functions included from PPCGenCallingConv.inc.
2176 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2177 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2180 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2181 CCValAssign::LocInfo &LocInfo,
2182 ISD::ArgFlagsTy &ArgFlags,
2187 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2189 CCValAssign::LocInfo &LocInfo,
2190 ISD::ArgFlagsTy &ArgFlags,
2192 static const MCPhysReg ArgRegs[] = {
2193 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2194 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2196 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2198 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2200 // Skip one register if the first unallocated register has an even register
2201 // number and there are still argument registers available which have not been
2202 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2203 // need to skip a register if RegNum is odd.
2204 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2205 State.AllocateReg(ArgRegs[RegNum]);
2208 // Always return false here, as this function only makes sure that the first
2209 // unallocated register has an odd register number and does not actually
2210 // allocate a register for the current argument.
2214 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2216 CCValAssign::LocInfo &LocInfo,
2217 ISD::ArgFlagsTy &ArgFlags,
2219 static const MCPhysReg ArgRegs[] = {
2220 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2224 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2226 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2228 // If there is only one Floating-point register left we need to put both f64
2229 // values of a split ppc_fp128 value on the stack.
2230 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2231 State.AllocateReg(ArgRegs[RegNum]);
2234 // Always return false here, as this function only makes sure that the two f64
2235 // values a ppc_fp128 value is split into are both passed in registers or both
2236 // passed on the stack and does not actually allocate a register for the
2237 // current argument.
2241 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2243 static const MCPhysReg *GetFPR() {
2244 static const MCPhysReg FPR[] = {
2245 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2246 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2252 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2254 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2255 unsigned PtrByteSize) {
2256 unsigned ArgSize = ArgVT.getStoreSize();
2257 if (Flags.isByVal())
2258 ArgSize = Flags.getByValSize();
2260 // Round up to multiples of the pointer size, except for array members,
2261 // which are always packed.
2262 if (!Flags.isInConsecutiveRegs())
2263 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2268 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2270 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2271 ISD::ArgFlagsTy Flags,
2272 unsigned PtrByteSize) {
2273 unsigned Align = PtrByteSize;
2275 // Altivec parameters are padded to a 16 byte boundary.
2276 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2277 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2278 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2281 // ByVal parameters are aligned as requested.
2282 if (Flags.isByVal()) {
2283 unsigned BVAlign = Flags.getByValAlign();
2284 if (BVAlign > PtrByteSize) {
2285 if (BVAlign % PtrByteSize != 0)
2287 "ByVal alignment is not a multiple of the pointer size");
2293 // Array members are always packed to their original alignment.
2294 if (Flags.isInConsecutiveRegs()) {
2295 // If the array member was split into multiple registers, the first
2296 // needs to be aligned to the size of the full type. (Except for
2297 // ppcf128, which is only aligned as its f64 components.)
2298 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2299 Align = OrigVT.getStoreSize();
2301 Align = ArgVT.getStoreSize();
2307 /// CalculateStackSlotUsed - Return whether this argument will use its
2308 /// stack slot (instead of being passed in registers). ArgOffset,
2309 /// AvailableFPRs, and AvailableVRs must hold the current argument
2310 /// position, and will be updated to account for this argument.
2311 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2312 ISD::ArgFlagsTy Flags,
2313 unsigned PtrByteSize,
2314 unsigned LinkageSize,
2315 unsigned ParamAreaSize,
2316 unsigned &ArgOffset,
2317 unsigned &AvailableFPRs,
2318 unsigned &AvailableVRs) {
2319 bool UseMemory = false;
2321 // Respect alignment of argument on the stack.
2323 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2324 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2325 // If there's no space left in the argument save area, we must
2326 // use memory (this check also catches zero-sized arguments).
2327 if (ArgOffset >= LinkageSize + ParamAreaSize)
2330 // Allocate argument on the stack.
2331 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2332 if (Flags.isInConsecutiveRegsLast())
2333 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2334 // If we overran the argument save area, we must use memory
2335 // (this check catches arguments passed partially in memory)
2336 if (ArgOffset > LinkageSize + ParamAreaSize)
2339 // However, if the argument is actually passed in an FPR or a VR,
2340 // we don't use memory after all.
2341 if (!Flags.isByVal()) {
2342 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2343 if (AvailableFPRs > 0) {
2347 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2348 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2349 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2350 if (AvailableVRs > 0) {
2359 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2360 /// ensure minimum alignment required for target.
2361 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2362 unsigned NumBytes) {
2363 unsigned TargetAlign = Lowering->getStackAlignment();
2364 unsigned AlignMask = TargetAlign - 1;
2365 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2370 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2371 CallingConv::ID CallConv, bool isVarArg,
2372 const SmallVectorImpl<ISD::InputArg>
2374 SDLoc dl, SelectionDAG &DAG,
2375 SmallVectorImpl<SDValue> &InVals)
2377 if (Subtarget.isSVR4ABI()) {
2378 if (Subtarget.isPPC64())
2379 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2382 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2385 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2391 PPCTargetLowering::LowerFormalArguments_32SVR4(
2393 CallingConv::ID CallConv, bool isVarArg,
2394 const SmallVectorImpl<ISD::InputArg>
2396 SDLoc dl, SelectionDAG &DAG,
2397 SmallVectorImpl<SDValue> &InVals) const {
2399 // 32-bit SVR4 ABI Stack Frame Layout:
2400 // +-----------------------------------+
2401 // +--> | Back chain |
2402 // | +-----------------------------------+
2403 // | | Floating-point register save area |
2404 // | +-----------------------------------+
2405 // | | General register save area |
2406 // | +-----------------------------------+
2407 // | | CR save word |
2408 // | +-----------------------------------+
2409 // | | VRSAVE save word |
2410 // | +-----------------------------------+
2411 // | | Alignment padding |
2412 // | +-----------------------------------+
2413 // | | Vector register save area |
2414 // | +-----------------------------------+
2415 // | | Local variable space |
2416 // | +-----------------------------------+
2417 // | | Parameter list area |
2418 // | +-----------------------------------+
2419 // | | LR save word |
2420 // | +-----------------------------------+
2421 // SP--> +--- | Back chain |
2422 // +-----------------------------------+
2425 // System V Application Binary Interface PowerPC Processor Supplement
2426 // AltiVec Technology Programming Interface Manual
2428 MachineFunction &MF = DAG.getMachineFunction();
2429 MachineFrameInfo *MFI = MF.getFrameInfo();
2430 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2432 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2433 // Potential tail calls could cause overwriting of argument stack slots.
2434 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2435 (CallConv == CallingConv::Fast));
2436 unsigned PtrByteSize = 4;
2438 // Assign locations to all of the incoming arguments.
2439 SmallVector<CCValAssign, 16> ArgLocs;
2440 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2443 // Reserve space for the linkage area on the stack.
2444 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2445 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2447 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2449 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2450 CCValAssign &VA = ArgLocs[i];
2452 // Arguments stored in registers.
2453 if (VA.isRegLoc()) {
2454 const TargetRegisterClass *RC;
2455 EVT ValVT = VA.getValVT();
2457 switch (ValVT.getSimpleVT().SimpleTy) {
2459 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2462 RC = &PPC::GPRCRegClass;
2465 RC = &PPC::F4RCRegClass;
2468 if (Subtarget.hasVSX())
2469 RC = &PPC::VSFRCRegClass;
2471 RC = &PPC::F8RCRegClass;
2477 RC = &PPC::VRRCRegClass;
2481 RC = &PPC::VSHRCRegClass;
2485 // Transform the arguments stored in physical registers into virtual ones.
2486 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2487 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2488 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2490 if (ValVT == MVT::i1)
2491 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2493 InVals.push_back(ArgValue);
2495 // Argument stored in memory.
2496 assert(VA.isMemLoc());
2498 unsigned ArgSize = VA.getLocVT().getStoreSize();
2499 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2502 // Create load nodes to retrieve arguments from the stack.
2503 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2504 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2505 MachinePointerInfo(),
2506 false, false, false, 0));
2510 // Assign locations to all of the incoming aggregate by value arguments.
2511 // Aggregates passed by value are stored in the local variable space of the
2512 // caller's stack frame, right above the parameter list area.
2513 SmallVector<CCValAssign, 16> ByValArgLocs;
2514 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2515 ByValArgLocs, *DAG.getContext());
2517 // Reserve stack space for the allocations in CCInfo.
2518 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2520 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2522 // Area that is at least reserved in the caller of this function.
2523 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2524 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2526 // Set the size that is at least reserved in caller of this function. Tail
2527 // call optimized function's reserved stack space needs to be aligned so that
2528 // taking the difference between two stack areas will result in an aligned
2531 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2532 FuncInfo->setMinReservedArea(MinReservedArea);
2534 SmallVector<SDValue, 8> MemOps;
2536 // If the function takes variable number of arguments, make a frame index for
2537 // the start of the first vararg value... for expansion of llvm.va_start.
2539 static const MCPhysReg GPArgRegs[] = {
2540 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2541 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2543 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2545 static const MCPhysReg FPArgRegs[] = {
2546 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2549 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2550 if (DisablePPCFloatInVariadic)
2553 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2555 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2558 // Make room for NumGPArgRegs and NumFPArgRegs.
2559 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2560 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2562 FuncInfo->setVarArgsStackOffset(
2563 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2564 CCInfo.getNextStackOffset(), true));
2566 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2567 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2569 // The fixed integer arguments of a variadic function are stored to the
2570 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2571 // the result of va_next.
2572 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2573 // Get an existing live-in vreg, or add a new one.
2574 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2576 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2578 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2579 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2580 MachinePointerInfo(), false, false, 0);
2581 MemOps.push_back(Store);
2582 // Increment the address by four for the next argument to store
2583 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2584 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2587 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2589 // The double arguments are stored to the VarArgsFrameIndex
2591 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2592 // Get an existing live-in vreg, or add a new one.
2593 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2595 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2597 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2598 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2599 MachinePointerInfo(), false, false, 0);
2600 MemOps.push_back(Store);
2601 // Increment the address by eight for the next argument to store
2602 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2604 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2608 if (!MemOps.empty())
2609 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2614 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2615 // value to MVT::i64 and then truncate to the correct register size.
2617 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2618 SelectionDAG &DAG, SDValue ArgVal,
2621 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2622 DAG.getValueType(ObjectVT));
2623 else if (Flags.isZExt())
2624 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2625 DAG.getValueType(ObjectVT));
2627 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2631 PPCTargetLowering::LowerFormalArguments_64SVR4(
2633 CallingConv::ID CallConv, bool isVarArg,
2634 const SmallVectorImpl<ISD::InputArg>
2636 SDLoc dl, SelectionDAG &DAG,
2637 SmallVectorImpl<SDValue> &InVals) const {
2638 // TODO: add description of PPC stack frame format, or at least some docs.
2640 bool isELFv2ABI = Subtarget.isELFv2ABI();
2641 bool isLittleEndian = Subtarget.isLittleEndian();
2642 MachineFunction &MF = DAG.getMachineFunction();
2643 MachineFrameInfo *MFI = MF.getFrameInfo();
2644 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2646 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2647 "fastcc not supported on varargs functions");
2649 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2650 // Potential tail calls could cause overwriting of argument stack slots.
2651 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2652 (CallConv == CallingConv::Fast));
2653 unsigned PtrByteSize = 8;
2655 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2658 static const MCPhysReg GPR[] = {
2659 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2660 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2663 static const MCPhysReg *FPR = GetFPR();
2665 static const MCPhysReg VR[] = {
2666 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2667 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2669 static const MCPhysReg VSRH[] = {
2670 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2671 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2674 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2675 const unsigned Num_FPR_Regs = 13;
2676 const unsigned Num_VR_Regs = array_lengthof(VR);
2678 // Do a first pass over the arguments to determine whether the ABI
2679 // guarantees that our caller has allocated the parameter save area
2680 // on its stack frame. In the ELFv1 ABI, this is always the case;
2681 // in the ELFv2 ABI, it is true if this is a vararg function or if
2682 // any parameter is located in a stack slot.
2684 bool HasParameterArea = !isELFv2ABI || isVarArg;
2685 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2686 unsigned NumBytes = LinkageSize;
2687 unsigned AvailableFPRs = Num_FPR_Regs;
2688 unsigned AvailableVRs = Num_VR_Regs;
2689 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2690 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2691 PtrByteSize, LinkageSize, ParamAreaSize,
2692 NumBytes, AvailableFPRs, AvailableVRs))
2693 HasParameterArea = true;
2695 // Add DAG nodes to load the arguments or copy them out of registers. On
2696 // entry to a function on PPC, the arguments start after the linkage area,
2697 // although the first ones are often in registers.
2699 unsigned ArgOffset = LinkageSize;
2700 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2701 SmallVector<SDValue, 8> MemOps;
2702 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2703 unsigned CurArgIdx = 0;
2704 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2706 bool needsLoad = false;
2707 EVT ObjectVT = Ins[ArgNo].VT;
2708 EVT OrigVT = Ins[ArgNo].ArgVT;
2709 unsigned ObjSize = ObjectVT.getStoreSize();
2710 unsigned ArgSize = ObjSize;
2711 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2712 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2713 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2715 // We re-align the argument offset for each argument, except when using the
2716 // fast calling convention, when we need to make sure we do that only when
2717 // we'll actually use a stack slot.
2718 unsigned CurArgOffset, Align;
2719 auto ComputeArgOffset = [&]() {
2720 /* Respect alignment of argument on the stack. */
2721 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2722 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2723 CurArgOffset = ArgOffset;
2726 if (CallConv != CallingConv::Fast) {
2729 /* Compute GPR index associated with argument offset. */
2730 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2731 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2734 // FIXME the codegen can be much improved in some cases.
2735 // We do not have to keep everything in memory.
2736 if (Flags.isByVal()) {
2737 if (CallConv == CallingConv::Fast)
2740 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2741 ObjSize = Flags.getByValSize();
2742 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2743 // Empty aggregate parameters do not take up registers. Examples:
2747 // etc. However, we have to provide a place-holder in InVals, so
2748 // pretend we have an 8-byte item at the current address for that
2751 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2752 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2753 InVals.push_back(FIN);
2757 // Create a stack object covering all stack doublewords occupied
2758 // by the argument. If the argument is (fully or partially) on
2759 // the stack, or if the argument is fully in registers but the
2760 // caller has allocated the parameter save anyway, we can refer
2761 // directly to the caller's stack frame. Otherwise, create a
2762 // local copy in our own frame.
2764 if (HasParameterArea ||
2765 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2766 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2768 FI = MFI->CreateStackObject(ArgSize, Align, false);
2769 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2771 // Handle aggregates smaller than 8 bytes.
2772 if (ObjSize < PtrByteSize) {
2773 // The value of the object is its address, which differs from the
2774 // address of the enclosing doubleword on big-endian systems.
2776 if (!isLittleEndian) {
2777 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2778 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2780 InVals.push_back(Arg);
2782 if (GPR_idx != Num_GPR_Regs) {
2783 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2784 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2787 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2788 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2789 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2790 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2791 MachinePointerInfo(FuncArg),
2792 ObjType, false, false, 0);
2794 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2795 // store the whole register as-is to the parameter save area
2797 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2798 MachinePointerInfo(FuncArg),
2802 MemOps.push_back(Store);
2804 // Whether we copied from a register or not, advance the offset
2805 // into the parameter save area by a full doubleword.
2806 ArgOffset += PtrByteSize;
2810 // The value of the object is its address, which is the address of
2811 // its first stack doubleword.
2812 InVals.push_back(FIN);
2814 // Store whatever pieces of the object are in registers to memory.
2815 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2816 if (GPR_idx == Num_GPR_Regs)
2819 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2820 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2823 SDValue Off = DAG.getConstant(j, PtrVT);
2824 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2826 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2827 MachinePointerInfo(FuncArg, j),
2829 MemOps.push_back(Store);
2832 ArgOffset += ArgSize;
2836 switch (ObjectVT.getSimpleVT().SimpleTy) {
2837 default: llvm_unreachable("Unhandled argument type!");
2841 // These can be scalar arguments or elements of an integer array type
2842 // passed directly. Clang may use those instead of "byval" aggregate
2843 // types to avoid forcing arguments to memory unnecessarily.
2844 if (GPR_idx != Num_GPR_Regs) {
2845 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2846 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2848 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2849 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2850 // value to MVT::i64 and then truncate to the correct register size.
2851 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2853 if (CallConv == CallingConv::Fast)
2857 ArgSize = PtrByteSize;
2859 if (CallConv != CallingConv::Fast || needsLoad)
2865 // These can be scalar arguments or elements of a float array type
2866 // passed directly. The latter are used to implement ELFv2 homogenous
2867 // float aggregates.
2868 if (FPR_idx != Num_FPR_Regs) {
2871 if (ObjectVT == MVT::f32)
2872 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2874 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
2875 ? &PPC::VSFRCRegClass
2876 : &PPC::F8RCRegClass);
2878 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2880 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
2881 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
2882 // once we support fp <-> gpr moves.
2884 // This can only ever happen in the presence of f32 array types,
2885 // since otherwise we never run out of FPRs before running out
2887 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2888 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2890 if (ObjectVT == MVT::f32) {
2891 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2892 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2893 DAG.getConstant(32, MVT::i32));
2894 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2897 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2899 if (CallConv == CallingConv::Fast)
2905 // When passing an array of floats, the array occupies consecutive
2906 // space in the argument area; only round up to the next doubleword
2907 // at the end of the array. Otherwise, each float takes 8 bytes.
2908 if (CallConv != CallingConv::Fast || needsLoad) {
2909 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2910 ArgOffset += ArgSize;
2911 if (Flags.isInConsecutiveRegsLast())
2912 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2921 // These can be scalar arguments or elements of a vector array type
2922 // passed directly. The latter are used to implement ELFv2 homogenous
2923 // vector aggregates.
2924 if (VR_idx != Num_VR_Regs) {
2925 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2926 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2927 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2928 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2931 if (CallConv == CallingConv::Fast)
2936 if (CallConv != CallingConv::Fast || needsLoad)
2941 // We need to load the argument to a virtual register if we determined
2942 // above that we ran out of physical registers of the appropriate type.
2944 if (ObjSize < ArgSize && !isLittleEndian)
2945 CurArgOffset += ArgSize - ObjSize;
2946 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2947 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2948 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2949 false, false, false, 0);
2952 InVals.push_back(ArgVal);
2955 // Area that is at least reserved in the caller of this function.
2956 unsigned MinReservedArea;
2957 if (HasParameterArea)
2958 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2960 MinReservedArea = LinkageSize;
2962 // Set the size that is at least reserved in caller of this function. Tail
2963 // call optimized functions' reserved stack space needs to be aligned so that
2964 // taking the difference between two stack areas will result in an aligned
2967 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2968 FuncInfo->setMinReservedArea(MinReservedArea);
2970 // If the function takes variable number of arguments, make a frame index for
2971 // the start of the first vararg value... for expansion of llvm.va_start.
2973 int Depth = ArgOffset;
2975 FuncInfo->setVarArgsFrameIndex(
2976 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2977 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2979 // If this function is vararg, store any remaining integer argument regs
2980 // to their spots on the stack so that they may be loaded by deferencing the
2981 // result of va_next.
2982 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2983 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2984 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2985 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2986 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2987 MachinePointerInfo(), false, false, 0);
2988 MemOps.push_back(Store);
2989 // Increment the address by four for the next argument to store
2990 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2991 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2995 if (!MemOps.empty())
2996 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3002 PPCTargetLowering::LowerFormalArguments_Darwin(
3004 CallingConv::ID CallConv, bool isVarArg,
3005 const SmallVectorImpl<ISD::InputArg>
3007 SDLoc dl, SelectionDAG &DAG,
3008 SmallVectorImpl<SDValue> &InVals) const {
3009 // TODO: add description of PPC stack frame format, or at least some docs.
3011 MachineFunction &MF = DAG.getMachineFunction();
3012 MachineFrameInfo *MFI = MF.getFrameInfo();
3013 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3015 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3016 bool isPPC64 = PtrVT == MVT::i64;
3017 // Potential tail calls could cause overwriting of argument stack slots.
3018 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3019 (CallConv == CallingConv::Fast));
3020 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3022 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
3024 unsigned ArgOffset = LinkageSize;
3025 // Area that is at least reserved in caller of this function.
3026 unsigned MinReservedArea = ArgOffset;
3028 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3029 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3030 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3032 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3033 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3034 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3037 static const MCPhysReg *FPR = GetFPR();
3039 static const MCPhysReg VR[] = {
3040 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3041 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3044 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3045 const unsigned Num_FPR_Regs = 13;
3046 const unsigned Num_VR_Regs = array_lengthof( VR);
3048 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3050 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3052 // In 32-bit non-varargs functions, the stack space for vectors is after the
3053 // stack space for non-vectors. We do not use this space unless we have
3054 // too many vectors to fit in registers, something that only occurs in
3055 // constructed examples:), but we have to walk the arglist to figure
3056 // that out...for the pathological case, compute VecArgOffset as the
3057 // start of the vector parameter area. Computing VecArgOffset is the
3058 // entire point of the following loop.
3059 unsigned VecArgOffset = ArgOffset;
3060 if (!isVarArg && !isPPC64) {
3061 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3063 EVT ObjectVT = Ins[ArgNo].VT;
3064 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3066 if (Flags.isByVal()) {
3067 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3068 unsigned ObjSize = Flags.getByValSize();
3070 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3071 VecArgOffset += ArgSize;
3075 switch(ObjectVT.getSimpleVT().SimpleTy) {
3076 default: llvm_unreachable("Unhandled argument type!");
3082 case MVT::i64: // PPC64
3084 // FIXME: We are guaranteed to be !isPPC64 at this point.
3085 // Does MVT::i64 apply?
3092 // Nothing to do, we're only looking at Nonvector args here.
3097 // We've found where the vector parameter area in memory is. Skip the
3098 // first 12 parameters; these don't use that memory.
3099 VecArgOffset = ((VecArgOffset+15)/16)*16;
3100 VecArgOffset += 12*16;
3102 // Add DAG nodes to load the arguments or copy them out of registers. On
3103 // entry to a function on PPC, the arguments start after the linkage area,
3104 // although the first ones are often in registers.
3106 SmallVector<SDValue, 8> MemOps;
3107 unsigned nAltivecParamsAtEnd = 0;
3108 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3109 unsigned CurArgIdx = 0;
3110 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3112 bool needsLoad = false;
3113 EVT ObjectVT = Ins[ArgNo].VT;
3114 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3115 unsigned ArgSize = ObjSize;
3116 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3117 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3118 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3120 unsigned CurArgOffset = ArgOffset;
3122 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3123 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3124 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3125 if (isVarArg || isPPC64) {
3126 MinReservedArea = ((MinReservedArea+15)/16)*16;
3127 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3130 } else nAltivecParamsAtEnd++;
3132 // Calculate min reserved area.
3133 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3137 // FIXME the codegen can be much improved in some cases.
3138 // We do not have to keep everything in memory.
3139 if (Flags.isByVal()) {
3140 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3141 ObjSize = Flags.getByValSize();
3142 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3143 // Objects of size 1 and 2 are right justified, everything else is
3144 // left justified. This means the memory address is adjusted forwards.
3145 if (ObjSize==1 || ObjSize==2) {
3146 CurArgOffset = CurArgOffset + (4 - ObjSize);
3148 // The value of the object is its address.
3149 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3150 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3151 InVals.push_back(FIN);
3152 if (ObjSize==1 || ObjSize==2) {
3153 if (GPR_idx != Num_GPR_Regs) {
3156 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3158 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3159 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3160 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3161 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3162 MachinePointerInfo(FuncArg),
3163 ObjType, false, false, 0);
3164 MemOps.push_back(Store);
3168 ArgOffset += PtrByteSize;
3172 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3173 // Store whatever pieces of the object are in registers
3174 // to memory. ArgOffset will be the address of the beginning
3176 if (GPR_idx != Num_GPR_Regs) {
3179 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3181 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3182 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3183 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3184 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3185 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3186 MachinePointerInfo(FuncArg, j),
3188 MemOps.push_back(Store);
3190 ArgOffset += PtrByteSize;
3192 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3199 switch (ObjectVT.getSimpleVT().SimpleTy) {
3200 default: llvm_unreachable("Unhandled argument type!");
3204 if (GPR_idx != Num_GPR_Regs) {
3205 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3206 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3208 if (ObjectVT == MVT::i1)
3209 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3214 ArgSize = PtrByteSize;
3216 // All int arguments reserve stack space in the Darwin ABI.
3217 ArgOffset += PtrByteSize;
3221 case MVT::i64: // PPC64
3222 if (GPR_idx != Num_GPR_Regs) {
3223 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3224 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3226 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3227 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3228 // value to MVT::i64 and then truncate to the correct register size.
3229 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3234 ArgSize = PtrByteSize;
3236 // All int arguments reserve stack space in the Darwin ABI.
3242 // Every 4 bytes of argument space consumes one of the GPRs available for
3243 // argument passing.
3244 if (GPR_idx != Num_GPR_Regs) {
3246 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3249 if (FPR_idx != Num_FPR_Regs) {
3252 if (ObjectVT == MVT::f32)
3253 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3255 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3257 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3263 // All FP arguments reserve stack space in the Darwin ABI.
3264 ArgOffset += isPPC64 ? 8 : ObjSize;
3270 // Note that vector arguments in registers don't reserve stack space,
3271 // except in varargs functions.
3272 if (VR_idx != Num_VR_Regs) {
3273 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3274 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3276 while ((ArgOffset % 16) != 0) {
3277 ArgOffset += PtrByteSize;
3278 if (GPR_idx != Num_GPR_Regs)
3282 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3286 if (!isVarArg && !isPPC64) {
3287 // Vectors go after all the nonvectors.
3288 CurArgOffset = VecArgOffset;
3291 // Vectors are aligned.
3292 ArgOffset = ((ArgOffset+15)/16)*16;
3293 CurArgOffset = ArgOffset;
3301 // We need to load the argument to a virtual register if we determined above
3302 // that we ran out of physical registers of the appropriate type.
3304 int FI = MFI->CreateFixedObject(ObjSize,
3305 CurArgOffset + (ArgSize - ObjSize),
3307 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3308 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3309 false, false, false, 0);
3312 InVals.push_back(ArgVal);
3315 // Allow for Altivec parameters at the end, if needed.
3316 if (nAltivecParamsAtEnd) {
3317 MinReservedArea = ((MinReservedArea+15)/16)*16;
3318 MinReservedArea += 16*nAltivecParamsAtEnd;
3321 // Area that is at least reserved in the caller of this function.
3322 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3324 // Set the size that is at least reserved in caller of this function. Tail
3325 // call optimized functions' reserved stack space needs to be aligned so that
3326 // taking the difference between two stack areas will result in an aligned
3329 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3330 FuncInfo->setMinReservedArea(MinReservedArea);
3332 // If the function takes variable number of arguments, make a frame index for
3333 // the start of the first vararg value... for expansion of llvm.va_start.
3335 int Depth = ArgOffset;
3337 FuncInfo->setVarArgsFrameIndex(
3338 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3340 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3342 // If this function is vararg, store any remaining integer argument regs
3343 // to their spots on the stack so that they may be loaded by deferencing the
3344 // result of va_next.
3345 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3349 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3351 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3353 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3354 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3355 MachinePointerInfo(), false, false, 0);
3356 MemOps.push_back(Store);
3357 // Increment the address by four for the next argument to store
3358 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3359 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3363 if (!MemOps.empty())
3364 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3369 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3370 /// adjusted to accommodate the arguments for the tailcall.
3371 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3372 unsigned ParamSize) {
3374 if (!isTailCall) return 0;
3376 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3377 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3378 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3379 // Remember only if the new adjustement is bigger.
3380 if (SPDiff < FI->getTailCallSPDelta())
3381 FI->setTailCallSPDelta(SPDiff);
3386 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3387 /// for tail call optimization. Targets which want to do tail call
3388 /// optimization should implement this function.
3390 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3391 CallingConv::ID CalleeCC,
3393 const SmallVectorImpl<ISD::InputArg> &Ins,
3394 SelectionDAG& DAG) const {
3395 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3398 // Variable argument functions are not supported.
3402 MachineFunction &MF = DAG.getMachineFunction();
3403 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3404 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3405 // Functions containing by val parameters are not supported.
3406 for (unsigned i = 0; i != Ins.size(); i++) {
3407 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3408 if (Flags.isByVal()) return false;
3411 // Non-PIC/GOT tail calls are supported.
3412 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3415 // At the moment we can only do local tail calls (in same module, hidden
3416 // or protected) if we are generating PIC.
3417 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3418 return G->getGlobal()->hasHiddenVisibility()
3419 || G->getGlobal()->hasProtectedVisibility();
3425 /// isCallCompatibleAddress - Return the immediate to use if the specified
3426 /// 32-bit value is representable in the immediate field of a BxA instruction.
3427 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3428 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3429 if (!C) return nullptr;
3431 int Addr = C->getZExtValue();
3432 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3433 SignExtend32<26>(Addr) != Addr)
3434 return nullptr; // Top 6 bits have to be sext of immediate.
3436 return DAG.getConstant((int)C->getZExtValue() >> 2,
3437 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3442 struct TailCallArgumentInfo {
3447 TailCallArgumentInfo() : FrameIdx(0) {}
3452 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3454 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3456 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3457 SmallVectorImpl<SDValue> &MemOpChains,
3459 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3460 SDValue Arg = TailCallArgs[i].Arg;
3461 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3462 int FI = TailCallArgs[i].FrameIdx;
3463 // Store relative to framepointer.
3464 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3465 MachinePointerInfo::getFixedStack(FI),
3470 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3471 /// the appropriate stack slot for the tail call optimized function call.
3472 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3473 MachineFunction &MF,
3482 // Calculate the new stack slot for the return address.
3483 int SlotSize = isPPC64 ? 8 : 4;
3484 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3486 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3487 NewRetAddrLoc, true);
3488 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3489 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3490 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3491 MachinePointerInfo::getFixedStack(NewRetAddr),
3494 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3495 // slot as the FP is never overwritten.
3498 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3499 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3501 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3502 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3503 MachinePointerInfo::getFixedStack(NewFPIdx),
3510 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3511 /// the position of the argument.
3513 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3514 SDValue Arg, int SPDiff, unsigned ArgOffset,
3515 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3516 int Offset = ArgOffset + SPDiff;
3517 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3518 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3519 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3520 SDValue FIN = DAG.getFrameIndex(FI, VT);
3521 TailCallArgumentInfo Info;
3523 Info.FrameIdxOp = FIN;
3525 TailCallArguments.push_back(Info);
3528 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3529 /// stack slot. Returns the chain as result and the loaded frame pointers in
3530 /// LROpOut/FPOpout. Used when tail calling.
3531 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3539 // Load the LR and FP stack slot for later adjusting.
3540 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3541 LROpOut = getReturnAddrFrameIndex(DAG);
3542 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3543 false, false, false, 0);
3544 Chain = SDValue(LROpOut.getNode(), 1);
3546 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3547 // slot as the FP is never overwritten.
3549 FPOpOut = getFramePointerFrameIndex(DAG);
3550 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3551 false, false, false, 0);
3552 Chain = SDValue(FPOpOut.getNode(), 1);
3558 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3559 /// by "Src" to address "Dst" of size "Size". Alignment information is
3560 /// specified by the specific parameter attribute. The copy will be passed as
3561 /// a byval function parameter.
3562 /// Sometimes what we are copying is the end of a larger object, the part that
3563 /// does not fit in registers.
3565 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3566 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3568 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3569 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3570 false, false, MachinePointerInfo(),
3571 MachinePointerInfo());
3574 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3577 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3578 SDValue Arg, SDValue PtrOff, int SPDiff,
3579 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3580 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3581 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3583 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3588 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3590 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3591 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3592 DAG.getConstant(ArgOffset, PtrVT));
3594 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3595 MachinePointerInfo(), false, false, 0));
3596 // Calculate and remember argument location.
3597 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3602 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3603 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3604 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3605 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3606 MachineFunction &MF = DAG.getMachineFunction();
3608 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3609 // might overwrite each other in case of tail call optimization.
3610 SmallVector<SDValue, 8> MemOpChains2;
3611 // Do not flag preceding copytoreg stuff together with the following stuff.
3613 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3615 if (!MemOpChains2.empty())
3616 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3618 // Store the return address to the appropriate stack slot.
3619 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3620 isPPC64, isDarwinABI, dl);
3622 // Emit callseq_end just before tailcall node.
3623 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3624 DAG.getIntPtrConstant(0, true), InFlag, dl);
3625 InFlag = Chain.getValue(1);
3628 // Is this global address that of a function that can be called by name? (as
3629 // opposed to something that must hold a descriptor for an indirect call).
3630 static bool isFunctionGlobalAddress(SDValue Callee) {
3631 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3632 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3633 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3636 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3643 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3644 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3645 bool isTailCall, bool IsPatchPoint,
3646 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3647 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3648 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3650 bool isPPC64 = Subtarget.isPPC64();
3651 bool isSVR4ABI = Subtarget.isSVR4ABI();
3652 bool isELFv2ABI = Subtarget.isELFv2ABI();
3654 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3655 NodeTys.push_back(MVT::Other); // Returns a chain
3656 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3658 unsigned CallOpc = PPCISD::CALL;
3660 bool needIndirectCall = true;
3661 if (!isSVR4ABI || !isPPC64)
3662 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3663 // If this is an absolute destination address, use the munged value.
3664 Callee = SDValue(Dest, 0);
3665 needIndirectCall = false;
3668 if (isFunctionGlobalAddress(Callee)) {
3669 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3670 // A call to a TLS address is actually an indirect call to a
3671 // thread-specific pointer.
3672 unsigned OpFlags = 0;
3673 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3674 (Subtarget.getTargetTriple().isMacOSX() &&
3675 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3676 (G->getGlobal()->isDeclaration() ||
3677 G->getGlobal()->isWeakForLinker())) ||
3678 (Subtarget.isTargetELF() && !isPPC64 &&
3679 !G->getGlobal()->hasLocalLinkage() &&
3680 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3681 // PC-relative references to external symbols should go through $stub,
3682 // unless we're building with the leopard linker or later, which
3683 // automatically synthesizes these stubs.
3684 OpFlags = PPCII::MO_PLT_OR_STUB;
3687 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3688 // every direct call is) turn it into a TargetGlobalAddress /
3689 // TargetExternalSymbol node so that legalize doesn't hack it.
3690 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3691 Callee.getValueType(), 0, OpFlags);
3692 needIndirectCall = false;
3695 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3696 unsigned char OpFlags = 0;
3698 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3699 (Subtarget.getTargetTriple().isMacOSX() &&
3700 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3701 (Subtarget.isTargetELF() && !isPPC64 &&
3702 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3703 // PC-relative references to external symbols should go through $stub,
3704 // unless we're building with the leopard linker or later, which
3705 // automatically synthesizes these stubs.
3706 OpFlags = PPCII::MO_PLT_OR_STUB;
3709 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3711 needIndirectCall = false;
3715 // We'll form an invalid direct call when lowering a patchpoint; the full
3716 // sequence for an indirect call is complicated, and many of the
3717 // instructions introduced might have side effects (and, thus, can't be
3718 // removed later). The call itself will be removed as soon as the
3719 // argument/return lowering is complete, so the fact that it has the wrong
3720 // kind of operands should not really matter.
3721 needIndirectCall = false;
3724 if (needIndirectCall) {
3725 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3726 // to do the call, we can't use PPCISD::CALL.
3727 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3729 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3730 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3731 // entry point, but to the function descriptor (the function entry point
3732 // address is part of the function descriptor though).
3733 // The function descriptor is a three doubleword structure with the
3734 // following fields: function entry point, TOC base address and
3735 // environment pointer.
3736 // Thus for a call through a function pointer, the following actions need
3738 // 1. Save the TOC of the caller in the TOC save area of its stack
3739 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3740 // 2. Load the address of the function entry point from the function
3742 // 3. Load the TOC of the callee from the function descriptor into r2.
3743 // 4. Load the environment pointer from the function descriptor into
3745 // 5. Branch to the function entry point address.
3746 // 6. On return of the callee, the TOC of the caller needs to be
3747 // restored (this is done in FinishCall()).
3749 // The loads are scheduled at the beginning of the call sequence, and the
3750 // register copies are flagged together to ensure that no other
3751 // operations can be scheduled in between. E.g. without flagging the
3752 // copies together, a TOC access in the caller could be scheduled between
3753 // the assignment of the callee TOC and the branch to the callee, which
3754 // results in the TOC access going through the TOC of the callee instead
3755 // of going through the TOC of the caller, which leads to incorrect code.
3757 // Load the address of the function entry point from the function
3759 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
3760 if (LDChain.getValueType() == MVT::Glue)
3761 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
3763 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
3765 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
3766 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
3767 false, false, LoadsInv, 8);
3769 // Load environment pointer into r11.
3770 SDValue PtrOff = DAG.getIntPtrConstant(16);
3771 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3772 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
3773 MPI.getWithOffset(16), false, false,
3776 SDValue TOCOff = DAG.getIntPtrConstant(8);
3777 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3778 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
3779 MPI.getWithOffset(8), false, false,
3782 setUsesTOCBasePtr(DAG);
3783 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
3785 Chain = TOCVal.getValue(0);
3786 InFlag = TOCVal.getValue(1);
3788 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3791 Chain = EnvVal.getValue(0);
3792 InFlag = EnvVal.getValue(1);
3794 MTCTROps[0] = Chain;
3795 MTCTROps[1] = LoadFuncPtr;
3796 MTCTROps[2] = InFlag;
3799 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3800 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3801 InFlag = Chain.getValue(1);
3804 NodeTys.push_back(MVT::Other);
3805 NodeTys.push_back(MVT::Glue);
3806 Ops.push_back(Chain);
3807 CallOpc = PPCISD::BCTRL;
3808 Callee.setNode(nullptr);
3809 // Add use of X11 (holding environment pointer)
3810 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3811 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3812 // Add CTR register as callee so a bctr can be emitted later.
3814 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3817 // If this is a direct call, pass the chain and the callee.
3818 if (Callee.getNode()) {
3819 Ops.push_back(Chain);
3820 Ops.push_back(Callee);
3822 // If this is a call to __tls_get_addr, find the symbol whose address
3823 // is to be taken and add it to the list. This will be used to
3824 // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3825 // We find the symbol by walking the chain to the CopyFromReg, walking
3826 // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3827 // pulling the symbol from that node.
3828 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3829 if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3830 assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3831 SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3832 SDValue TGTAddr = AddI->getOperand(1);
3833 assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3834 "Didn't find target global TLS address where we expected one");
3835 Ops.push_back(TGTAddr);
3836 CallOpc = PPCISD::CALL_TLS;
3839 // If this is a tail call add stack pointer delta.
3841 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3843 // Add argument registers to the end of the list so that they are known live
3845 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3846 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3847 RegsToPass[i].second.getValueType()));
3849 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
3851 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
3852 setUsesTOCBasePtr(DAG);
3853 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3860 bool isLocalCall(const SDValue &Callee)
3862 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3863 return !G->getGlobal()->isDeclaration() &&
3864 !G->getGlobal()->isWeakForLinker();
3869 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3870 CallingConv::ID CallConv, bool isVarArg,
3871 const SmallVectorImpl<ISD::InputArg> &Ins,
3872 SDLoc dl, SelectionDAG &DAG,
3873 SmallVectorImpl<SDValue> &InVals) const {
3875 SmallVector<CCValAssign, 16> RVLocs;
3876 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3878 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3880 // Copy all of the result registers out of their specified physreg.
3881 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3882 CCValAssign &VA = RVLocs[i];
3883 assert(VA.isRegLoc() && "Can only return in registers!");
3885 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3886 VA.getLocReg(), VA.getLocVT(), InFlag);
3887 Chain = Val.getValue(1);
3888 InFlag = Val.getValue(2);
3890 switch (VA.getLocInfo()) {
3891 default: llvm_unreachable("Unknown loc info!");
3892 case CCValAssign::Full: break;
3893 case CCValAssign::AExt:
3894 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3896 case CCValAssign::ZExt:
3897 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3898 DAG.getValueType(VA.getValVT()));
3899 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3901 case CCValAssign::SExt:
3902 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3903 DAG.getValueType(VA.getValVT()));
3904 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3908 InVals.push_back(Val);
3915 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3916 bool isTailCall, bool isVarArg, bool IsPatchPoint,
3918 SmallVector<std::pair<unsigned, SDValue>, 8>
3920 SDValue InFlag, SDValue Chain,
3921 SDValue CallSeqStart, SDValue &Callee,
3922 int SPDiff, unsigned NumBytes,
3923 const SmallVectorImpl<ISD::InputArg> &Ins,
3924 SmallVectorImpl<SDValue> &InVals,
3925 ImmutableCallSite *CS) const {
3927 bool isELFv2ABI = Subtarget.isELFv2ABI();
3928 std::vector<EVT> NodeTys;
3929 SmallVector<SDValue, 8> Ops;
3930 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
3931 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
3932 Ops, NodeTys, CS, Subtarget);
3934 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3935 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3936 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3938 // When performing tail call optimization the callee pops its arguments off
3939 // the stack. Account for this here so these bytes can be pushed back on in
3940 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3941 int BytesCalleePops =
3942 (CallConv == CallingConv::Fast &&
3943 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3945 // Add a register mask operand representing the call-preserved registers.
3946 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3947 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3948 assert(Mask && "Missing call preserved mask for calling convention");
3949 Ops.push_back(DAG.getRegisterMask(Mask));
3951 if (InFlag.getNode())
3952 Ops.push_back(InFlag);
3956 assert(((Callee.getOpcode() == ISD::Register &&
3957 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3958 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3959 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3960 isa<ConstantSDNode>(Callee)) &&
3961 "Expecting an global address, external symbol, absolute value or register");
3963 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3966 // Add a NOP immediately after the branch instruction when using the 64-bit
3967 // SVR4 ABI. At link time, if caller and callee are in a different module and
3968 // thus have a different TOC, the call will be replaced with a call to a stub
3969 // function which saves the current TOC, loads the TOC of the callee and
3970 // branches to the callee. The NOP will be replaced with a load instruction
3971 // which restores the TOC of the caller from the TOC save slot of the current
3972 // stack frame. If caller and callee belong to the same module (and have the
3973 // same TOC), the NOP will remain unchanged.
3975 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
3977 if (CallOpc == PPCISD::BCTRL) {
3978 // This is a call through a function pointer.
3979 // Restore the caller TOC from the save area into R2.
3980 // See PrepareCall() for more information about calls through function
3981 // pointers in the 64-bit SVR4 ABI.
3982 // We are using a target-specific load with r2 hard coded, because the
3983 // result of a target-independent load would never go directly into r2,
3984 // since r2 is a reserved register (which prevents the register allocator
3985 // from allocating it), resulting in an additional register being
3986 // allocated and an unnecessary move instruction being generated.
3987 CallOpc = PPCISD::BCTRL_LOAD_TOC;
3989 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3990 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3991 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3992 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3993 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3995 // The address needs to go after the chain input but before the flag (or
3996 // any other variadic arguments).
3997 Ops.insert(std::next(Ops.begin()), AddTOC);
3998 } else if ((CallOpc == PPCISD::CALL) &&
3999 (!isLocalCall(Callee) ||
4000 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4001 // Otherwise insert NOP for non-local calls.
4002 CallOpc = PPCISD::CALL_NOP;
4003 } else if (CallOpc == PPCISD::CALL_TLS)
4004 // For 64-bit SVR4, TLS calls are always non-local.
4005 CallOpc = PPCISD::CALL_NOP_TLS;
4008 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4009 InFlag = Chain.getValue(1);
4011 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4012 DAG.getIntPtrConstant(BytesCalleePops, true),
4015 InFlag = Chain.getValue(1);
4017 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4018 Ins, dl, DAG, InVals);
4022 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4023 SmallVectorImpl<SDValue> &InVals) const {
4024 SelectionDAG &DAG = CLI.DAG;
4026 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4027 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4028 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4029 SDValue Chain = CLI.Chain;
4030 SDValue Callee = CLI.Callee;
4031 bool &isTailCall = CLI.IsTailCall;
4032 CallingConv::ID CallConv = CLI.CallConv;
4033 bool isVarArg = CLI.IsVarArg;
4034 bool IsPatchPoint = CLI.IsPatchPoint;
4035 ImmutableCallSite *CS = CLI.CS;
4038 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4041 if (!isTailCall && CS && CS->isMustTailCall())
4042 report_fatal_error("failed to perform tail call elimination on a call "
4043 "site marked musttail");
4045 if (Subtarget.isSVR4ABI()) {
4046 if (Subtarget.isPPC64())
4047 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4048 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4049 dl, DAG, InVals, CS);
4051 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4052 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4053 dl, DAG, InVals, CS);
4056 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4057 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4058 dl, DAG, InVals, CS);
4062 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4063 CallingConv::ID CallConv, bool isVarArg,
4064 bool isTailCall, bool IsPatchPoint,
4065 const SmallVectorImpl<ISD::OutputArg> &Outs,
4066 const SmallVectorImpl<SDValue> &OutVals,
4067 const SmallVectorImpl<ISD::InputArg> &Ins,
4068 SDLoc dl, SelectionDAG &DAG,
4069 SmallVectorImpl<SDValue> &InVals,
4070 ImmutableCallSite *CS) const {
4071 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4072 // of the 32-bit SVR4 ABI stack frame layout.
4074 assert((CallConv == CallingConv::C ||
4075 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4077 unsigned PtrByteSize = 4;
4079 MachineFunction &MF = DAG.getMachineFunction();
4081 // Mark this function as potentially containing a function that contains a
4082 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4083 // and restoring the callers stack pointer in this functions epilog. This is
4084 // done because by tail calling the called function might overwrite the value
4085 // in this function's (MF) stack pointer stack slot 0(SP).
4086 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4087 CallConv == CallingConv::Fast)
4088 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4090 // Count how many bytes are to be pushed on the stack, including the linkage
4091 // area, parameter list area and the part of the local variable space which
4092 // contains copies of aggregates which are passed by value.
4094 // Assign locations to all of the outgoing arguments.
4095 SmallVector<CCValAssign, 16> ArgLocs;
4096 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4099 // Reserve space for the linkage area on the stack.
4100 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4104 // Handle fixed and variable vector arguments differently.
4105 // Fixed vector arguments go into registers as long as registers are
4106 // available. Variable vector arguments always go into memory.
4107 unsigned NumArgs = Outs.size();
4109 for (unsigned i = 0; i != NumArgs; ++i) {
4110 MVT ArgVT = Outs[i].VT;
4111 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4114 if (Outs[i].IsFixed) {
4115 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4118 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4124 errs() << "Call operand #" << i << " has unhandled type "
4125 << EVT(ArgVT).getEVTString() << "\n";
4127 llvm_unreachable(nullptr);
4131 // All arguments are treated the same.
4132 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4135 // Assign locations to all of the outgoing aggregate by value arguments.
4136 SmallVector<CCValAssign, 16> ByValArgLocs;
4137 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4138 ByValArgLocs, *DAG.getContext());
4140 // Reserve stack space for the allocations in CCInfo.
4141 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4143 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4145 // Size of the linkage area, parameter list area and the part of the local
4146 // space variable where copies of aggregates which are passed by value are
4148 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4150 // Calculate by how many bytes the stack has to be adjusted in case of tail
4151 // call optimization.
4152 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4154 // Adjust the stack pointer for the new arguments...
4155 // These operations are automatically eliminated by the prolog/epilog pass
4156 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4158 SDValue CallSeqStart = Chain;
4160 // Load the return address and frame pointer so it can be moved somewhere else
4163 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4166 // Set up a copy of the stack pointer for use loading and storing any
4167 // arguments that may not fit in the registers available for argument
4169 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4171 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4172 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4173 SmallVector<SDValue, 8> MemOpChains;
4175 bool seenFloatArg = false;
4176 // Walk the register/memloc assignments, inserting copies/loads.
4177 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4180 CCValAssign &VA = ArgLocs[i];
4181 SDValue Arg = OutVals[i];
4182 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4184 if (Flags.isByVal()) {
4185 // Argument is an aggregate which is passed by value, thus we need to
4186 // create a copy of it in the local variable space of the current stack
4187 // frame (which is the stack frame of the caller) and pass the address of
4188 // this copy to the callee.
4189 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4190 CCValAssign &ByValVA = ByValArgLocs[j++];
4191 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4193 // Memory reserved in the local variable space of the callers stack frame.
4194 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4196 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4197 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4199 // Create a copy of the argument in the local area of the current
4201 SDValue MemcpyCall =
4202 CreateCopyOfByValArgument(Arg, PtrOff,
4203 CallSeqStart.getNode()->getOperand(0),
4206 // This must go outside the CALLSEQ_START..END.
4207 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4208 CallSeqStart.getNode()->getOperand(1),
4210 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4211 NewCallSeqStart.getNode());
4212 Chain = CallSeqStart = NewCallSeqStart;
4214 // Pass the address of the aggregate copy on the stack either in a
4215 // physical register or in the parameter list area of the current stack
4216 // frame to the callee.
4220 if (VA.isRegLoc()) {
4221 if (Arg.getValueType() == MVT::i1)
4222 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4224 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4225 // Put argument in a physical register.
4226 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4228 // Put argument in the parameter list area of the current stack frame.
4229 assert(VA.isMemLoc());
4230 unsigned LocMemOffset = VA.getLocMemOffset();
4233 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4234 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4236 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4237 MachinePointerInfo(),
4240 // Calculate and remember argument location.
4241 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4247 if (!MemOpChains.empty())
4248 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4250 // Build a sequence of copy-to-reg nodes chained together with token chain
4251 // and flag operands which copy the outgoing args into the appropriate regs.
4253 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4254 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4255 RegsToPass[i].second, InFlag);
4256 InFlag = Chain.getValue(1);
4259 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4262 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4263 SDValue Ops[] = { Chain, InFlag };
4265 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4266 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4268 InFlag = Chain.getValue(1);
4272 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4273 false, TailCallArguments);
4275 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4276 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4277 NumBytes, Ins, InVals, CS);
4280 // Copy an argument into memory, being careful to do this outside the
4281 // call sequence for the call to which the argument belongs.
4283 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4284 SDValue CallSeqStart,
4285 ISD::ArgFlagsTy Flags,
4288 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4289 CallSeqStart.getNode()->getOperand(0),
4291 // The MEMCPY must go outside the CALLSEQ_START..END.
4292 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4293 CallSeqStart.getNode()->getOperand(1),
4295 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4296 NewCallSeqStart.getNode());
4297 return NewCallSeqStart;
4301 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4302 CallingConv::ID CallConv, bool isVarArg,
4303 bool isTailCall, bool IsPatchPoint,
4304 const SmallVectorImpl<ISD::OutputArg> &Outs,
4305 const SmallVectorImpl<SDValue> &OutVals,
4306 const SmallVectorImpl<ISD::InputArg> &Ins,
4307 SDLoc dl, SelectionDAG &DAG,
4308 SmallVectorImpl<SDValue> &InVals,
4309 ImmutableCallSite *CS) const {
4311 bool isELFv2ABI = Subtarget.isELFv2ABI();
4312 bool isLittleEndian = Subtarget.isLittleEndian();
4313 unsigned NumOps = Outs.size();
4315 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4316 unsigned PtrByteSize = 8;
4318 MachineFunction &MF = DAG.getMachineFunction();
4320 // Mark this function as potentially containing a function that contains a
4321 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4322 // and restoring the callers stack pointer in this functions epilog. This is
4323 // done because by tail calling the called function might overwrite the value
4324 // in this function's (MF) stack pointer stack slot 0(SP).
4325 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4326 CallConv == CallingConv::Fast)
4327 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4329 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4330 "fastcc not supported on varargs functions");
4332 // Count how many bytes are to be pushed on the stack, including the linkage
4333 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4334 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4335 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4336 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4338 unsigned NumBytes = LinkageSize;
4339 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4341 static const MCPhysReg GPR[] = {
4342 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4343 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4345 static const MCPhysReg *FPR = GetFPR();
4347 static const MCPhysReg VR[] = {
4348 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4349 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4351 static const MCPhysReg VSRH[] = {
4352 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4353 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4356 const unsigned NumGPRs = array_lengthof(GPR);
4357 const unsigned NumFPRs = 13;
4358 const unsigned NumVRs = array_lengthof(VR);
4360 // When using the fast calling convention, we don't provide backing for
4361 // arguments that will be in registers.
4362 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4364 // Add up all the space actually used.
4365 for (unsigned i = 0; i != NumOps; ++i) {
4366 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4367 EVT ArgVT = Outs[i].VT;
4368 EVT OrigVT = Outs[i].ArgVT;
4370 if (CallConv == CallingConv::Fast) {
4371 if (Flags.isByVal())
4372 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4374 switch (ArgVT.getSimpleVT().SimpleTy) {
4375 default: llvm_unreachable("Unexpected ValueType for argument!");
4379 if (++NumGPRsUsed <= NumGPRs)
4384 if (++NumFPRsUsed <= NumFPRs)
4393 if (++NumVRsUsed <= NumVRs)
4399 /* Respect alignment of argument on the stack. */
4401 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4402 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4404 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4405 if (Flags.isInConsecutiveRegsLast())
4406 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4409 unsigned NumBytesActuallyUsed = NumBytes;
4411 // The prolog code of the callee may store up to 8 GPR argument registers to
4412 // the stack, allowing va_start to index over them in memory if its varargs.
4413 // Because we cannot tell if this is needed on the caller side, we have to
4414 // conservatively assume that it is needed. As such, make sure we have at
4415 // least enough stack space for the caller to store the 8 GPRs.
4416 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4417 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4419 // Tail call needs the stack to be aligned.
4420 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4421 CallConv == CallingConv::Fast)
4422 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4424 // Calculate by how many bytes the stack has to be adjusted in case of tail
4425 // call optimization.
4426 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4428 // To protect arguments on the stack from being clobbered in a tail call,
4429 // force all the loads to happen before doing any other lowering.
4431 Chain = DAG.getStackArgumentTokenFactor(Chain);
4433 // Adjust the stack pointer for the new arguments...
4434 // These operations are automatically eliminated by the prolog/epilog pass
4435 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4437 SDValue CallSeqStart = Chain;
4439 // Load the return address and frame pointer so it can be move somewhere else
4442 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4445 // Set up a copy of the stack pointer for use loading and storing any
4446 // arguments that may not fit in the registers available for argument
4448 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4450 // Figure out which arguments are going to go in registers, and which in
4451 // memory. Also, if this is a vararg function, floating point operations
4452 // must be stored to our stack, and loaded into integer regs as well, if
4453 // any integer regs are available for argument passing.
4454 unsigned ArgOffset = LinkageSize;
4456 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4457 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4459 SmallVector<SDValue, 8> MemOpChains;
4460 for (unsigned i = 0; i != NumOps; ++i) {
4461 SDValue Arg = OutVals[i];
4462 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4463 EVT ArgVT = Outs[i].VT;
4464 EVT OrigVT = Outs[i].ArgVT;
4466 // PtrOff will be used to store the current argument to the stack if a
4467 // register cannot be found for it.
4470 // We re-align the argument offset for each argument, except when using the
4471 // fast calling convention, when we need to make sure we do that only when
4472 // we'll actually use a stack slot.
4473 auto ComputePtrOff = [&]() {
4474 /* Respect alignment of argument on the stack. */
4476 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4477 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4479 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4481 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4484 if (CallConv != CallingConv::Fast) {
4487 /* Compute GPR index associated with argument offset. */
4488 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4489 GPR_idx = std::min(GPR_idx, NumGPRs);
4492 // Promote integers to 64-bit values.
4493 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4494 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4495 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4496 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4499 // FIXME memcpy is used way more than necessary. Correctness first.
4500 // Note: "by value" is code for passing a structure by value, not
4502 if (Flags.isByVal()) {
4503 // Note: Size includes alignment padding, so
4504 // struct x { short a; char b; }
4505 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4506 // These are the proper values we need for right-justifying the
4507 // aggregate in a parameter register.
4508 unsigned Size = Flags.getByValSize();
4510 // An empty aggregate parameter takes up no storage and no
4515 if (CallConv == CallingConv::Fast)
4518 // All aggregates smaller than 8 bytes must be passed right-justified.
4519 if (Size==1 || Size==2 || Size==4) {
4520 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4521 if (GPR_idx != NumGPRs) {
4522 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4523 MachinePointerInfo(), VT,
4524 false, false, false, 0);
4525 MemOpChains.push_back(Load.getValue(1));
4526 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4528 ArgOffset += PtrByteSize;
4533 if (GPR_idx == NumGPRs && Size < 8) {
4534 SDValue AddPtr = PtrOff;
4535 if (!isLittleEndian) {
4536 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4537 PtrOff.getValueType());
4538 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4540 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4543 ArgOffset += PtrByteSize;
4546 // Copy entire object into memory. There are cases where gcc-generated
4547 // code assumes it is there, even if it could be put entirely into
4548 // registers. (This is not what the doc says.)
4550 // FIXME: The above statement is likely due to a misunderstanding of the
4551 // documents. All arguments must be copied into the parameter area BY
4552 // THE CALLEE in the event that the callee takes the address of any
4553 // formal argument. That has not yet been implemented. However, it is
4554 // reasonable to use the stack area as a staging area for the register
4557 // Skip this for small aggregates, as we will use the same slot for a
4558 // right-justified copy, below.
4560 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4564 // When a register is available, pass a small aggregate right-justified.
4565 if (Size < 8 && GPR_idx != NumGPRs) {
4566 // The easiest way to get this right-justified in a register
4567 // is to copy the structure into the rightmost portion of a
4568 // local variable slot, then load the whole slot into the
4570 // FIXME: The memcpy seems to produce pretty awful code for
4571 // small aggregates, particularly for packed ones.
4572 // FIXME: It would be preferable to use the slot in the
4573 // parameter save area instead of a new local variable.
4574 SDValue AddPtr = PtrOff;
4575 if (!isLittleEndian) {
4576 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4577 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4579 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4583 // Load the slot into the register.
4584 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4585 MachinePointerInfo(),
4586 false, false, false, 0);
4587 MemOpChains.push_back(Load.getValue(1));
4588 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4590 // Done with this argument.
4591 ArgOffset += PtrByteSize;
4595 // For aggregates larger than PtrByteSize, copy the pieces of the
4596 // object that fit into registers from the parameter save area.
4597 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4598 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4599 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4600 if (GPR_idx != NumGPRs) {
4601 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4602 MachinePointerInfo(),
4603 false, false, false, 0);
4604 MemOpChains.push_back(Load.getValue(1));
4605 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4606 ArgOffset += PtrByteSize;
4608 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4615 switch (Arg.getSimpleValueType().SimpleTy) {
4616 default: llvm_unreachable("Unexpected ValueType for argument!");
4620 // These can be scalar arguments or elements of an integer array type
4621 // passed directly. Clang may use those instead of "byval" aggregate
4622 // types to avoid forcing arguments to memory unnecessarily.
4623 if (GPR_idx != NumGPRs) {
4624 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4626 if (CallConv == CallingConv::Fast)
4629 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4630 true, isTailCall, false, MemOpChains,
4631 TailCallArguments, dl);
4632 if (CallConv == CallingConv::Fast)
4633 ArgOffset += PtrByteSize;
4635 if (CallConv != CallingConv::Fast)
4636 ArgOffset += PtrByteSize;
4640 // These can be scalar arguments or elements of a float array type
4641 // passed directly. The latter are used to implement ELFv2 homogenous
4642 // float aggregates.
4644 // Named arguments go into FPRs first, and once they overflow, the
4645 // remaining arguments go into GPRs and then the parameter save area.
4646 // Unnamed arguments for vararg functions always go to GPRs and
4647 // then the parameter save area. For now, put all arguments to vararg
4648 // routines always in both locations (FPR *and* GPR or stack slot).
4649 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4650 bool NeededLoad = false;
4652 // First load the argument into the next available FPR.
4653 if (FPR_idx != NumFPRs)
4654 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4656 // Next, load the argument into GPR or stack slot if needed.
4657 if (!NeedGPROrStack)
4659 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4660 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4661 // once we support fp <-> gpr moves.
4663 // In the non-vararg case, this can only ever happen in the
4664 // presence of f32 array types, since otherwise we never run
4665 // out of FPRs before running out of GPRs.
4668 // Double values are always passed in a single GPR.
4669 if (Arg.getValueType() != MVT::f32) {
4670 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4672 // Non-array float values are extended and passed in a GPR.
4673 } else if (!Flags.isInConsecutiveRegs()) {
4674 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4675 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4677 // If we have an array of floats, we collect every odd element
4678 // together with its predecessor into one GPR.
4679 } else if (ArgOffset % PtrByteSize != 0) {
4681 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4682 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4683 if (!isLittleEndian)
4685 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4687 // The final element, if even, goes into the first half of a GPR.
4688 } else if (Flags.isInConsecutiveRegsLast()) {
4689 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4690 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4691 if (!isLittleEndian)
4692 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4693 DAG.getConstant(32, MVT::i32));
4695 // Non-final even elements are skipped; they will be handled
4696 // together the with subsequent argument on the next go-around.
4700 if (ArgVal.getNode())
4701 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4703 if (CallConv == CallingConv::Fast)
4706 // Single-precision floating-point values are mapped to the
4707 // second (rightmost) word of the stack doubleword.
4708 if (Arg.getValueType() == MVT::f32 &&
4709 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4710 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4711 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4714 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4715 true, isTailCall, false, MemOpChains,
4716 TailCallArguments, dl);
4720 // When passing an array of floats, the array occupies consecutive
4721 // space in the argument area; only round up to the next doubleword
4722 // at the end of the array. Otherwise, each float takes 8 bytes.
4723 if (CallConv != CallingConv::Fast || NeededLoad) {
4724 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4725 Flags.isInConsecutiveRegs()) ? 4 : 8;
4726 if (Flags.isInConsecutiveRegsLast())
4727 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4737 // These can be scalar arguments or elements of a vector array type
4738 // passed directly. The latter are used to implement ELFv2 homogenous
4739 // vector aggregates.
4741 // For a varargs call, named arguments go into VRs or on the stack as
4742 // usual; unnamed arguments always go to the stack or the corresponding
4743 // GPRs when within range. For now, we always put the value in both
4744 // locations (or even all three).
4746 // We could elide this store in the case where the object fits
4747 // entirely in R registers. Maybe later.
4748 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4749 MachinePointerInfo(), false, false, 0);
4750 MemOpChains.push_back(Store);
4751 if (VR_idx != NumVRs) {
4752 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4753 MachinePointerInfo(),
4754 false, false, false, 0);
4755 MemOpChains.push_back(Load.getValue(1));
4757 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4758 Arg.getSimpleValueType() == MVT::v2i64) ?
4759 VSRH[VR_idx] : VR[VR_idx];
4762 RegsToPass.push_back(std::make_pair(VReg, Load));
4765 for (unsigned i=0; i<16; i+=PtrByteSize) {
4766 if (GPR_idx == NumGPRs)
4768 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4769 DAG.getConstant(i, PtrVT));
4770 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4771 false, false, false, 0);
4772 MemOpChains.push_back(Load.getValue(1));
4773 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4778 // Non-varargs Altivec params go into VRs or on the stack.
4779 if (VR_idx != NumVRs) {
4780 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4781 Arg.getSimpleValueType() == MVT::v2i64) ?
4782 VSRH[VR_idx] : VR[VR_idx];
4785 RegsToPass.push_back(std::make_pair(VReg, Arg));
4787 if (CallConv == CallingConv::Fast)
4790 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4791 true, isTailCall, true, MemOpChains,
4792 TailCallArguments, dl);
4793 if (CallConv == CallingConv::Fast)
4797 if (CallConv != CallingConv::Fast)
4803 assert(NumBytesActuallyUsed == ArgOffset);
4804 (void)NumBytesActuallyUsed;
4806 if (!MemOpChains.empty())
4807 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4809 // Check if this is an indirect call (MTCTR/BCTRL).
4810 // See PrepareCall() for more information about calls through function
4811 // pointers in the 64-bit SVR4 ABI.
4812 if (!isTailCall && !IsPatchPoint &&
4813 !isFunctionGlobalAddress(Callee) &&
4814 !isa<ExternalSymbolSDNode>(Callee)) {
4815 // Load r2 into a virtual register and store it to the TOC save area.
4816 setUsesTOCBasePtr(DAG);
4817 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4818 // TOC save area offset.
4819 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4820 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4821 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4822 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
4823 MachinePointerInfo::getStack(TOCSaveOffset),
4825 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4826 // This does not mean the MTCTR instruction must use R12; it's easier
4827 // to model this as an extra parameter, so do that.
4828 if (isELFv2ABI && !IsPatchPoint)
4829 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4832 // Build a sequence of copy-to-reg nodes chained together with token chain
4833 // and flag operands which copy the outgoing args into the appropriate regs.
4835 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4836 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4837 RegsToPass[i].second, InFlag);
4838 InFlag = Chain.getValue(1);
4842 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4843 FPOp, true, TailCallArguments);
4845 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4846 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4847 NumBytes, Ins, InVals, CS);
4851 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4852 CallingConv::ID CallConv, bool isVarArg,
4853 bool isTailCall, bool IsPatchPoint,
4854 const SmallVectorImpl<ISD::OutputArg> &Outs,
4855 const SmallVectorImpl<SDValue> &OutVals,
4856 const SmallVectorImpl<ISD::InputArg> &Ins,
4857 SDLoc dl, SelectionDAG &DAG,
4858 SmallVectorImpl<SDValue> &InVals,
4859 ImmutableCallSite *CS) const {
4861 unsigned NumOps = Outs.size();
4863 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4864 bool isPPC64 = PtrVT == MVT::i64;
4865 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4867 MachineFunction &MF = DAG.getMachineFunction();
4869 // Mark this function as potentially containing a function that contains a
4870 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4871 // and restoring the callers stack pointer in this functions epilog. This is
4872 // done because by tail calling the called function might overwrite the value
4873 // in this function's (MF) stack pointer stack slot 0(SP).
4874 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4875 CallConv == CallingConv::Fast)
4876 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4878 // Count how many bytes are to be pushed on the stack, including the linkage
4879 // area, and parameter passing area. We start with 24/48 bytes, which is
4880 // prereserved space for [SP][CR][LR][3 x unused].
4881 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4883 unsigned NumBytes = LinkageSize;
4885 // Add up all the space actually used.
4886 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4887 // they all go in registers, but we must reserve stack space for them for
4888 // possible use by the caller. In varargs or 64-bit calls, parameters are
4889 // assigned stack space in order, with padding so Altivec parameters are
4891 unsigned nAltivecParamsAtEnd = 0;
4892 for (unsigned i = 0; i != NumOps; ++i) {
4893 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4894 EVT ArgVT = Outs[i].VT;
4895 // Varargs Altivec parameters are padded to a 16 byte boundary.
4896 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4897 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4898 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4899 if (!isVarArg && !isPPC64) {
4900 // Non-varargs Altivec parameters go after all the non-Altivec
4901 // parameters; handle those later so we know how much padding we need.
4902 nAltivecParamsAtEnd++;
4905 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4906 NumBytes = ((NumBytes+15)/16)*16;
4908 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4911 // Allow for Altivec parameters at the end, if needed.
4912 if (nAltivecParamsAtEnd) {
4913 NumBytes = ((NumBytes+15)/16)*16;
4914 NumBytes += 16*nAltivecParamsAtEnd;
4917 // The prolog code of the callee may store up to 8 GPR argument registers to
4918 // the stack, allowing va_start to index over them in memory if its varargs.
4919 // Because we cannot tell if this is needed on the caller side, we have to
4920 // conservatively assume that it is needed. As such, make sure we have at
4921 // least enough stack space for the caller to store the 8 GPRs.
4922 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4924 // Tail call needs the stack to be aligned.
4925 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4926 CallConv == CallingConv::Fast)
4927 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4929 // Calculate by how many bytes the stack has to be adjusted in case of tail
4930 // call optimization.
4931 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4933 // To protect arguments on the stack from being clobbered in a tail call,
4934 // force all the loads to happen before doing any other lowering.
4936 Chain = DAG.getStackArgumentTokenFactor(Chain);
4938 // Adjust the stack pointer for the new arguments...
4939 // These operations are automatically eliminated by the prolog/epilog pass
4940 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4942 SDValue CallSeqStart = Chain;
4944 // Load the return address and frame pointer so it can be move somewhere else
4947 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4950 // Set up a copy of the stack pointer for use loading and storing any
4951 // arguments that may not fit in the registers available for argument
4955 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4957 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4959 // Figure out which arguments are going to go in registers, and which in
4960 // memory. Also, if this is a vararg function, floating point operations
4961 // must be stored to our stack, and loaded into integer regs as well, if
4962 // any integer regs are available for argument passing.
4963 unsigned ArgOffset = LinkageSize;
4964 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4966 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4967 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4968 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4970 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4971 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4972 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4974 static const MCPhysReg *FPR = GetFPR();
4976 static const MCPhysReg VR[] = {
4977 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4978 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4980 const unsigned NumGPRs = array_lengthof(GPR_32);
4981 const unsigned NumFPRs = 13;
4982 const unsigned NumVRs = array_lengthof(VR);
4984 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4986 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4987 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4989 SmallVector<SDValue, 8> MemOpChains;
4990 for (unsigned i = 0; i != NumOps; ++i) {
4991 SDValue Arg = OutVals[i];
4992 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4994 // PtrOff will be used to store the current argument to the stack if a
4995 // register cannot be found for it.
4998 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5000 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5002 // On PPC64, promote integers to 64-bit values.
5003 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5004 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5005 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5006 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5009 // FIXME memcpy is used way more than necessary. Correctness first.
5010 // Note: "by value" is code for passing a structure by value, not
5012 if (Flags.isByVal()) {
5013 unsigned Size = Flags.getByValSize();
5014 // Very small objects are passed right-justified. Everything else is
5015 // passed left-justified.
5016 if (Size==1 || Size==2) {
5017 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5018 if (GPR_idx != NumGPRs) {
5019 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5020 MachinePointerInfo(), VT,
5021 false, false, false, 0);
5022 MemOpChains.push_back(Load.getValue(1));
5023 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5025 ArgOffset += PtrByteSize;
5027 SDValue Const = DAG.getConstant(PtrByteSize - Size,
5028 PtrOff.getValueType());
5029 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5030 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5033 ArgOffset += PtrByteSize;
5037 // Copy entire object into memory. There are cases where gcc-generated
5038 // code assumes it is there, even if it could be put entirely into
5039 // registers. (This is not what the doc says.)
5040 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5044 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5045 // copy the pieces of the object that fit into registers from the
5046 // parameter save area.
5047 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5048 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5049 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5050 if (GPR_idx != NumGPRs) {
5051 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5052 MachinePointerInfo(),
5053 false, false, false, 0);
5054 MemOpChains.push_back(Load.getValue(1));
5055 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5056 ArgOffset += PtrByteSize;
5058 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5065 switch (Arg.getSimpleValueType().SimpleTy) {
5066 default: llvm_unreachable("Unexpected ValueType for argument!");
5070 if (GPR_idx != NumGPRs) {
5071 if (Arg.getValueType() == MVT::i1)
5072 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5074 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5076 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5077 isPPC64, isTailCall, false, MemOpChains,
5078 TailCallArguments, dl);
5080 ArgOffset += PtrByteSize;
5084 if (FPR_idx != NumFPRs) {
5085 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5088 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5089 MachinePointerInfo(), false, false, 0);
5090 MemOpChains.push_back(Store);
5092 // Float varargs are always shadowed in available integer registers
5093 if (GPR_idx != NumGPRs) {
5094 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5095 MachinePointerInfo(), false, false,
5097 MemOpChains.push_back(Load.getValue(1));
5098 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5100 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5101 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5102 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5103 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5104 MachinePointerInfo(),
5105 false, false, false, 0);
5106 MemOpChains.push_back(Load.getValue(1));
5107 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5110 // If we have any FPRs remaining, we may also have GPRs remaining.
5111 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5113 if (GPR_idx != NumGPRs)
5115 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5116 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5120 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5121 isPPC64, isTailCall, false, MemOpChains,
5122 TailCallArguments, dl);
5126 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5133 // These go aligned on the stack, or in the corresponding R registers
5134 // when within range. The Darwin PPC ABI doc claims they also go in
5135 // V registers; in fact gcc does this only for arguments that are
5136 // prototyped, not for those that match the ... We do it for all
5137 // arguments, seems to work.
5138 while (ArgOffset % 16 !=0) {
5139 ArgOffset += PtrByteSize;
5140 if (GPR_idx != NumGPRs)
5143 // We could elide this store in the case where the object fits
5144 // entirely in R registers. Maybe later.
5145 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5146 DAG.getConstant(ArgOffset, PtrVT));
5147 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5148 MachinePointerInfo(), false, false, 0);
5149 MemOpChains.push_back(Store);
5150 if (VR_idx != NumVRs) {
5151 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5152 MachinePointerInfo(),
5153 false, false, false, 0);
5154 MemOpChains.push_back(Load.getValue(1));
5155 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5158 for (unsigned i=0; i<16; i+=PtrByteSize) {
5159 if (GPR_idx == NumGPRs)
5161 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5162 DAG.getConstant(i, PtrVT));
5163 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5164 false, false, false, 0);
5165 MemOpChains.push_back(Load.getValue(1));
5166 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5171 // Non-varargs Altivec params generally go in registers, but have
5172 // stack space allocated at the end.
5173 if (VR_idx != NumVRs) {
5174 // Doesn't have GPR space allocated.
5175 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5176 } else if (nAltivecParamsAtEnd==0) {
5177 // We are emitting Altivec params in order.
5178 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5179 isPPC64, isTailCall, true, MemOpChains,
5180 TailCallArguments, dl);
5186 // If all Altivec parameters fit in registers, as they usually do,
5187 // they get stack space following the non-Altivec parameters. We
5188 // don't track this here because nobody below needs it.
5189 // If there are more Altivec parameters than fit in registers emit
5191 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5193 // Offset is aligned; skip 1st 12 params which go in V registers.
5194 ArgOffset = ((ArgOffset+15)/16)*16;
5196 for (unsigned i = 0; i != NumOps; ++i) {
5197 SDValue Arg = OutVals[i];
5198 EVT ArgType = Outs[i].VT;
5199 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5200 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5203 // We are emitting Altivec params in order.
5204 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5205 isPPC64, isTailCall, true, MemOpChains,
5206 TailCallArguments, dl);
5213 if (!MemOpChains.empty())
5214 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5216 // On Darwin, R12 must contain the address of an indirect callee. This does
5217 // not mean the MTCTR instruction must use R12; it's easier to model this as
5218 // an extra parameter, so do that.
5220 !isFunctionGlobalAddress(Callee) &&
5221 !isa<ExternalSymbolSDNode>(Callee) &&
5222 !isBLACompatibleAddress(Callee, DAG))
5223 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5224 PPC::R12), Callee));
5226 // Build a sequence of copy-to-reg nodes chained together with token chain
5227 // and flag operands which copy the outgoing args into the appropriate regs.
5229 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5230 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5231 RegsToPass[i].second, InFlag);
5232 InFlag = Chain.getValue(1);
5236 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5237 FPOp, true, TailCallArguments);
5239 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5240 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5241 NumBytes, Ins, InVals, CS);
5245 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5246 MachineFunction &MF, bool isVarArg,
5247 const SmallVectorImpl<ISD::OutputArg> &Outs,
5248 LLVMContext &Context) const {
5249 SmallVector<CCValAssign, 16> RVLocs;
5250 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5251 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5255 PPCTargetLowering::LowerReturn(SDValue Chain,
5256 CallingConv::ID CallConv, bool isVarArg,
5257 const SmallVectorImpl<ISD::OutputArg> &Outs,
5258 const SmallVectorImpl<SDValue> &OutVals,
5259 SDLoc dl, SelectionDAG &DAG) const {
5261 SmallVector<CCValAssign, 16> RVLocs;
5262 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5264 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5267 SmallVector<SDValue, 4> RetOps(1, Chain);
5269 // Copy the result values into the output registers.
5270 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5271 CCValAssign &VA = RVLocs[i];
5272 assert(VA.isRegLoc() && "Can only return in registers!");
5274 SDValue Arg = OutVals[i];
5276 switch (VA.getLocInfo()) {
5277 default: llvm_unreachable("Unknown loc info!");
5278 case CCValAssign::Full: break;
5279 case CCValAssign::AExt:
5280 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5282 case CCValAssign::ZExt:
5283 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5285 case CCValAssign::SExt:
5286 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5290 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5291 Flag = Chain.getValue(1);
5292 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5295 RetOps[0] = Chain; // Update chain.
5297 // Add the flag if we have it.
5299 RetOps.push_back(Flag);
5301 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5304 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5305 const PPCSubtarget &Subtarget) const {
5306 // When we pop the dynamic allocation we need to restore the SP link.
5309 // Get the corect type for pointers.
5310 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5312 // Construct the stack pointer operand.
5313 bool isPPC64 = Subtarget.isPPC64();
5314 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5315 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5317 // Get the operands for the STACKRESTORE.
5318 SDValue Chain = Op.getOperand(0);
5319 SDValue SaveSP = Op.getOperand(1);
5321 // Load the old link SP.
5322 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5323 MachinePointerInfo(),
5324 false, false, false, 0);
5326 // Restore the stack pointer.
5327 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5329 // Store the old link SP.
5330 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5337 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5338 MachineFunction &MF = DAG.getMachineFunction();
5339 bool isPPC64 = Subtarget.isPPC64();
5340 bool isDarwinABI = Subtarget.isDarwinABI();
5341 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5343 // Get current frame pointer save index. The users of this index will be
5344 // primarily DYNALLOC instructions.
5345 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5346 int RASI = FI->getReturnAddrSaveIndex();
5348 // If the frame pointer save index hasn't been defined yet.
5350 // Find out what the fix offset of the frame pointer save area.
5351 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5352 // Allocate the frame index for frame pointer save area.
5353 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5355 FI->setReturnAddrSaveIndex(RASI);
5357 return DAG.getFrameIndex(RASI, PtrVT);
5361 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5362 MachineFunction &MF = DAG.getMachineFunction();
5363 bool isPPC64 = Subtarget.isPPC64();
5364 bool isDarwinABI = Subtarget.isDarwinABI();
5365 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5367 // Get current frame pointer save index. The users of this index will be
5368 // primarily DYNALLOC instructions.
5369 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5370 int FPSI = FI->getFramePointerSaveIndex();
5372 // If the frame pointer save index hasn't been defined yet.
5374 // Find out what the fix offset of the frame pointer save area.
5375 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5378 // Allocate the frame index for frame pointer save area.
5379 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5381 FI->setFramePointerSaveIndex(FPSI);
5383 return DAG.getFrameIndex(FPSI, PtrVT);
5386 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5388 const PPCSubtarget &Subtarget) const {
5390 SDValue Chain = Op.getOperand(0);
5391 SDValue Size = Op.getOperand(1);
5394 // Get the corect type for pointers.
5395 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5397 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5398 DAG.getConstant(0, PtrVT), Size);
5399 // Construct a node for the frame pointer save index.
5400 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5401 // Build a DYNALLOC node.
5402 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5403 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5404 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5407 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5408 SelectionDAG &DAG) const {
5410 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5411 DAG.getVTList(MVT::i32, MVT::Other),
5412 Op.getOperand(0), Op.getOperand(1));
5415 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5416 SelectionDAG &DAG) const {
5418 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5419 Op.getOperand(0), Op.getOperand(1));
5422 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5423 assert(Op.getValueType() == MVT::i1 &&
5424 "Custom lowering only for i1 loads");
5426 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5429 LoadSDNode *LD = cast<LoadSDNode>(Op);
5431 SDValue Chain = LD->getChain();
5432 SDValue BasePtr = LD->getBasePtr();
5433 MachineMemOperand *MMO = LD->getMemOperand();
5435 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5436 BasePtr, MVT::i8, MMO);
5437 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5439 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5440 return DAG.getMergeValues(Ops, dl);
5443 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5444 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5445 "Custom lowering only for i1 stores");
5447 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5450 StoreSDNode *ST = cast<StoreSDNode>(Op);
5452 SDValue Chain = ST->getChain();
5453 SDValue BasePtr = ST->getBasePtr();
5454 SDValue Value = ST->getValue();
5455 MachineMemOperand *MMO = ST->getMemOperand();
5457 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5458 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5461 // FIXME: Remove this once the ANDI glue bug is fixed:
5462 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5463 assert(Op.getValueType() == MVT::i1 &&
5464 "Custom lowering only for i1 results");
5467 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5471 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5473 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5474 // Not FP? Not a fsel.
5475 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5476 !Op.getOperand(2).getValueType().isFloatingPoint())
5479 // We might be able to do better than this under some circumstances, but in
5480 // general, fsel-based lowering of select is a finite-math-only optimization.
5481 // For more information, see section F.3 of the 2.06 ISA specification.
5482 if (!DAG.getTarget().Options.NoInfsFPMath ||
5483 !DAG.getTarget().Options.NoNaNsFPMath)
5486 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5488 EVT ResVT = Op.getValueType();
5489 EVT CmpVT = Op.getOperand(0).getValueType();
5490 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5491 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5494 // If the RHS of the comparison is a 0.0, we don't need to do the
5495 // subtraction at all.
5497 if (isFloatingPointZero(RHS))
5499 default: break; // SETUO etc aren't handled by fsel.
5503 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5504 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5505 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5506 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5507 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5508 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5509 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5512 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5515 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5516 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5517 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5520 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5523 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5524 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5525 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5526 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5531 default: break; // SETUO etc aren't handled by fsel.
5535 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5536 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5537 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5538 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5539 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5540 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5541 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5542 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5545 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5546 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5547 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5548 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5551 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5552 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5553 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5554 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5557 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5558 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5559 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5560 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5563 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5564 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5565 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5566 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5571 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5574 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5575 SDValue Src = Op.getOperand(0);
5576 if (Src.getValueType() == MVT::f32)
5577 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5580 switch (Op.getSimpleValueType().SimpleTy) {
5581 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5584 Op.getOpcode() == ISD::FP_TO_SINT
5586 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5590 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5591 "i64 FP_TO_UINT is supported only with FPCVT");
5592 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5598 // Convert the FP value to an int value through memory.
5599 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5600 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5601 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5602 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5603 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5605 // Emit a store to the stack slot.
5608 MachineFunction &MF = DAG.getMachineFunction();
5609 MachineMemOperand *MMO =
5610 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5611 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5612 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5613 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5615 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5616 MPI, false, false, 0);
5618 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5620 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5621 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5622 DAG.getConstant(4, FIPtr.getValueType()));
5623 MPI = MPI.getWithOffset(4);
5631 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5634 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5636 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5637 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5641 // We're trying to insert a regular store, S, and then a load, L. If the
5642 // incoming value, O, is a load, we might just be able to have our load use the
5643 // address used by O. However, we don't know if anything else will store to
5644 // that address before we can load from it. To prevent this situation, we need
5645 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5646 // the same chain operand as O, we create a token factor from the chain results
5647 // of O and L, and we replace all uses of O's chain result with that token
5648 // factor (see spliceIntoChain below for this last part).
5649 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5652 ISD::LoadExtType ET) const {
5654 if (ET == ISD::NON_EXTLOAD &&
5655 (Op.getOpcode() == ISD::FP_TO_UINT ||
5656 Op.getOpcode() == ISD::FP_TO_SINT) &&
5657 isOperationLegalOrCustom(Op.getOpcode(),
5658 Op.getOperand(0).getValueType())) {
5660 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5664 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5665 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5666 LD->isNonTemporal())
5668 if (LD->getMemoryVT() != MemVT)
5671 RLI.Ptr = LD->getBasePtr();
5672 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5673 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5674 "Non-pre-inc AM on PPC?");
5675 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5679 RLI.Chain = LD->getChain();
5680 RLI.MPI = LD->getPointerInfo();
5681 RLI.IsInvariant = LD->isInvariant();
5682 RLI.Alignment = LD->getAlignment();
5683 RLI.AAInfo = LD->getAAInfo();
5684 RLI.Ranges = LD->getRanges();
5686 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5690 // Given the head of the old chain, ResChain, insert a token factor containing
5691 // it and NewResChain, and make users of ResChain now be users of that token
5693 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5694 SDValue NewResChain,
5695 SelectionDAG &DAG) const {
5699 SDLoc dl(NewResChain);
5701 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5702 NewResChain, DAG.getUNDEF(MVT::Other));
5703 assert(TF.getNode() != NewResChain.getNode() &&
5704 "A new TF really is required here");
5706 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5707 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5710 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5711 SelectionDAG &DAG) const {
5713 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5714 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5717 if (Op.getOperand(0).getValueType() == MVT::i1)
5718 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5719 DAG.getConstantFP(1.0, Op.getValueType()),
5720 DAG.getConstantFP(0.0, Op.getValueType()));
5722 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5723 "UINT_TO_FP is supported only with FPCVT");
5725 // If we have FCFIDS, then use it when converting to single-precision.
5726 // Otherwise, convert to double-precision and then round.
5727 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5728 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
5730 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
5732 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5736 if (Op.getOperand(0).getValueType() == MVT::i64) {
5737 SDValue SINT = Op.getOperand(0);
5738 // When converting to single-precision, we actually need to convert
5739 // to double-precision first and then round to single-precision.
5740 // To avoid double-rounding effects during that operation, we have
5741 // to prepare the input operand. Bits that might be truncated when
5742 // converting to double-precision are replaced by a bit that won't
5743 // be lost at this stage, but is below the single-precision rounding
5746 // However, if -enable-unsafe-fp-math is in effect, accept double
5747 // rounding to avoid the extra overhead.
5748 if (Op.getValueType() == MVT::f32 &&
5749 !Subtarget.hasFPCVT() &&
5750 !DAG.getTarget().Options.UnsafeFPMath) {
5752 // Twiddle input to make sure the low 11 bits are zero. (If this
5753 // is the case, we are guaranteed the value will fit into the 53 bit
5754 // mantissa of an IEEE double-precision value without rounding.)
5755 // If any of those low 11 bits were not zero originally, make sure
5756 // bit 12 (value 2048) is set instead, so that the final rounding
5757 // to single-precision gets the correct result.
5758 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5759 SINT, DAG.getConstant(2047, MVT::i64));
5760 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5761 Round, DAG.getConstant(2047, MVT::i64));
5762 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5763 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5764 Round, DAG.getConstant(-2048, MVT::i64));
5766 // However, we cannot use that value unconditionally: if the magnitude
5767 // of the input value is small, the bit-twiddling we did above might
5768 // end up visibly changing the output. Fortunately, in that case, we
5769 // don't need to twiddle bits since the original input will convert
5770 // exactly to double-precision floating-point already. Therefore,
5771 // construct a conditional to use the original value if the top 11
5772 // bits are all sign-bit copies, and use the rounded value computed
5774 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5775 SINT, DAG.getConstant(53, MVT::i32));
5776 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5777 Cond, DAG.getConstant(1, MVT::i64));
5778 Cond = DAG.getSetCC(dl, MVT::i32,
5779 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5781 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5787 MachineFunction &MF = DAG.getMachineFunction();
5788 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5789 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5790 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5792 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5793 } else if (Subtarget.hasLFIWAX() &&
5794 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5795 MachineMemOperand *MMO =
5796 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5797 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5798 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5799 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5800 DAG.getVTList(MVT::f64, MVT::Other),
5801 Ops, MVT::i32, MMO);
5802 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5803 } else if (Subtarget.hasFPCVT() &&
5804 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5805 MachineMemOperand *MMO =
5806 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5807 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5808 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5809 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5810 DAG.getVTList(MVT::f64, MVT::Other),
5811 Ops, MVT::i32, MMO);
5812 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5813 } else if (((Subtarget.hasLFIWAX() &&
5814 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5815 (Subtarget.hasFPCVT() &&
5816 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5817 SINT.getOperand(0).getValueType() == MVT::i32) {
5818 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5819 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5821 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5822 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5825 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5826 MachinePointerInfo::getFixedStack(FrameIdx),
5829 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5830 "Expected an i32 store");
5834 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5837 MachineMemOperand *MMO =
5838 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5839 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5840 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5841 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5842 PPCISD::LFIWZX : PPCISD::LFIWAX,
5843 dl, DAG.getVTList(MVT::f64, MVT::Other),
5844 Ops, MVT::i32, MMO);
5846 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5848 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5850 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5851 FP = DAG.getNode(ISD::FP_ROUND, dl,
5852 MVT::f32, FP, DAG.getIntPtrConstant(0));
5856 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5857 "Unhandled INT_TO_FP type in custom expander!");
5858 // Since we only generate this in 64-bit mode, we can take advantage of
5859 // 64-bit registers. In particular, sign extend the input value into the
5860 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5861 // then lfd it and fcfid it.
5862 MachineFunction &MF = DAG.getMachineFunction();
5863 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5864 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5867 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5870 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5872 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5873 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5875 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5876 MachinePointerInfo::getFixedStack(FrameIdx),
5879 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5880 "Expected an i32 store");
5884 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5888 MachineMemOperand *MMO =
5889 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5890 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5891 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5892 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5893 PPCISD::LFIWZX : PPCISD::LFIWAX,
5894 dl, DAG.getVTList(MVT::f64, MVT::Other),
5895 Ops, MVT::i32, MMO);
5897 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5899 assert(Subtarget.isPPC64() &&
5900 "i32->FP without LFIWAX supported only on PPC64");
5902 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5903 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5905 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5908 // STD the extended value into the stack slot.
5909 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5910 MachinePointerInfo::getFixedStack(FrameIdx),
5913 // Load the value as a double.
5914 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5915 MachinePointerInfo::getFixedStack(FrameIdx),
5916 false, false, false, 0);
5919 // FCFID it and return it.
5920 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5921 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5922 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5926 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5927 SelectionDAG &DAG) const {
5930 The rounding mode is in bits 30:31 of FPSR, and has the following
5937 FLT_ROUNDS, on the other hand, expects the following:
5944 To perform the conversion, we do:
5945 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5948 MachineFunction &MF = DAG.getMachineFunction();
5949 EVT VT = Op.getValueType();
5950 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5952 // Save FP Control Word to register
5954 MVT::f64, // return register
5955 MVT::Glue // unused in this context
5957 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5959 // Save FP register to stack slot
5960 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5961 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5962 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5963 StackSlot, MachinePointerInfo(), false, false,0);
5965 // Load FP Control Word from low 32 bits of stack slot.
5966 SDValue Four = DAG.getConstant(4, PtrVT);
5967 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5968 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5969 false, false, false, 0);
5971 // Transform as necessary
5973 DAG.getNode(ISD::AND, dl, MVT::i32,
5974 CWD, DAG.getConstant(3, MVT::i32));
5976 DAG.getNode(ISD::SRL, dl, MVT::i32,
5977 DAG.getNode(ISD::AND, dl, MVT::i32,
5978 DAG.getNode(ISD::XOR, dl, MVT::i32,
5979 CWD, DAG.getConstant(3, MVT::i32)),
5980 DAG.getConstant(3, MVT::i32)),
5981 DAG.getConstant(1, MVT::i32));
5984 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5986 return DAG.getNode((VT.getSizeInBits() < 16 ?
5987 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5990 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5991 EVT VT = Op.getValueType();
5992 unsigned BitWidth = VT.getSizeInBits();
5994 assert(Op.getNumOperands() == 3 &&
5995 VT == Op.getOperand(1).getValueType() &&
5998 // Expand into a bunch of logical ops. Note that these ops
5999 // depend on the PPC behavior for oversized shift amounts.
6000 SDValue Lo = Op.getOperand(0);
6001 SDValue Hi = Op.getOperand(1);
6002 SDValue Amt = Op.getOperand(2);
6003 EVT AmtVT = Amt.getValueType();
6005 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6006 DAG.getConstant(BitWidth, AmtVT), Amt);
6007 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6008 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6009 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6010 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6011 DAG.getConstant(-BitWidth, AmtVT));
6012 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6013 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6014 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6015 SDValue OutOps[] = { OutLo, OutHi };
6016 return DAG.getMergeValues(OutOps, dl);
6019 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6020 EVT VT = Op.getValueType();
6022 unsigned BitWidth = VT.getSizeInBits();
6023 assert(Op.getNumOperands() == 3 &&
6024 VT == Op.getOperand(1).getValueType() &&
6027 // Expand into a bunch of logical ops. Note that these ops
6028 // depend on the PPC behavior for oversized shift amounts.
6029 SDValue Lo = Op.getOperand(0);
6030 SDValue Hi = Op.getOperand(1);
6031 SDValue Amt = Op.getOperand(2);
6032 EVT AmtVT = Amt.getValueType();
6034 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6035 DAG.getConstant(BitWidth, AmtVT), Amt);
6036 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6037 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6038 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6039 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6040 DAG.getConstant(-BitWidth, AmtVT));
6041 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6042 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6043 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6044 SDValue OutOps[] = { OutLo, OutHi };
6045 return DAG.getMergeValues(OutOps, dl);
6048 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6050 EVT VT = Op.getValueType();
6051 unsigned BitWidth = VT.getSizeInBits();
6052 assert(Op.getNumOperands() == 3 &&
6053 VT == Op.getOperand(1).getValueType() &&
6056 // Expand into a bunch of logical ops, followed by a select_cc.
6057 SDValue Lo = Op.getOperand(0);
6058 SDValue Hi = Op.getOperand(1);
6059 SDValue Amt = Op.getOperand(2);
6060 EVT AmtVT = Amt.getValueType();
6062 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6063 DAG.getConstant(BitWidth, AmtVT), Amt);
6064 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6065 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6066 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6067 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6068 DAG.getConstant(-BitWidth, AmtVT));
6069 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6070 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6071 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6072 Tmp4, Tmp6, ISD::SETLE);
6073 SDValue OutOps[] = { OutLo, OutHi };
6074 return DAG.getMergeValues(OutOps, dl);
6077 //===----------------------------------------------------------------------===//
6078 // Vector related lowering.
6081 /// BuildSplatI - Build a canonical splati of Val with an element size of
6082 /// SplatSize. Cast the result to VT.
6083 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6084 SelectionDAG &DAG, SDLoc dl) {
6085 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6087 static const EVT VTys[] = { // canonical VT to use for each size.
6088 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6091 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6093 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6097 EVT CanonicalVT = VTys[SplatSize-1];
6099 // Build a canonical splat for this value.
6100 SDValue Elt = DAG.getConstant(Val, MVT::i32);
6101 SmallVector<SDValue, 8> Ops;
6102 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6103 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6104 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6107 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6108 /// specified intrinsic ID.
6109 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6110 SelectionDAG &DAG, SDLoc dl,
6111 EVT DestVT = MVT::Other) {
6112 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6113 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6114 DAG.getConstant(IID, MVT::i32), Op);
6117 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6118 /// specified intrinsic ID.
6119 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6120 SelectionDAG &DAG, SDLoc dl,
6121 EVT DestVT = MVT::Other) {
6122 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6123 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6124 DAG.getConstant(IID, MVT::i32), LHS, RHS);
6127 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6128 /// specified intrinsic ID.
6129 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6130 SDValue Op2, SelectionDAG &DAG,
6131 SDLoc dl, EVT DestVT = MVT::Other) {
6132 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6133 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6134 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6138 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6139 /// amount. The result has the specified value type.
6140 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6141 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6142 // Force LHS/RHS to be the right type.
6143 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6144 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6147 for (unsigned i = 0; i != 16; ++i)
6149 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6150 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6153 // If this is a case we can't handle, return null and let the default
6154 // expansion code take care of it. If we CAN select this case, and if it
6155 // selects to a single instruction, return Op. Otherwise, if we can codegen
6156 // this case more efficiently than a constant pool load, lower it to the
6157 // sequence of ops that should be used.
6158 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6159 SelectionDAG &DAG) const {
6161 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6162 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6164 // Check if this is a splat of a constant value.
6165 APInt APSplatBits, APSplatUndef;
6166 unsigned SplatBitSize;
6168 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6169 HasAnyUndefs, 0, true) || SplatBitSize > 32)
6172 unsigned SplatBits = APSplatBits.getZExtValue();
6173 unsigned SplatUndef = APSplatUndef.getZExtValue();
6174 unsigned SplatSize = SplatBitSize / 8;
6176 // First, handle single instruction cases.
6179 if (SplatBits == 0) {
6180 // Canonicalize all zero vectors to be v4i32.
6181 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6182 SDValue Z = DAG.getConstant(0, MVT::i32);
6183 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6184 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6189 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6190 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6192 if (SextVal >= -16 && SextVal <= 15)
6193 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6196 // Two instruction sequences.
6198 // If this value is in the range [-32,30] and is even, use:
6199 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6200 // If this value is in the range [17,31] and is odd, use:
6201 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6202 // If this value is in the range [-31,-17] and is odd, use:
6203 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6204 // Note the last two are three-instruction sequences.
6205 if (SextVal >= -32 && SextVal <= 31) {
6206 // To avoid having these optimizations undone by constant folding,
6207 // we convert to a pseudo that will be expanded later into one of
6209 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6210 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6211 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6212 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6213 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6214 if (VT == Op.getValueType())
6217 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6220 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6221 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6223 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6224 // Make -1 and vspltisw -1:
6225 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6227 // Make the VSLW intrinsic, computing 0x8000_0000.
6228 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6231 // xor by OnesV to invert it.
6232 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6233 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6236 // The remaining cases assume either big endian element order or
6237 // a splat-size that equates to the element size of the vector
6238 // to be built. An example that doesn't work for little endian is
6239 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6240 // and a vector element size of 16 bits. The code below will
6241 // produce the vector in big endian element order, which for little
6242 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6244 // For now, just avoid these optimizations in that case.
6245 // FIXME: Develop correct optimizations for LE with mismatched
6246 // splat and element sizes.
6248 if (Subtarget.isLittleEndian() &&
6249 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6252 // Check to see if this is a wide variety of vsplti*, binop self cases.
6253 static const signed char SplatCsts[] = {
6254 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6255 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6258 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6259 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6260 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6261 int i = SplatCsts[idx];
6263 // Figure out what shift amount will be used by altivec if shifted by i in
6265 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6267 // vsplti + shl self.
6268 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6269 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6270 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6271 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6272 Intrinsic::ppc_altivec_vslw
6274 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6275 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6278 // vsplti + srl self.
6279 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6280 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6281 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6282 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6283 Intrinsic::ppc_altivec_vsrw
6285 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6286 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6289 // vsplti + sra self.
6290 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6291 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6292 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6293 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6294 Intrinsic::ppc_altivec_vsraw
6296 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6297 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6300 // vsplti + rol self.
6301 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6302 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6303 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6304 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6305 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6306 Intrinsic::ppc_altivec_vrlw
6308 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6309 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6312 // t = vsplti c, result = vsldoi t, t, 1
6313 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6314 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6315 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6317 // t = vsplti c, result = vsldoi t, t, 2
6318 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6319 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6320 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6322 // t = vsplti c, result = vsldoi t, t, 3
6323 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6324 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6325 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6332 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6333 /// the specified operations to build the shuffle.
6334 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6335 SDValue RHS, SelectionDAG &DAG,
6337 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6338 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6339 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6342 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6354 if (OpNum == OP_COPY) {
6355 if (LHSID == (1*9+2)*9+3) return LHS;
6356 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6360 SDValue OpLHS, OpRHS;
6361 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6362 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6366 default: llvm_unreachable("Unknown i32 permute!");
6368 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6369 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6370 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6371 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6374 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6375 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6376 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6377 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6380 for (unsigned i = 0; i != 16; ++i)
6381 ShufIdxs[i] = (i&3)+0;
6384 for (unsigned i = 0; i != 16; ++i)
6385 ShufIdxs[i] = (i&3)+4;
6388 for (unsigned i = 0; i != 16; ++i)
6389 ShufIdxs[i] = (i&3)+8;
6392 for (unsigned i = 0; i != 16; ++i)
6393 ShufIdxs[i] = (i&3)+12;
6396 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6398 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6400 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6402 EVT VT = OpLHS.getValueType();
6403 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6404 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6405 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6406 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6409 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6410 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6411 /// return the code it can be lowered into. Worst case, it can always be
6412 /// lowered into a vperm.
6413 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6414 SelectionDAG &DAG) const {
6416 SDValue V1 = Op.getOperand(0);
6417 SDValue V2 = Op.getOperand(1);
6418 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6419 EVT VT = Op.getValueType();
6420 bool isLittleEndian = Subtarget.isLittleEndian();
6422 // Cases that are handled by instructions that take permute immediates
6423 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6424 // selected by the instruction selector.
6425 if (V2.getOpcode() == ISD::UNDEF) {
6426 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6427 PPC::isSplatShuffleMask(SVOp, 2) ||
6428 PPC::isSplatShuffleMask(SVOp, 4) ||
6429 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6430 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6431 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6432 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6433 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6434 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6435 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6436 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6437 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6442 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6443 // and produce a fixed permutation. If any of these match, do not lower to
6445 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6446 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6447 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6448 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6449 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6450 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6451 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6452 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6453 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6454 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6457 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6458 // perfect shuffle table to emit an optimal matching sequence.
6459 ArrayRef<int> PermMask = SVOp->getMask();
6461 unsigned PFIndexes[4];
6462 bool isFourElementShuffle = true;
6463 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6464 unsigned EltNo = 8; // Start out undef.
6465 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6466 if (PermMask[i*4+j] < 0)
6467 continue; // Undef, ignore it.
6469 unsigned ByteSource = PermMask[i*4+j];
6470 if ((ByteSource & 3) != j) {
6471 isFourElementShuffle = false;
6476 EltNo = ByteSource/4;
6477 } else if (EltNo != ByteSource/4) {
6478 isFourElementShuffle = false;
6482 PFIndexes[i] = EltNo;
6485 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6486 // perfect shuffle vector to determine if it is cost effective to do this as
6487 // discrete instructions, or whether we should use a vperm.
6488 // For now, we skip this for little endian until such time as we have a
6489 // little-endian perfect shuffle table.
6490 if (isFourElementShuffle && !isLittleEndian) {
6491 // Compute the index in the perfect shuffle table.
6492 unsigned PFTableIndex =
6493 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6495 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6496 unsigned Cost = (PFEntry >> 30);
6498 // Determining when to avoid vperm is tricky. Many things affect the cost
6499 // of vperm, particularly how many times the perm mask needs to be computed.
6500 // For example, if the perm mask can be hoisted out of a loop or is already
6501 // used (perhaps because there are multiple permutes with the same shuffle
6502 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6503 // the loop requires an extra register.
6505 // As a compromise, we only emit discrete instructions if the shuffle can be
6506 // generated in 3 or fewer operations. When we have loop information
6507 // available, if this block is within a loop, we should avoid using vperm
6508 // for 3-operation perms and use a constant pool load instead.
6510 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6513 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6514 // vector that will get spilled to the constant pool.
6515 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6517 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6518 // that it is in input element units, not in bytes. Convert now.
6520 // For little endian, the order of the input vectors is reversed, and
6521 // the permutation mask is complemented with respect to 31. This is
6522 // necessary to produce proper semantics with the big-endian-biased vperm
6524 EVT EltVT = V1.getValueType().getVectorElementType();
6525 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6527 SmallVector<SDValue, 16> ResultMask;
6528 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6529 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6531 for (unsigned j = 0; j != BytesPerElement; ++j)
6533 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6536 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6540 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6543 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6546 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6550 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6551 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6552 /// information about the intrinsic.
6553 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6555 unsigned IntrinsicID =
6556 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6559 switch (IntrinsicID) {
6560 default: return false;
6561 // Comparison predicates.
6562 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6563 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6564 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6565 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6566 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6567 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6568 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6569 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6570 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6571 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6572 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6573 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6574 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6576 // Normal Comparisons.
6577 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6578 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6579 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6580 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6581 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6582 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6583 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6584 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6585 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6586 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6587 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6588 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6589 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6594 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6595 /// lower, do it, otherwise return null.
6596 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6597 SelectionDAG &DAG) const {
6598 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6599 // opcode number of the comparison.
6603 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6604 return SDValue(); // Don't custom lower most intrinsics.
6606 // If this is a non-dot comparison, make the VCMP node and we are done.
6608 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6609 Op.getOperand(1), Op.getOperand(2),
6610 DAG.getConstant(CompareOpc, MVT::i32));
6611 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6614 // Create the PPCISD altivec 'dot' comparison node.
6616 Op.getOperand(2), // LHS
6617 Op.getOperand(3), // RHS
6618 DAG.getConstant(CompareOpc, MVT::i32)
6620 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6621 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6623 // Now that we have the comparison, emit a copy from the CR to a GPR.
6624 // This is flagged to the above dot comparison.
6625 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6626 DAG.getRegister(PPC::CR6, MVT::i32),
6627 CompNode.getValue(1));
6629 // Unpack the result based on how the target uses it.
6630 unsigned BitNo; // Bit # of CR6.
6631 bool InvertBit; // Invert result?
6632 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6633 default: // Can't happen, don't crash on invalid number though.
6634 case 0: // Return the value of the EQ bit of CR6.
6635 BitNo = 0; InvertBit = false;
6637 case 1: // Return the inverted value of the EQ bit of CR6.
6638 BitNo = 0; InvertBit = true;
6640 case 2: // Return the value of the LT bit of CR6.
6641 BitNo = 2; InvertBit = false;
6643 case 3: // Return the inverted value of the LT bit of CR6.
6644 BitNo = 2; InvertBit = true;
6648 // Shift the bit into the low position.
6649 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6650 DAG.getConstant(8-(3-BitNo), MVT::i32));
6652 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6653 DAG.getConstant(1, MVT::i32));
6655 // If we are supposed to, toggle the bit.
6657 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6658 DAG.getConstant(1, MVT::i32));
6662 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6663 SelectionDAG &DAG) const {
6665 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6666 // instructions), but for smaller types, we need to first extend up to v2i32
6667 // before doing going farther.
6668 if (Op.getValueType() == MVT::v2i64) {
6669 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6670 if (ExtVT != MVT::v2i32) {
6671 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6672 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6673 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6674 ExtVT.getVectorElementType(), 4)));
6675 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6676 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6677 DAG.getValueType(MVT::v2i32));
6686 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6687 SelectionDAG &DAG) const {
6689 // Create a stack slot that is 16-byte aligned.
6690 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6691 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6692 EVT PtrVT = getPointerTy();
6693 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6695 // Store the input value into Value#0 of the stack slot.
6696 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6697 Op.getOperand(0), FIdx, MachinePointerInfo(),
6700 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6701 false, false, false, 0);
6704 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6706 if (Op.getValueType() == MVT::v4i32) {
6707 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6709 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6710 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6712 SDValue RHSSwap = // = vrlw RHS, 16
6713 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6715 // Shrinkify inputs to v8i16.
6716 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6717 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6718 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6720 // Low parts multiplied together, generating 32-bit results (we ignore the
6722 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6723 LHS, RHS, DAG, dl, MVT::v4i32);
6725 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6726 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6727 // Shift the high parts up 16 bits.
6728 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6730 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6731 } else if (Op.getValueType() == MVT::v8i16) {
6732 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6734 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6736 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6737 LHS, RHS, Zero, DAG, dl);
6738 } else if (Op.getValueType() == MVT::v16i8) {
6739 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6740 bool isLittleEndian = Subtarget.isLittleEndian();
6742 // Multiply the even 8-bit parts, producing 16-bit sums.
6743 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6744 LHS, RHS, DAG, dl, MVT::v8i16);
6745 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6747 // Multiply the odd 8-bit parts, producing 16-bit sums.
6748 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6749 LHS, RHS, DAG, dl, MVT::v8i16);
6750 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6752 // Merge the results together. Because vmuleub and vmuloub are
6753 // instructions with a big-endian bias, we must reverse the
6754 // element numbering and reverse the meaning of "odd" and "even"
6755 // when generating little endian code.
6757 for (unsigned i = 0; i != 8; ++i) {
6758 if (isLittleEndian) {
6760 Ops[i*2+1] = 2*i+16;
6763 Ops[i*2+1] = 2*i+1+16;
6767 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6769 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6771 llvm_unreachable("Unknown mul to lower!");
6775 /// LowerOperation - Provide custom lowering hooks for some operations.
6777 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6778 switch (Op.getOpcode()) {
6779 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6780 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6781 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6782 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6783 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6784 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6785 case ISD::SETCC: return LowerSETCC(Op, DAG);
6786 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6787 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6789 return LowerVASTART(Op, DAG, Subtarget);
6792 return LowerVAARG(Op, DAG, Subtarget);
6795 return LowerVACOPY(Op, DAG, Subtarget);
6797 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6798 case ISD::DYNAMIC_STACKALLOC:
6799 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6801 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6802 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6804 case ISD::LOAD: return LowerLOAD(Op, DAG);
6805 case ISD::STORE: return LowerSTORE(Op, DAG);
6806 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6807 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6808 case ISD::FP_TO_UINT:
6809 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6811 case ISD::UINT_TO_FP:
6812 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6813 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6815 // Lower 64-bit shifts.
6816 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6817 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6818 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6820 // Vector-related lowering.
6821 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6822 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6823 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6824 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6825 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6826 case ISD::MUL: return LowerMUL(Op, DAG);
6828 // For counter-based loop handling.
6829 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6831 // Frame & Return address.
6832 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6833 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6837 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6838 SmallVectorImpl<SDValue>&Results,
6839 SelectionDAG &DAG) const {
6841 switch (N->getOpcode()) {
6843 llvm_unreachable("Do not know how to custom type legalize this operation!");
6844 case ISD::READCYCLECOUNTER: {
6845 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6846 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6848 Results.push_back(RTB);
6849 Results.push_back(RTB.getValue(1));
6850 Results.push_back(RTB.getValue(2));
6853 case ISD::INTRINSIC_W_CHAIN: {
6854 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6855 Intrinsic::ppc_is_decremented_ctr_nonzero)
6858 assert(N->getValueType(0) == MVT::i1 &&
6859 "Unexpected result type for CTR decrement intrinsic");
6860 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6861 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6862 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6865 Results.push_back(NewInt);
6866 Results.push_back(NewInt.getValue(1));
6870 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
6873 EVT VT = N->getValueType(0);
6875 if (VT == MVT::i64) {
6876 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6878 Results.push_back(NewNode);
6879 Results.push_back(NewNode.getValue(1));
6883 case ISD::FP_ROUND_INREG: {
6884 assert(N->getValueType(0) == MVT::ppcf128);
6885 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6886 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6887 MVT::f64, N->getOperand(0),
6888 DAG.getIntPtrConstant(0));
6889 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6890 MVT::f64, N->getOperand(0),
6891 DAG.getIntPtrConstant(1));
6893 // Add the two halves of the long double in round-to-zero mode.
6894 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6896 // We know the low half is about to be thrown away, so just use something
6898 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6902 case ISD::FP_TO_SINT:
6903 // LowerFP_TO_INT() can only handle f32 and f64.
6904 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6906 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6912 //===----------------------------------------------------------------------===//
6913 // Other Lowering Code
6914 //===----------------------------------------------------------------------===//
6916 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6917 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6918 Function *Func = Intrinsic::getDeclaration(M, Id);
6919 return Builder.CreateCall(Func);
6922 // The mappings for emitLeading/TrailingFence is taken from
6923 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6924 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6925 AtomicOrdering Ord, bool IsStore,
6926 bool IsLoad) const {
6927 if (Ord == SequentiallyConsistent)
6928 return callIntrinsic(Builder, Intrinsic::ppc_sync);
6929 else if (isAtLeastRelease(Ord))
6930 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6935 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6936 AtomicOrdering Ord, bool IsStore,
6937 bool IsLoad) const {
6938 if (IsLoad && isAtLeastAcquire(Ord))
6939 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6940 // FIXME: this is too conservative, a dependent branch + isync is enough.
6941 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6942 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6943 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6949 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6950 bool is64bit, unsigned BinOpcode) const {
6951 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6952 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6954 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6955 MachineFunction *F = BB->getParent();
6956 MachineFunction::iterator It = BB;
6959 unsigned dest = MI->getOperand(0).getReg();
6960 unsigned ptrA = MI->getOperand(1).getReg();
6961 unsigned ptrB = MI->getOperand(2).getReg();
6962 unsigned incr = MI->getOperand(3).getReg();
6963 DebugLoc dl = MI->getDebugLoc();
6965 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6966 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6967 F->insert(It, loopMBB);
6968 F->insert(It, exitMBB);
6969 exitMBB->splice(exitMBB->begin(), BB,
6970 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6971 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6973 MachineRegisterInfo &RegInfo = F->getRegInfo();
6974 unsigned TmpReg = (!BinOpcode) ? incr :
6975 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6976 : &PPC::GPRCRegClass);
6980 // fallthrough --> loopMBB
6981 BB->addSuccessor(loopMBB);
6984 // l[wd]arx dest, ptr
6985 // add r0, dest, incr
6986 // st[wd]cx. r0, ptr
6988 // fallthrough --> exitMBB
6990 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6991 .addReg(ptrA).addReg(ptrB);
6993 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6994 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6995 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6996 BuildMI(BB, dl, TII->get(PPC::BCC))
6997 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6998 BB->addSuccessor(loopMBB);
6999 BB->addSuccessor(exitMBB);
7008 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7009 MachineBasicBlock *BB,
7010 bool is8bit, // operation
7011 unsigned BinOpcode) const {
7012 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7013 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7014 // In 64 bit mode we have to use 64 bits for addresses, even though the
7015 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7016 // registers without caring whether they're 32 or 64, but here we're
7017 // doing actual arithmetic on the addresses.
7018 bool is64bit = Subtarget.isPPC64();
7019 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7021 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7022 MachineFunction *F = BB->getParent();
7023 MachineFunction::iterator It = BB;
7026 unsigned dest = MI->getOperand(0).getReg();
7027 unsigned ptrA = MI->getOperand(1).getReg();
7028 unsigned ptrB = MI->getOperand(2).getReg();
7029 unsigned incr = MI->getOperand(3).getReg();
7030 DebugLoc dl = MI->getDebugLoc();
7032 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7033 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7034 F->insert(It, loopMBB);
7035 F->insert(It, exitMBB);
7036 exitMBB->splice(exitMBB->begin(), BB,
7037 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7038 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7040 MachineRegisterInfo &RegInfo = F->getRegInfo();
7041 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7042 : &PPC::GPRCRegClass;
7043 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7044 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7045 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7046 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7047 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7048 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7049 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7050 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7051 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7052 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7053 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7055 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7059 // fallthrough --> loopMBB
7060 BB->addSuccessor(loopMBB);
7062 // The 4-byte load must be aligned, while a char or short may be
7063 // anywhere in the word. Hence all this nasty bookkeeping code.
7064 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7065 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7066 // xori shift, shift1, 24 [16]
7067 // rlwinm ptr, ptr1, 0, 0, 29
7068 // slw incr2, incr, shift
7069 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7070 // slw mask, mask2, shift
7072 // lwarx tmpDest, ptr
7073 // add tmp, tmpDest, incr2
7074 // andc tmp2, tmpDest, mask
7075 // and tmp3, tmp, mask
7076 // or tmp4, tmp3, tmp2
7079 // fallthrough --> exitMBB
7080 // srw dest, tmpDest, shift
7081 if (ptrA != ZeroReg) {
7082 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7083 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7084 .addReg(ptrA).addReg(ptrB);
7088 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7089 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7090 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7091 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7093 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7094 .addReg(Ptr1Reg).addImm(0).addImm(61);
7096 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7097 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7098 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7099 .addReg(incr).addReg(ShiftReg);
7101 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7103 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7104 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7106 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7107 .addReg(Mask2Reg).addReg(ShiftReg);
7110 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7111 .addReg(ZeroReg).addReg(PtrReg);
7113 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7114 .addReg(Incr2Reg).addReg(TmpDestReg);
7115 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7116 .addReg(TmpDestReg).addReg(MaskReg);
7117 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7118 .addReg(TmpReg).addReg(MaskReg);
7119 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7120 .addReg(Tmp3Reg).addReg(Tmp2Reg);
7121 BuildMI(BB, dl, TII->get(PPC::STWCX))
7122 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7123 BuildMI(BB, dl, TII->get(PPC::BCC))
7124 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7125 BB->addSuccessor(loopMBB);
7126 BB->addSuccessor(exitMBB);
7131 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7136 llvm::MachineBasicBlock*
7137 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7138 MachineBasicBlock *MBB) const {
7139 DebugLoc DL = MI->getDebugLoc();
7140 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7142 MachineFunction *MF = MBB->getParent();
7143 MachineRegisterInfo &MRI = MF->getRegInfo();
7145 const BasicBlock *BB = MBB->getBasicBlock();
7146 MachineFunction::iterator I = MBB;
7150 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7151 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7153 unsigned DstReg = MI->getOperand(0).getReg();
7154 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7155 assert(RC->hasType(MVT::i32) && "Invalid destination!");
7156 unsigned mainDstReg = MRI.createVirtualRegister(RC);
7157 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7159 MVT PVT = getPointerTy();
7160 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7161 "Invalid Pointer Size!");
7162 // For v = setjmp(buf), we generate
7165 // SjLjSetup mainMBB
7171 // buf[LabelOffset] = LR
7175 // v = phi(main, restore)
7178 MachineBasicBlock *thisMBB = MBB;
7179 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7180 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7181 MF->insert(I, mainMBB);
7182 MF->insert(I, sinkMBB);
7184 MachineInstrBuilder MIB;
7186 // Transfer the remainder of BB and its successor edges to sinkMBB.
7187 sinkMBB->splice(sinkMBB->begin(), MBB,
7188 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7189 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7191 // Note that the structure of the jmp_buf used here is not compatible
7192 // with that used by libc, and is not designed to be. Specifically, it
7193 // stores only those 'reserved' registers that LLVM does not otherwise
7194 // understand how to spill. Also, by convention, by the time this
7195 // intrinsic is called, Clang has already stored the frame address in the
7196 // first slot of the buffer and stack address in the third. Following the
7197 // X86 target code, we'll store the jump address in the second slot. We also
7198 // need to save the TOC pointer (R2) to handle jumps between shared
7199 // libraries, and that will be stored in the fourth slot. The thread
7200 // identifier (R13) is not affected.
7203 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7204 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7205 const int64_t BPOffset = 4 * PVT.getStoreSize();
7207 // Prepare IP either in reg.
7208 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7209 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7210 unsigned BufReg = MI->getOperand(1).getReg();
7212 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7213 setUsesTOCBasePtr(*MBB->getParent());
7214 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7218 MIB.setMemRefs(MMOBegin, MMOEnd);
7221 // Naked functions never have a base pointer, and so we use r1. For all
7222 // other functions, this decision must be delayed until during PEI.
7224 if (MF->getFunction()->getAttributes().hasAttribute(
7225 AttributeSet::FunctionIndex, Attribute::Naked))
7226 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7228 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7230 MIB = BuildMI(*thisMBB, MI, DL,
7231 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7235 MIB.setMemRefs(MMOBegin, MMOEnd);
7238 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7239 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7240 MIB.addRegMask(TRI->getNoPreservedMask());
7242 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7244 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7246 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7248 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7249 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7254 BuildMI(mainMBB, DL,
7255 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7258 if (Subtarget.isPPC64()) {
7259 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7261 .addImm(LabelOffset)
7264 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7266 .addImm(LabelOffset)
7270 MIB.setMemRefs(MMOBegin, MMOEnd);
7272 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7273 mainMBB->addSuccessor(sinkMBB);
7276 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7277 TII->get(PPC::PHI), DstReg)
7278 .addReg(mainDstReg).addMBB(mainMBB)
7279 .addReg(restoreDstReg).addMBB(thisMBB);
7281 MI->eraseFromParent();
7286 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7287 MachineBasicBlock *MBB) const {
7288 DebugLoc DL = MI->getDebugLoc();
7289 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7291 MachineFunction *MF = MBB->getParent();
7292 MachineRegisterInfo &MRI = MF->getRegInfo();
7295 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7296 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7298 MVT PVT = getPointerTy();
7299 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7300 "Invalid Pointer Size!");
7302 const TargetRegisterClass *RC =
7303 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7304 unsigned Tmp = MRI.createVirtualRegister(RC);
7305 // Since FP is only updated here but NOT referenced, it's treated as GPR.
7306 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7307 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7311 : (Subtarget.isSVR4ABI() &&
7312 MF->getTarget().getRelocationModel() == Reloc::PIC_
7316 MachineInstrBuilder MIB;
7318 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7319 const int64_t SPOffset = 2 * PVT.getStoreSize();
7320 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7321 const int64_t BPOffset = 4 * PVT.getStoreSize();
7323 unsigned BufReg = MI->getOperand(0).getReg();
7325 // Reload FP (the jumped-to function may not have had a
7326 // frame pointer, and if so, then its r31 will be restored
7328 if (PVT == MVT::i64) {
7329 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7333 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7337 MIB.setMemRefs(MMOBegin, MMOEnd);
7340 if (PVT == MVT::i64) {
7341 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7342 .addImm(LabelOffset)
7345 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7346 .addImm(LabelOffset)
7349 MIB.setMemRefs(MMOBegin, MMOEnd);
7352 if (PVT == MVT::i64) {
7353 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7357 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7361 MIB.setMemRefs(MMOBegin, MMOEnd);
7364 if (PVT == MVT::i64) {
7365 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7369 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7373 MIB.setMemRefs(MMOBegin, MMOEnd);
7376 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7377 setUsesTOCBasePtr(*MBB->getParent());
7378 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7382 MIB.setMemRefs(MMOBegin, MMOEnd);
7386 BuildMI(*MBB, MI, DL,
7387 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7388 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7390 MI->eraseFromParent();
7395 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7396 MachineBasicBlock *BB) const {
7397 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
7398 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7399 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
7400 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7401 // Call lowering should have added an r2 operand to indicate a dependence
7402 // on the TOC base pointer value. It can't however, because there is no
7403 // way to mark the dependence as implicit there, and so the stackmap code
7404 // will confuse it with a regular operand. Instead, add the dependence
7406 setUsesTOCBasePtr(*BB->getParent());
7407 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
7410 return emitPatchPoint(MI, BB);
7413 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7414 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7415 return emitEHSjLjSetJmp(MI, BB);
7416 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7417 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7418 return emitEHSjLjLongJmp(MI, BB);
7421 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7423 // To "insert" these instructions we actually have to insert their
7424 // control-flow patterns.
7425 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7426 MachineFunction::iterator It = BB;
7429 MachineFunction *F = BB->getParent();
7431 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7432 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7433 MI->getOpcode() == PPC::SELECT_I4 ||
7434 MI->getOpcode() == PPC::SELECT_I8)) {
7435 SmallVector<MachineOperand, 2> Cond;
7436 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7437 MI->getOpcode() == PPC::SELECT_CC_I8)
7438 Cond.push_back(MI->getOperand(4));
7440 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7441 Cond.push_back(MI->getOperand(1));
7443 DebugLoc dl = MI->getDebugLoc();
7444 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7445 Cond, MI->getOperand(2).getReg(),
7446 MI->getOperand(3).getReg());
7447 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7448 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7449 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7450 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7451 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7452 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7453 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7454 MI->getOpcode() == PPC::SELECT_I4 ||
7455 MI->getOpcode() == PPC::SELECT_I8 ||
7456 MI->getOpcode() == PPC::SELECT_F4 ||
7457 MI->getOpcode() == PPC::SELECT_F8 ||
7458 MI->getOpcode() == PPC::SELECT_VRRC ||
7459 MI->getOpcode() == PPC::SELECT_VSFRC ||
7460 MI->getOpcode() == PPC::SELECT_VSRC) {
7461 // The incoming instruction knows the destination vreg to set, the
7462 // condition code register to branch on, the true/false values to
7463 // select between, and a branch opcode to use.
7468 // cmpTY ccX, r1, r2
7470 // fallthrough --> copy0MBB
7471 MachineBasicBlock *thisMBB = BB;
7472 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7473 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7474 DebugLoc dl = MI->getDebugLoc();
7475 F->insert(It, copy0MBB);
7476 F->insert(It, sinkMBB);
7478 // Transfer the remainder of BB and its successor edges to sinkMBB.
7479 sinkMBB->splice(sinkMBB->begin(), BB,
7480 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7481 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7483 // Next, add the true and fallthrough blocks as its successors.
7484 BB->addSuccessor(copy0MBB);
7485 BB->addSuccessor(sinkMBB);
7487 if (MI->getOpcode() == PPC::SELECT_I4 ||
7488 MI->getOpcode() == PPC::SELECT_I8 ||
7489 MI->getOpcode() == PPC::SELECT_F4 ||
7490 MI->getOpcode() == PPC::SELECT_F8 ||
7491 MI->getOpcode() == PPC::SELECT_VRRC ||
7492 MI->getOpcode() == PPC::SELECT_VSFRC ||
7493 MI->getOpcode() == PPC::SELECT_VSRC) {
7494 BuildMI(BB, dl, TII->get(PPC::BC))
7495 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7497 unsigned SelectPred = MI->getOperand(4).getImm();
7498 BuildMI(BB, dl, TII->get(PPC::BCC))
7499 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7503 // %FalseValue = ...
7504 // # fallthrough to sinkMBB
7507 // Update machine-CFG edges
7508 BB->addSuccessor(sinkMBB);
7511 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7514 BuildMI(*BB, BB->begin(), dl,
7515 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7516 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7517 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7518 } else if (MI->getOpcode() == PPC::ReadTB) {
7519 // To read the 64-bit time-base register on a 32-bit target, we read the
7520 // two halves. Should the counter have wrapped while it was being read, we
7521 // need to try again.
7524 // mfspr Rx,TBU # load from TBU
7525 // mfspr Ry,TB # load from TB
7526 // mfspr Rz,TBU # load from TBU
7527 // cmpw crX,Rx,Rz # check if ‘old’=’new’
7528 // bne readLoop # branch if they're not equal
7531 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7532 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7533 DebugLoc dl = MI->getDebugLoc();
7534 F->insert(It, readMBB);
7535 F->insert(It, sinkMBB);
7537 // Transfer the remainder of BB and its successor edges to sinkMBB.
7538 sinkMBB->splice(sinkMBB->begin(), BB,
7539 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7540 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7542 BB->addSuccessor(readMBB);
7545 MachineRegisterInfo &RegInfo = F->getRegInfo();
7546 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7547 unsigned LoReg = MI->getOperand(0).getReg();
7548 unsigned HiReg = MI->getOperand(1).getReg();
7550 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7551 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7552 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7554 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7556 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7557 .addReg(HiReg).addReg(ReadAgainReg);
7558 BuildMI(BB, dl, TII->get(PPC::BCC))
7559 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7561 BB->addSuccessor(readMBB);
7562 BB->addSuccessor(sinkMBB);
7564 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7565 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7566 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7567 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7568 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7569 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7570 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7571 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7573 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7574 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7575 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7576 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7577 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7578 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7579 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7580 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7582 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7583 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7584 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7585 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7586 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7587 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7588 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7589 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7591 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7592 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7593 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7594 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7595 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7596 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7597 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7598 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7600 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7601 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7602 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7603 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7604 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7605 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7606 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7607 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7609 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7610 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7611 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7612 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7613 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7614 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7615 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7616 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7618 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7619 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7620 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7621 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7622 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7623 BB = EmitAtomicBinary(MI, BB, false, 0);
7624 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7625 BB = EmitAtomicBinary(MI, BB, true, 0);
7627 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7628 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7629 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7631 unsigned dest = MI->getOperand(0).getReg();
7632 unsigned ptrA = MI->getOperand(1).getReg();
7633 unsigned ptrB = MI->getOperand(2).getReg();
7634 unsigned oldval = MI->getOperand(3).getReg();
7635 unsigned newval = MI->getOperand(4).getReg();
7636 DebugLoc dl = MI->getDebugLoc();
7638 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7639 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7640 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7641 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7642 F->insert(It, loop1MBB);
7643 F->insert(It, loop2MBB);
7644 F->insert(It, midMBB);
7645 F->insert(It, exitMBB);
7646 exitMBB->splice(exitMBB->begin(), BB,
7647 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7648 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7652 // fallthrough --> loopMBB
7653 BB->addSuccessor(loop1MBB);
7656 // l[wd]arx dest, ptr
7657 // cmp[wd] dest, oldval
7660 // st[wd]cx. newval, ptr
7664 // st[wd]cx. dest, ptr
7667 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7668 .addReg(ptrA).addReg(ptrB);
7669 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7670 .addReg(oldval).addReg(dest);
7671 BuildMI(BB, dl, TII->get(PPC::BCC))
7672 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7673 BB->addSuccessor(loop2MBB);
7674 BB->addSuccessor(midMBB);
7677 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7678 .addReg(newval).addReg(ptrA).addReg(ptrB);
7679 BuildMI(BB, dl, TII->get(PPC::BCC))
7680 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7681 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7682 BB->addSuccessor(loop1MBB);
7683 BB->addSuccessor(exitMBB);
7686 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7687 .addReg(dest).addReg(ptrA).addReg(ptrB);
7688 BB->addSuccessor(exitMBB);
7693 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7694 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7695 // We must use 64-bit registers for addresses when targeting 64-bit,
7696 // since we're actually doing arithmetic on them. Other registers
7698 bool is64bit = Subtarget.isPPC64();
7699 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7701 unsigned dest = MI->getOperand(0).getReg();
7702 unsigned ptrA = MI->getOperand(1).getReg();
7703 unsigned ptrB = MI->getOperand(2).getReg();
7704 unsigned oldval = MI->getOperand(3).getReg();
7705 unsigned newval = MI->getOperand(4).getReg();
7706 DebugLoc dl = MI->getDebugLoc();
7708 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7709 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7710 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7711 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7712 F->insert(It, loop1MBB);
7713 F->insert(It, loop2MBB);
7714 F->insert(It, midMBB);
7715 F->insert(It, exitMBB);
7716 exitMBB->splice(exitMBB->begin(), BB,
7717 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7718 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7720 MachineRegisterInfo &RegInfo = F->getRegInfo();
7721 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7722 : &PPC::GPRCRegClass;
7723 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7724 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7725 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7726 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7727 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7728 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7729 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7730 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7731 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7732 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7733 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7734 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7735 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7737 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7738 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7741 // fallthrough --> loopMBB
7742 BB->addSuccessor(loop1MBB);
7744 // The 4-byte load must be aligned, while a char or short may be
7745 // anywhere in the word. Hence all this nasty bookkeeping code.
7746 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7747 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7748 // xori shift, shift1, 24 [16]
7749 // rlwinm ptr, ptr1, 0, 0, 29
7750 // slw newval2, newval, shift
7751 // slw oldval2, oldval,shift
7752 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7753 // slw mask, mask2, shift
7754 // and newval3, newval2, mask
7755 // and oldval3, oldval2, mask
7757 // lwarx tmpDest, ptr
7758 // and tmp, tmpDest, mask
7759 // cmpw tmp, oldval3
7762 // andc tmp2, tmpDest, mask
7763 // or tmp4, tmp2, newval3
7768 // stwcx. tmpDest, ptr
7770 // srw dest, tmpDest, shift
7771 if (ptrA != ZeroReg) {
7772 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7773 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7774 .addReg(ptrA).addReg(ptrB);
7778 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7779 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7780 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7781 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7783 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7784 .addReg(Ptr1Reg).addImm(0).addImm(61);
7786 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7787 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7788 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7789 .addReg(newval).addReg(ShiftReg);
7790 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7791 .addReg(oldval).addReg(ShiftReg);
7793 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7795 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7796 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7797 .addReg(Mask3Reg).addImm(65535);
7799 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7800 .addReg(Mask2Reg).addReg(ShiftReg);
7801 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7802 .addReg(NewVal2Reg).addReg(MaskReg);
7803 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7804 .addReg(OldVal2Reg).addReg(MaskReg);
7807 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7808 .addReg(ZeroReg).addReg(PtrReg);
7809 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7810 .addReg(TmpDestReg).addReg(MaskReg);
7811 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7812 .addReg(TmpReg).addReg(OldVal3Reg);
7813 BuildMI(BB, dl, TII->get(PPC::BCC))
7814 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7815 BB->addSuccessor(loop2MBB);
7816 BB->addSuccessor(midMBB);
7819 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7820 .addReg(TmpDestReg).addReg(MaskReg);
7821 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7822 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7823 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7824 .addReg(ZeroReg).addReg(PtrReg);
7825 BuildMI(BB, dl, TII->get(PPC::BCC))
7826 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7827 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7828 BB->addSuccessor(loop1MBB);
7829 BB->addSuccessor(exitMBB);
7832 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7833 .addReg(ZeroReg).addReg(PtrReg);
7834 BB->addSuccessor(exitMBB);
7839 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7841 } else if (MI->getOpcode() == PPC::FADDrtz) {
7842 // This pseudo performs an FADD with rounding mode temporarily forced
7843 // to round-to-zero. We emit this via custom inserter since the FPSCR
7844 // is not modeled at the SelectionDAG level.
7845 unsigned Dest = MI->getOperand(0).getReg();
7846 unsigned Src1 = MI->getOperand(1).getReg();
7847 unsigned Src2 = MI->getOperand(2).getReg();
7848 DebugLoc dl = MI->getDebugLoc();
7850 MachineRegisterInfo &RegInfo = F->getRegInfo();
7851 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7853 // Save FPSCR value.
7854 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7856 // Set rounding mode to round-to-zero.
7857 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7858 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7860 // Perform addition.
7861 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7863 // Restore FPSCR value.
7864 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
7865 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7866 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7867 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7868 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7869 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7870 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7871 PPC::ANDIo8 : PPC::ANDIo;
7872 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7873 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7875 MachineRegisterInfo &RegInfo = F->getRegInfo();
7876 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7877 &PPC::GPRCRegClass :
7878 &PPC::G8RCRegClass);
7880 DebugLoc dl = MI->getDebugLoc();
7881 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7882 .addReg(MI->getOperand(1).getReg()).addImm(1);
7883 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7884 MI->getOperand(0).getReg())
7885 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7887 llvm_unreachable("Unexpected instr type to insert");
7890 MI->eraseFromParent(); // The pseudo instruction is gone now.
7894 //===----------------------------------------------------------------------===//
7895 // Target Optimization Hooks
7896 //===----------------------------------------------------------------------===//
7898 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7899 DAGCombinerInfo &DCI,
7900 unsigned &RefinementSteps,
7901 bool &UseOneConstNR) const {
7902 EVT VT = Operand.getValueType();
7903 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7904 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7905 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7906 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7907 // Convergence is quadratic, so we essentially double the number of digits
7908 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7909 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7910 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7911 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7912 if (VT.getScalarType() == MVT::f64)
7914 UseOneConstNR = true;
7915 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7920 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7921 DAGCombinerInfo &DCI,
7922 unsigned &RefinementSteps) const {
7923 EVT VT = Operand.getValueType();
7924 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7925 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7926 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7927 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7928 // Convergence is quadratic, so we essentially double the number of digits
7929 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7930 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7931 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7932 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7933 if (VT.getScalarType() == MVT::f64)
7935 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7940 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7941 // Note: This functionality is used only when unsafe-fp-math is enabled, and
7942 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7943 // enabled for division), this functionality is redundant with the default
7944 // combiner logic (once the division -> reciprocal/multiply transformation
7945 // has taken place). As a result, this matters more for older cores than for
7948 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7949 // reciprocal if there are two or more FDIVs (for embedded cores with only
7950 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7951 switch (Subtarget.getDarwinDirective()) {
7953 return NumUsers > 2;
7956 case PPC::DIR_E500mc:
7957 case PPC::DIR_E5500:
7958 return NumUsers > 1;
7962 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7963 unsigned Bytes, int Dist,
7964 SelectionDAG &DAG) {
7965 if (VT.getSizeInBits() / 8 != Bytes)
7968 SDValue BaseLoc = Base->getBasePtr();
7969 if (Loc.getOpcode() == ISD::FrameIndex) {
7970 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7972 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7973 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7974 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7975 int FS = MFI->getObjectSize(FI);
7976 int BFS = MFI->getObjectSize(BFI);
7977 if (FS != BFS || FS != (int)Bytes) return false;
7978 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7982 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7983 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7987 const GlobalValue *GV1 = nullptr;
7988 const GlobalValue *GV2 = nullptr;
7989 int64_t Offset1 = 0;
7990 int64_t Offset2 = 0;
7991 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7992 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7993 if (isGA1 && isGA2 && GV1 == GV2)
7994 return Offset1 == (Offset2 + Dist*Bytes);
7998 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7999 // not enforce equality of the chain operands.
8000 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8001 unsigned Bytes, int Dist,
8002 SelectionDAG &DAG) {
8003 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8004 EVT VT = LS->getMemoryVT();
8005 SDValue Loc = LS->getBasePtr();
8006 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8009 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8011 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8012 default: return false;
8013 case Intrinsic::ppc_altivec_lvx:
8014 case Intrinsic::ppc_altivec_lvxl:
8015 case Intrinsic::ppc_vsx_lxvw4x:
8018 case Intrinsic::ppc_vsx_lxvd2x:
8021 case Intrinsic::ppc_altivec_lvebx:
8024 case Intrinsic::ppc_altivec_lvehx:
8027 case Intrinsic::ppc_altivec_lvewx:
8032 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8035 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8037 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8038 default: return false;
8039 case Intrinsic::ppc_altivec_stvx:
8040 case Intrinsic::ppc_altivec_stvxl:
8041 case Intrinsic::ppc_vsx_stxvw4x:
8044 case Intrinsic::ppc_vsx_stxvd2x:
8047 case Intrinsic::ppc_altivec_stvebx:
8050 case Intrinsic::ppc_altivec_stvehx:
8053 case Intrinsic::ppc_altivec_stvewx:
8058 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8064 // Return true is there is a nearyby consecutive load to the one provided
8065 // (regardless of alignment). We search up and down the chain, looking though
8066 // token factors and other loads (but nothing else). As a result, a true result
8067 // indicates that it is safe to create a new consecutive load adjacent to the
8069 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8070 SDValue Chain = LD->getChain();
8071 EVT VT = LD->getMemoryVT();
8073 SmallSet<SDNode *, 16> LoadRoots;
8074 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8075 SmallSet<SDNode *, 16> Visited;
8077 // First, search up the chain, branching to follow all token-factor operands.
8078 // If we find a consecutive load, then we're done, otherwise, record all
8079 // nodes just above the top-level loads and token factors.
8080 while (!Queue.empty()) {
8081 SDNode *ChainNext = Queue.pop_back_val();
8082 if (!Visited.insert(ChainNext).second)
8085 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8086 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8089 if (!Visited.count(ChainLD->getChain().getNode()))
8090 Queue.push_back(ChainLD->getChain().getNode());
8091 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8092 for (const SDUse &O : ChainNext->ops())
8093 if (!Visited.count(O.getNode()))
8094 Queue.push_back(O.getNode());
8096 LoadRoots.insert(ChainNext);
8099 // Second, search down the chain, starting from the top-level nodes recorded
8100 // in the first phase. These top-level nodes are the nodes just above all
8101 // loads and token factors. Starting with their uses, recursively look though
8102 // all loads (just the chain uses) and token factors to find a consecutive
8107 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8108 IE = LoadRoots.end(); I != IE; ++I) {
8109 Queue.push_back(*I);
8111 while (!Queue.empty()) {
8112 SDNode *LoadRoot = Queue.pop_back_val();
8113 if (!Visited.insert(LoadRoot).second)
8116 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8117 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8120 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8121 UE = LoadRoot->use_end(); UI != UE; ++UI)
8122 if (((isa<MemSDNode>(*UI) &&
8123 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8124 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8125 Queue.push_back(*UI);
8132 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8133 DAGCombinerInfo &DCI) const {
8134 SelectionDAG &DAG = DCI.DAG;
8137 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8138 // If we're tracking CR bits, we need to be careful that we don't have:
8139 // trunc(binary-ops(zext(x), zext(y)))
8141 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8142 // such that we're unnecessarily moving things into GPRs when it would be
8143 // better to keep them in CR bits.
8145 // Note that trunc here can be an actual i1 trunc, or can be the effective
8146 // truncation that comes from a setcc or select_cc.
8147 if (N->getOpcode() == ISD::TRUNCATE &&
8148 N->getValueType(0) != MVT::i1)
8151 if (N->getOperand(0).getValueType() != MVT::i32 &&
8152 N->getOperand(0).getValueType() != MVT::i64)
8155 if (N->getOpcode() == ISD::SETCC ||
8156 N->getOpcode() == ISD::SELECT_CC) {
8157 // If we're looking at a comparison, then we need to make sure that the
8158 // high bits (all except for the first) don't matter the result.
8160 cast<CondCodeSDNode>(N->getOperand(
8161 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8162 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8164 if (ISD::isSignedIntSetCC(CC)) {
8165 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
8166 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
8168 } else if (ISD::isUnsignedIntSetCC(CC)) {
8169 if (!DAG.MaskedValueIsZero(N->getOperand(0),
8170 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
8171 !DAG.MaskedValueIsZero(N->getOperand(1),
8172 APInt::getHighBitsSet(OpBits, OpBits-1)))
8175 // This is neither a signed nor an unsigned comparison, just make sure
8176 // that the high bits are equal.
8177 APInt Op1Zero, Op1One;
8178 APInt Op2Zero, Op2One;
8179 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8180 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8182 // We don't really care about what is known about the first bit (if
8183 // anything), so clear it in all masks prior to comparing them.
8184 Op1Zero.clearBit(0); Op1One.clearBit(0);
8185 Op2Zero.clearBit(0); Op2One.clearBit(0);
8187 if (Op1Zero != Op2Zero || Op1One != Op2One)
8192 // We now know that the higher-order bits are irrelevant, we just need to
8193 // make sure that all of the intermediate operations are bit operations, and
8194 // all inputs are extensions.
8195 if (N->getOperand(0).getOpcode() != ISD::AND &&
8196 N->getOperand(0).getOpcode() != ISD::OR &&
8197 N->getOperand(0).getOpcode() != ISD::XOR &&
8198 N->getOperand(0).getOpcode() != ISD::SELECT &&
8199 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8200 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8201 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8202 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8203 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8206 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8207 N->getOperand(1).getOpcode() != ISD::AND &&
8208 N->getOperand(1).getOpcode() != ISD::OR &&
8209 N->getOperand(1).getOpcode() != ISD::XOR &&
8210 N->getOperand(1).getOpcode() != ISD::SELECT &&
8211 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8212 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8213 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8214 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8215 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8218 SmallVector<SDValue, 4> Inputs;
8219 SmallVector<SDValue, 8> BinOps, PromOps;
8220 SmallPtrSet<SDNode *, 16> Visited;
8222 for (unsigned i = 0; i < 2; ++i) {
8223 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8224 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8225 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8226 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8227 isa<ConstantSDNode>(N->getOperand(i)))
8228 Inputs.push_back(N->getOperand(i));
8230 BinOps.push_back(N->getOperand(i));
8232 if (N->getOpcode() == ISD::TRUNCATE)
8236 // Visit all inputs, collect all binary operations (and, or, xor and
8237 // select) that are all fed by extensions.
8238 while (!BinOps.empty()) {
8239 SDValue BinOp = BinOps.back();
8242 if (!Visited.insert(BinOp.getNode()).second)
8245 PromOps.push_back(BinOp);
8247 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8248 // The condition of the select is not promoted.
8249 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8251 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8254 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8255 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8256 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8257 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8258 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8259 Inputs.push_back(BinOp.getOperand(i));
8260 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8261 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8262 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8263 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8264 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8265 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8266 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8267 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8268 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8269 BinOps.push_back(BinOp.getOperand(i));
8271 // We have an input that is not an extension or another binary
8272 // operation; we'll abort this transformation.
8278 // Make sure that this is a self-contained cluster of operations (which
8279 // is not quite the same thing as saying that everything has only one
8281 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8282 if (isa<ConstantSDNode>(Inputs[i]))
8285 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8286 UE = Inputs[i].getNode()->use_end();
8289 if (User != N && !Visited.count(User))
8292 // Make sure that we're not going to promote the non-output-value
8293 // operand(s) or SELECT or SELECT_CC.
8294 // FIXME: Although we could sometimes handle this, and it does occur in
8295 // practice that one of the condition inputs to the select is also one of
8296 // the outputs, we currently can't deal with this.
8297 if (User->getOpcode() == ISD::SELECT) {
8298 if (User->getOperand(0) == Inputs[i])
8300 } else if (User->getOpcode() == ISD::SELECT_CC) {
8301 if (User->getOperand(0) == Inputs[i] ||
8302 User->getOperand(1) == Inputs[i])
8308 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8309 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8310 UE = PromOps[i].getNode()->use_end();
8313 if (User != N && !Visited.count(User))
8316 // Make sure that we're not going to promote the non-output-value
8317 // operand(s) or SELECT or SELECT_CC.
8318 // FIXME: Although we could sometimes handle this, and it does occur in
8319 // practice that one of the condition inputs to the select is also one of
8320 // the outputs, we currently can't deal with this.
8321 if (User->getOpcode() == ISD::SELECT) {
8322 if (User->getOperand(0) == PromOps[i])
8324 } else if (User->getOpcode() == ISD::SELECT_CC) {
8325 if (User->getOperand(0) == PromOps[i] ||
8326 User->getOperand(1) == PromOps[i])
8332 // Replace all inputs with the extension operand.
8333 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8334 // Constants may have users outside the cluster of to-be-promoted nodes,
8335 // and so we need to replace those as we do the promotions.
8336 if (isa<ConstantSDNode>(Inputs[i]))
8339 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
8342 // Replace all operations (these are all the same, but have a different
8343 // (i1) return type). DAG.getNode will validate that the types of
8344 // a binary operator match, so go through the list in reverse so that
8345 // we've likely promoted both operands first. Any intermediate truncations or
8346 // extensions disappear.
8347 while (!PromOps.empty()) {
8348 SDValue PromOp = PromOps.back();
8351 if (PromOp.getOpcode() == ISD::TRUNCATE ||
8352 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8353 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8354 PromOp.getOpcode() == ISD::ANY_EXTEND) {
8355 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8356 PromOp.getOperand(0).getValueType() != MVT::i1) {
8357 // The operand is not yet ready (see comment below).
8358 PromOps.insert(PromOps.begin(), PromOp);
8362 SDValue RepValue = PromOp.getOperand(0);
8363 if (isa<ConstantSDNode>(RepValue))
8364 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8366 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8371 switch (PromOp.getOpcode()) {
8372 default: C = 0; break;
8373 case ISD::SELECT: C = 1; break;
8374 case ISD::SELECT_CC: C = 2; break;
8377 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8378 PromOp.getOperand(C).getValueType() != MVT::i1) ||
8379 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8380 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8381 // The to-be-promoted operands of this node have not yet been
8382 // promoted (this should be rare because we're going through the
8383 // list backward, but if one of the operands has several users in
8384 // this cluster of to-be-promoted nodes, it is possible).
8385 PromOps.insert(PromOps.begin(), PromOp);
8389 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8390 PromOp.getNode()->op_end());
8392 // If there are any constant inputs, make sure they're replaced now.
8393 for (unsigned i = 0; i < 2; ++i)
8394 if (isa<ConstantSDNode>(Ops[C+i]))
8395 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8397 DAG.ReplaceAllUsesOfValueWith(PromOp,
8398 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8401 // Now we're left with the initial truncation itself.
8402 if (N->getOpcode() == ISD::TRUNCATE)
8403 return N->getOperand(0);
8405 // Otherwise, this is a comparison. The operands to be compared have just
8406 // changed type (to i1), but everything else is the same.
8407 return SDValue(N, 0);
8410 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8411 DAGCombinerInfo &DCI) const {
8412 SelectionDAG &DAG = DCI.DAG;
8415 // If we're tracking CR bits, we need to be careful that we don't have:
8416 // zext(binary-ops(trunc(x), trunc(y)))
8418 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8419 // such that we're unnecessarily moving things into CR bits that can more
8420 // efficiently stay in GPRs. Note that if we're not certain that the high
8421 // bits are set as required by the final extension, we still may need to do
8422 // some masking to get the proper behavior.
8424 // This same functionality is important on PPC64 when dealing with
8425 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8426 // the return values of functions. Because it is so similar, it is handled
8429 if (N->getValueType(0) != MVT::i32 &&
8430 N->getValueType(0) != MVT::i64)
8433 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
8434 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
8437 if (N->getOperand(0).getOpcode() != ISD::AND &&
8438 N->getOperand(0).getOpcode() != ISD::OR &&
8439 N->getOperand(0).getOpcode() != ISD::XOR &&
8440 N->getOperand(0).getOpcode() != ISD::SELECT &&
8441 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8444 SmallVector<SDValue, 4> Inputs;
8445 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8446 SmallPtrSet<SDNode *, 16> Visited;
8448 // Visit all inputs, collect all binary operations (and, or, xor and
8449 // select) that are all fed by truncations.
8450 while (!BinOps.empty()) {
8451 SDValue BinOp = BinOps.back();
8454 if (!Visited.insert(BinOp.getNode()).second)
8457 PromOps.push_back(BinOp);
8459 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8460 // The condition of the select is not promoted.
8461 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8463 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8466 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8467 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8468 Inputs.push_back(BinOp.getOperand(i));
8469 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8470 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8471 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8472 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8473 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8474 BinOps.push_back(BinOp.getOperand(i));
8476 // We have an input that is not a truncation or another binary
8477 // operation; we'll abort this transformation.
8483 // The operands of a select that must be truncated when the select is
8484 // promoted because the operand is actually part of the to-be-promoted set.
8485 DenseMap<SDNode *, EVT> SelectTruncOp[2];
8487 // Make sure that this is a self-contained cluster of operations (which
8488 // is not quite the same thing as saying that everything has only one
8490 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8491 if (isa<ConstantSDNode>(Inputs[i]))
8494 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8495 UE = Inputs[i].getNode()->use_end();
8498 if (User != N && !Visited.count(User))
8501 // If we're going to promote the non-output-value operand(s) or SELECT or
8502 // SELECT_CC, record them for truncation.
8503 if (User->getOpcode() == ISD::SELECT) {
8504 if (User->getOperand(0) == Inputs[i])
8505 SelectTruncOp[0].insert(std::make_pair(User,
8506 User->getOperand(0).getValueType()));
8507 } else if (User->getOpcode() == ISD::SELECT_CC) {
8508 if (User->getOperand(0) == Inputs[i])
8509 SelectTruncOp[0].insert(std::make_pair(User,
8510 User->getOperand(0).getValueType()));
8511 if (User->getOperand(1) == Inputs[i])
8512 SelectTruncOp[1].insert(std::make_pair(User,
8513 User->getOperand(1).getValueType()));
8518 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8519 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8520 UE = PromOps[i].getNode()->use_end();
8523 if (User != N && !Visited.count(User))
8526 // If we're going to promote the non-output-value operand(s) or SELECT or
8527 // SELECT_CC, record them for truncation.
8528 if (User->getOpcode() == ISD::SELECT) {
8529 if (User->getOperand(0) == PromOps[i])
8530 SelectTruncOp[0].insert(std::make_pair(User,
8531 User->getOperand(0).getValueType()));
8532 } else if (User->getOpcode() == ISD::SELECT_CC) {
8533 if (User->getOperand(0) == PromOps[i])
8534 SelectTruncOp[0].insert(std::make_pair(User,
8535 User->getOperand(0).getValueType()));
8536 if (User->getOperand(1) == PromOps[i])
8537 SelectTruncOp[1].insert(std::make_pair(User,
8538 User->getOperand(1).getValueType()));
8543 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8544 bool ReallyNeedsExt = false;
8545 if (N->getOpcode() != ISD::ANY_EXTEND) {
8546 // If all of the inputs are not already sign/zero extended, then
8547 // we'll still need to do that at the end.
8548 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8549 if (isa<ConstantSDNode>(Inputs[i]))
8553 Inputs[i].getOperand(0).getValueSizeInBits();
8554 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8556 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8557 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8558 APInt::getHighBitsSet(OpBits,
8559 OpBits-PromBits))) ||
8560 (N->getOpcode() == ISD::SIGN_EXTEND &&
8561 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8562 (OpBits-(PromBits-1)))) {
8563 ReallyNeedsExt = true;
8569 // Replace all inputs, either with the truncation operand, or a
8570 // truncation or extension to the final output type.
8571 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8572 // Constant inputs need to be replaced with the to-be-promoted nodes that
8573 // use them because they might have users outside of the cluster of
8575 if (isa<ConstantSDNode>(Inputs[i]))
8578 SDValue InSrc = Inputs[i].getOperand(0);
8579 if (Inputs[i].getValueType() == N->getValueType(0))
8580 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8581 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8582 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8583 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8584 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8585 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8586 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8588 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8589 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8592 // Replace all operations (these are all the same, but have a different
8593 // (promoted) return type). DAG.getNode will validate that the types of
8594 // a binary operator match, so go through the list in reverse so that
8595 // we've likely promoted both operands first.
8596 while (!PromOps.empty()) {
8597 SDValue PromOp = PromOps.back();
8601 switch (PromOp.getOpcode()) {
8602 default: C = 0; break;
8603 case ISD::SELECT: C = 1; break;
8604 case ISD::SELECT_CC: C = 2; break;
8607 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8608 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8609 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8610 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8611 // The to-be-promoted operands of this node have not yet been
8612 // promoted (this should be rare because we're going through the
8613 // list backward, but if one of the operands has several users in
8614 // this cluster of to-be-promoted nodes, it is possible).
8615 PromOps.insert(PromOps.begin(), PromOp);
8619 // For SELECT and SELECT_CC nodes, we do a similar check for any
8620 // to-be-promoted comparison inputs.
8621 if (PromOp.getOpcode() == ISD::SELECT ||
8622 PromOp.getOpcode() == ISD::SELECT_CC) {
8623 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8624 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8625 (SelectTruncOp[1].count(PromOp.getNode()) &&
8626 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8627 PromOps.insert(PromOps.begin(), PromOp);
8632 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8633 PromOp.getNode()->op_end());
8635 // If this node has constant inputs, then they'll need to be promoted here.
8636 for (unsigned i = 0; i < 2; ++i) {
8637 if (!isa<ConstantSDNode>(Ops[C+i]))
8639 if (Ops[C+i].getValueType() == N->getValueType(0))
8642 if (N->getOpcode() == ISD::SIGN_EXTEND)
8643 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8644 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8645 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8647 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8650 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8651 // truncate them again to the original value type.
8652 if (PromOp.getOpcode() == ISD::SELECT ||
8653 PromOp.getOpcode() == ISD::SELECT_CC) {
8654 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8655 if (SI0 != SelectTruncOp[0].end())
8656 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8657 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8658 if (SI1 != SelectTruncOp[1].end())
8659 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8662 DAG.ReplaceAllUsesOfValueWith(PromOp,
8663 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8666 // Now we're left with the initial extension itself.
8667 if (!ReallyNeedsExt)
8668 return N->getOperand(0);
8670 // To zero extend, just mask off everything except for the first bit (in the
8672 if (N->getOpcode() == ISD::ZERO_EXTEND)
8673 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8674 DAG.getConstant(APInt::getLowBitsSet(
8675 N->getValueSizeInBits(0), PromBits),
8676 N->getValueType(0)));
8678 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8679 "Invalid extension type");
8680 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8682 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8683 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8684 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8685 N->getOperand(0), ShiftCst), ShiftCst);
8688 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8689 DAGCombinerInfo &DCI) const {
8690 assert((N->getOpcode() == ISD::SINT_TO_FP ||
8691 N->getOpcode() == ISD::UINT_TO_FP) &&
8692 "Need an int -> FP conversion node here");
8694 if (!Subtarget.has64BitSupport())
8697 SelectionDAG &DAG = DCI.DAG;
8701 // Don't handle ppc_fp128 here or i1 conversions.
8702 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8704 if (Op.getOperand(0).getValueType() == MVT::i1)
8707 // For i32 intermediate values, unfortunately, the conversion functions
8708 // leave the upper 32 bits of the value are undefined. Within the set of
8709 // scalar instructions, we have no method for zero- or sign-extending the
8710 // value. Thus, we cannot handle i32 intermediate values here.
8711 if (Op.getOperand(0).getValueType() == MVT::i32)
8714 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8715 "UINT_TO_FP is supported only with FPCVT");
8717 // If we have FCFIDS, then use it when converting to single-precision.
8718 // Otherwise, convert to double-precision and then round.
8719 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8720 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8722 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8724 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8728 // If we're converting from a float, to an int, and back to a float again,
8729 // then we don't need the store/load pair at all.
8730 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8731 Subtarget.hasFPCVT()) ||
8732 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8733 SDValue Src = Op.getOperand(0).getOperand(0);
8734 if (Src.getValueType() == MVT::f32) {
8735 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8736 DCI.AddToWorklist(Src.getNode());
8740 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8743 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8744 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8746 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8747 FP = DAG.getNode(ISD::FP_ROUND, dl,
8748 MVT::f32, FP, DAG.getIntPtrConstant(0));
8749 DCI.AddToWorklist(FP.getNode());
8758 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8759 // builtins) into loads with swaps.
8760 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8761 DAGCombinerInfo &DCI) const {
8762 SelectionDAG &DAG = DCI.DAG;
8766 MachineMemOperand *MMO;
8768 switch (N->getOpcode()) {
8770 llvm_unreachable("Unexpected opcode for little endian VSX load");
8772 LoadSDNode *LD = cast<LoadSDNode>(N);
8773 Chain = LD->getChain();
8774 Base = LD->getBasePtr();
8775 MMO = LD->getMemOperand();
8776 // If the MMO suggests this isn't a load of a full vector, leave
8777 // things alone. For a built-in, we have to make the change for
8778 // correctness, so if there is a size problem that will be a bug.
8779 if (MMO->getSize() < 16)
8783 case ISD::INTRINSIC_W_CHAIN: {
8784 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8785 Chain = Intrin->getChain();
8786 Base = Intrin->getBasePtr();
8787 MMO = Intrin->getMemOperand();
8792 MVT VecTy = N->getValueType(0).getSimpleVT();
8793 SDValue LoadOps[] = { Chain, Base };
8794 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8795 DAG.getVTList(VecTy, MVT::Other),
8796 LoadOps, VecTy, MMO);
8797 DCI.AddToWorklist(Load.getNode());
8798 Chain = Load.getValue(1);
8799 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8800 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8801 DCI.AddToWorklist(Swap.getNode());
8805 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8806 // builtins) into stores with swaps.
8807 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8808 DAGCombinerInfo &DCI) const {
8809 SelectionDAG &DAG = DCI.DAG;
8814 MachineMemOperand *MMO;
8816 switch (N->getOpcode()) {
8818 llvm_unreachable("Unexpected opcode for little endian VSX store");
8820 StoreSDNode *ST = cast<StoreSDNode>(N);
8821 Chain = ST->getChain();
8822 Base = ST->getBasePtr();
8823 MMO = ST->getMemOperand();
8825 // If the MMO suggests this isn't a store of a full vector, leave
8826 // things alone. For a built-in, we have to make the change for
8827 // correctness, so if there is a size problem that will be a bug.
8828 if (MMO->getSize() < 16)
8832 case ISD::INTRINSIC_VOID: {
8833 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8834 Chain = Intrin->getChain();
8835 // Intrin->getBasePtr() oddly does not get what we want.
8836 Base = Intrin->getOperand(3);
8837 MMO = Intrin->getMemOperand();
8843 SDValue Src = N->getOperand(SrcOpnd);
8844 MVT VecTy = Src.getValueType().getSimpleVT();
8845 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8846 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8847 DCI.AddToWorklist(Swap.getNode());
8848 Chain = Swap.getValue(1);
8849 SDValue StoreOps[] = { Chain, Swap, Base };
8850 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8851 DAG.getVTList(MVT::Other),
8852 StoreOps, VecTy, MMO);
8853 DCI.AddToWorklist(Store.getNode());
8857 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8858 DAGCombinerInfo &DCI) const {
8859 SelectionDAG &DAG = DCI.DAG;
8861 switch (N->getOpcode()) {
8864 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8865 if (C->isNullValue()) // 0 << V -> 0.
8866 return N->getOperand(0);
8870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8871 if (C->isNullValue()) // 0 >>u V -> 0.
8872 return N->getOperand(0);
8876 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8877 if (C->isNullValue() || // 0 >>s V -> 0.
8878 C->isAllOnesValue()) // -1 >>s V -> -1.
8879 return N->getOperand(0);
8882 case ISD::SIGN_EXTEND:
8883 case ISD::ZERO_EXTEND:
8884 case ISD::ANY_EXTEND:
8885 return DAGCombineExtBoolTrunc(N, DCI);
8888 case ISD::SELECT_CC:
8889 return DAGCombineTruncBoolExt(N, DCI);
8890 case ISD::SINT_TO_FP:
8891 case ISD::UINT_TO_FP:
8892 return combineFPToIntToFP(N, DCI);
8894 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8895 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
8896 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8897 N->getOperand(1).getValueType() == MVT::i32 &&
8898 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8899 SDValue Val = N->getOperand(1).getOperand(0);
8900 if (Val.getValueType() == MVT::f32) {
8901 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8902 DCI.AddToWorklist(Val.getNode());
8904 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8905 DCI.AddToWorklist(Val.getNode());
8908 N->getOperand(0), Val, N->getOperand(2),
8909 DAG.getValueType(N->getOperand(1).getValueType())
8912 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8913 DAG.getVTList(MVT::Other), Ops,
8914 cast<StoreSDNode>(N)->getMemoryVT(),
8915 cast<StoreSDNode>(N)->getMemOperand());
8916 DCI.AddToWorklist(Val.getNode());
8920 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8921 if (cast<StoreSDNode>(N)->isUnindexed() &&
8922 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8923 N->getOperand(1).getNode()->hasOneUse() &&
8924 (N->getOperand(1).getValueType() == MVT::i32 ||
8925 N->getOperand(1).getValueType() == MVT::i16 ||
8926 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
8927 N->getOperand(1).getValueType() == MVT::i64))) {
8928 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8929 // Do an any-extend to 32-bits if this is a half-word input.
8930 if (BSwapOp.getValueType() == MVT::i16)
8931 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8934 N->getOperand(0), BSwapOp, N->getOperand(2),
8935 DAG.getValueType(N->getOperand(1).getValueType())
8938 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8939 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8940 cast<StoreSDNode>(N)->getMemOperand());
8943 // For little endian, VSX stores require generating xxswapd/lxvd2x.
8944 EVT VT = N->getOperand(1).getValueType();
8945 if (VT.isSimple()) {
8946 MVT StoreVT = VT.getSimpleVT();
8947 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8948 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8949 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8950 return expandVSXStoreForLE(N, DCI);
8955 LoadSDNode *LD = cast<LoadSDNode>(N);
8956 EVT VT = LD->getValueType(0);
8958 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8959 if (VT.isSimple()) {
8960 MVT LoadVT = VT.getSimpleVT();
8961 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8962 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8963 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8964 return expandVSXLoadForLE(N, DCI);
8967 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8968 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8969 if (ISD::isNON_EXTLoad(N) && VT.isVector() && Subtarget.hasAltivec() &&
8970 // P8 and later hardware should just use LOAD.
8971 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8972 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8973 LD->getAlignment() < ABIAlignment) {
8974 // This is a type-legal unaligned Altivec load.
8975 SDValue Chain = LD->getChain();
8976 SDValue Ptr = LD->getBasePtr();
8977 bool isLittleEndian = Subtarget.isLittleEndian();
8979 // This implements the loading of unaligned vectors as described in
8980 // the venerable Apple Velocity Engine overview. Specifically:
8981 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8982 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8984 // The general idea is to expand a sequence of one or more unaligned
8985 // loads into an alignment-based permutation-control instruction (lvsl
8986 // or lvsr), a series of regular vector loads (which always truncate
8987 // their input address to an aligned address), and a series of
8988 // permutations. The results of these permutations are the requested
8989 // loaded values. The trick is that the last "extra" load is not taken
8990 // from the address you might suspect (sizeof(vector) bytes after the
8991 // last requested load), but rather sizeof(vector) - 1 bytes after the
8992 // last requested vector. The point of this is to avoid a page fault if
8993 // the base address happened to be aligned. This works because if the
8994 // base address is aligned, then adding less than a full vector length
8995 // will cause the last vector in the sequence to be (re)loaded.
8996 // Otherwise, the next vector will be fetched as you might suspect was
8999 // We might be able to reuse the permutation generation from
9000 // a different base address offset from this one by an aligned amount.
9001 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9002 // optimization later.
9003 Intrinsic::ID Intr = (isLittleEndian ?
9004 Intrinsic::ppc_altivec_lvsr :
9005 Intrinsic::ppc_altivec_lvsl);
9006 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
9008 // Create the new MMO for the new base load. It is like the original MMO,
9009 // but represents an area in memory almost twice the vector size centered
9010 // on the original address. If the address is unaligned, we might start
9011 // reading up to (sizeof(vector)-1) bytes below the address of the
9012 // original unaligned load.
9013 MachineFunction &MF = DAG.getMachineFunction();
9014 MachineMemOperand *BaseMMO =
9015 MF.getMachineMemOperand(LD->getMemOperand(),
9016 -LD->getMemoryVT().getStoreSize()+1,
9017 2*LD->getMemoryVT().getStoreSize()-1);
9019 // Create the new base load.
9020 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
9022 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9024 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9025 DAG.getVTList(MVT::v4i32, MVT::Other),
9026 BaseLoadOps, MVT::v4i32, BaseMMO);
9028 // Note that the value of IncOffset (which is provided to the next
9029 // load's pointer info offset value, and thus used to calculate the
9030 // alignment), and the value of IncValue (which is actually used to
9031 // increment the pointer value) are different! This is because we
9032 // require the next load to appear to be aligned, even though it
9033 // is actually offset from the base pointer by a lesser amount.
9034 int IncOffset = VT.getSizeInBits() / 8;
9035 int IncValue = IncOffset;
9037 // Walk (both up and down) the chain looking for another load at the real
9038 // (aligned) offset (the alignment of the other load does not matter in
9039 // this case). If found, then do not use the offset reduction trick, as
9040 // that will prevent the loads from being later combined (as they would
9041 // otherwise be duplicates).
9042 if (!findConsecutiveLoad(LD, DAG))
9045 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9046 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9048 MachineMemOperand *ExtraMMO =
9049 MF.getMachineMemOperand(LD->getMemOperand(),
9050 1, 2*LD->getMemoryVT().getStoreSize()-1);
9051 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9053 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9054 DAG.getVTList(MVT::v4i32, MVT::Other),
9055 ExtraLoadOps, MVT::v4i32, ExtraMMO);
9057 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9058 BaseLoad.getValue(1), ExtraLoad.getValue(1));
9060 // Because vperm has a big-endian bias, we must reverse the order
9061 // of the input vectors and complement the permute control vector
9062 // when generating little endian code. We have already handled the
9063 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9064 // and ExtraLoad here.
9067 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9068 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9070 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9071 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9073 if (VT != MVT::v4i32)
9074 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
9076 // The output of the permutation is our loaded result, the TokenFactor is
9078 DCI.CombineTo(N, Perm, TF);
9079 return SDValue(N, 0);
9083 case ISD::INTRINSIC_WO_CHAIN: {
9084 bool isLittleEndian = Subtarget.isLittleEndian();
9085 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9086 : Intrinsic::ppc_altivec_lvsl);
9087 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
9088 N->getOperand(1)->getOpcode() == ISD::ADD) {
9089 SDValue Add = N->getOperand(1);
9091 if (DAG.MaskedValueIsZero(
9093 APInt::getAllOnesValue(4 /* 16 byte alignment */)
9095 Add.getValueType().getScalarType().getSizeInBits()))) {
9096 SDNode *BasePtr = Add->getOperand(0).getNode();
9097 for (SDNode::use_iterator UI = BasePtr->use_begin(),
9098 UE = BasePtr->use_end();
9100 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9101 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
9103 // We've found another LVSL/LVSR, and this address is an aligned
9104 // multiple of that one. The results will be the same, so use the
9105 // one we've just found instead.
9107 return SDValue(*UI, 0);
9115 case ISD::INTRINSIC_W_CHAIN: {
9116 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9117 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9118 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9121 case Intrinsic::ppc_vsx_lxvw4x:
9122 case Intrinsic::ppc_vsx_lxvd2x:
9123 return expandVSXLoadForLE(N, DCI);
9128 case ISD::INTRINSIC_VOID: {
9129 // For little endian, VSX stores require generating xxswapd/stxvd2x.
9130 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9131 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9134 case Intrinsic::ppc_vsx_stxvw4x:
9135 case Intrinsic::ppc_vsx_stxvd2x:
9136 return expandVSXStoreForLE(N, DCI);
9142 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
9143 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
9144 N->getOperand(0).hasOneUse() &&
9145 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
9146 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9147 N->getValueType(0) == MVT::i64))) {
9148 SDValue Load = N->getOperand(0);
9149 LoadSDNode *LD = cast<LoadSDNode>(Load);
9150 // Create the byte-swapping load.
9152 LD->getChain(), // Chain
9153 LD->getBasePtr(), // Ptr
9154 DAG.getValueType(N->getValueType(0)) // VT
9157 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
9158 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
9159 MVT::i64 : MVT::i32, MVT::Other),
9160 Ops, LD->getMemoryVT(), LD->getMemOperand());
9162 // If this is an i16 load, insert the truncate.
9163 SDValue ResVal = BSLoad;
9164 if (N->getValueType(0) == MVT::i16)
9165 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
9167 // First, combine the bswap away. This makes the value produced by the
9169 DCI.CombineTo(N, ResVal);
9171 // Next, combine the load away, we give it a bogus result value but a real
9172 // chain result. The result value is dead because the bswap is dead.
9173 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9175 // Return N so it doesn't get rechecked!
9176 return SDValue(N, 0);
9180 case PPCISD::VCMP: {
9181 // If a VCMPo node already exists with exactly the same operands as this
9182 // node, use its result instead of this node (VCMPo computes both a CR6 and
9183 // a normal output).
9185 if (!N->getOperand(0).hasOneUse() &&
9186 !N->getOperand(1).hasOneUse() &&
9187 !N->getOperand(2).hasOneUse()) {
9189 // Scan all of the users of the LHS, looking for VCMPo's that match.
9190 SDNode *VCMPoNode = nullptr;
9192 SDNode *LHSN = N->getOperand(0).getNode();
9193 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9195 if (UI->getOpcode() == PPCISD::VCMPo &&
9196 UI->getOperand(1) == N->getOperand(1) &&
9197 UI->getOperand(2) == N->getOperand(2) &&
9198 UI->getOperand(0) == N->getOperand(0)) {
9203 // If there is no VCMPo node, or if the flag value has a single use, don't
9205 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9208 // Look at the (necessarily single) use of the flag value. If it has a
9209 // chain, this transformation is more complex. Note that multiple things
9210 // could use the value result, which we should ignore.
9211 SDNode *FlagUser = nullptr;
9212 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9213 FlagUser == nullptr; ++UI) {
9214 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9216 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9217 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9224 // If the user is a MFOCRF instruction, we know this is safe.
9225 // Otherwise we give up for right now.
9226 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9227 return SDValue(VCMPoNode, 0);
9232 SDValue Cond = N->getOperand(1);
9233 SDValue Target = N->getOperand(2);
9235 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9236 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9237 Intrinsic::ppc_is_decremented_ctr_nonzero) {
9239 // We now need to make the intrinsic dead (it cannot be instruction
9241 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9242 assert(Cond.getNode()->hasOneUse() &&
9243 "Counter decrement has more than one use");
9245 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9246 N->getOperand(0), Target);
9251 // If this is a branch on an altivec predicate comparison, lower this so
9252 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
9253 // lowering is done pre-legalize, because the legalizer lowers the predicate
9254 // compare down to code that is difficult to reassemble.
9255 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9256 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9258 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9259 // value. If so, pass-through the AND to get to the intrinsic.
9260 if (LHS.getOpcode() == ISD::AND &&
9261 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9262 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9263 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9264 isa<ConstantSDNode>(LHS.getOperand(1)) &&
9265 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9267 LHS = LHS.getOperand(0);
9269 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9270 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9271 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9272 isa<ConstantSDNode>(RHS)) {
9273 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9274 "Counter decrement comparison is not EQ or NE");
9276 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9277 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9278 (CC == ISD::SETNE && !Val);
9280 // We now need to make the intrinsic dead (it cannot be instruction
9282 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9283 assert(LHS.getNode()->hasOneUse() &&
9284 "Counter decrement has more than one use");
9286 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9287 N->getOperand(0), N->getOperand(4));
9293 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9294 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9295 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9296 assert(isDot && "Can't compare against a vector result!");
9298 // If this is a comparison against something other than 0/1, then we know
9299 // that the condition is never/always true.
9300 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9301 if (Val != 0 && Val != 1) {
9302 if (CC == ISD::SETEQ) // Cond never true, remove branch.
9303 return N->getOperand(0);
9304 // Always !=, turn it into an unconditional branch.
9305 return DAG.getNode(ISD::BR, dl, MVT::Other,
9306 N->getOperand(0), N->getOperand(4));
9309 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9311 // Create the PPCISD altivec 'dot' comparison node.
9313 LHS.getOperand(2), // LHS of compare
9314 LHS.getOperand(3), // RHS of compare
9315 DAG.getConstant(CompareOpc, MVT::i32)
9317 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9318 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9320 // Unpack the result based on how the target uses it.
9321 PPC::Predicate CompOpc;
9322 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9323 default: // Can't happen, don't crash on invalid number though.
9324 case 0: // Branch on the value of the EQ bit of CR6.
9325 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9327 case 1: // Branch on the inverted value of the EQ bit of CR6.
9328 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9330 case 2: // Branch on the value of the LT bit of CR6.
9331 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9333 case 3: // Branch on the inverted value of the LT bit of CR6.
9334 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9338 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9339 DAG.getConstant(CompOpc, MVT::i32),
9340 DAG.getRegister(PPC::CR6, MVT::i32),
9341 N->getOperand(4), CompNode.getValue(1));
9351 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9353 std::vector<SDNode *> *Created) const {
9354 // fold (sdiv X, pow2)
9355 EVT VT = N->getValueType(0);
9356 if (VT == MVT::i64 && !Subtarget.isPPC64())
9358 if ((VT != MVT::i32 && VT != MVT::i64) ||
9359 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9363 SDValue N0 = N->getOperand(0);
9365 bool IsNegPow2 = (-Divisor).isPowerOf2();
9366 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9367 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9369 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9371 Created->push_back(Op.getNode());
9374 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9376 Created->push_back(Op.getNode());
9382 //===----------------------------------------------------------------------===//
9383 // Inline Assembly Support
9384 //===----------------------------------------------------------------------===//
9386 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9389 const SelectionDAG &DAG,
9390 unsigned Depth) const {
9391 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9392 switch (Op.getOpcode()) {
9394 case PPCISD::LBRX: {
9395 // lhbrx is known to have the top bits cleared out.
9396 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9397 KnownZero = 0xFFFF0000;
9400 case ISD::INTRINSIC_WO_CHAIN: {
9401 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9403 case Intrinsic::ppc_altivec_vcmpbfp_p:
9404 case Intrinsic::ppc_altivec_vcmpeqfp_p:
9405 case Intrinsic::ppc_altivec_vcmpequb_p:
9406 case Intrinsic::ppc_altivec_vcmpequh_p:
9407 case Intrinsic::ppc_altivec_vcmpequw_p:
9408 case Intrinsic::ppc_altivec_vcmpgefp_p:
9409 case Intrinsic::ppc_altivec_vcmpgtfp_p:
9410 case Intrinsic::ppc_altivec_vcmpgtsb_p:
9411 case Intrinsic::ppc_altivec_vcmpgtsh_p:
9412 case Intrinsic::ppc_altivec_vcmpgtsw_p:
9413 case Intrinsic::ppc_altivec_vcmpgtub_p:
9414 case Intrinsic::ppc_altivec_vcmpgtuh_p:
9415 case Intrinsic::ppc_altivec_vcmpgtuw_p:
9416 KnownZero = ~1U; // All bits but the low one are known to be zero.
9423 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9424 switch (Subtarget.getDarwinDirective()) {
9429 case PPC::DIR_PWR5X:
9431 case PPC::DIR_PWR6X:
9433 case PPC::DIR_PWR8: {
9437 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
9439 // For small loops (between 5 and 8 instructions), align to a 32-byte
9440 // boundary so that the entire loop fits in one instruction-cache line.
9441 uint64_t LoopSize = 0;
9442 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9443 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9444 LoopSize += TII->GetInstSizeInBytes(J);
9446 if (LoopSize > 16 && LoopSize <= 32)
9453 return TargetLowering::getPrefLoopAlignment(ML);
9456 /// getConstraintType - Given a constraint, return the type of
9457 /// constraint it is for this target.
9458 PPCTargetLowering::ConstraintType
9459 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9460 if (Constraint.size() == 1) {
9461 switch (Constraint[0]) {
9468 return C_RegisterClass;
9470 // FIXME: While Z does indicate a memory constraint, it specifically
9471 // indicates an r+r address (used in conjunction with the 'y' modifier
9472 // in the replacement string). Currently, we're forcing the base
9473 // register to be r0 in the asm printer (which is interpreted as zero)
9474 // and forming the complete address in the second register. This is
9478 } else if (Constraint == "wc") { // individual CR bits.
9479 return C_RegisterClass;
9480 } else if (Constraint == "wa" || Constraint == "wd" ||
9481 Constraint == "wf" || Constraint == "ws") {
9482 return C_RegisterClass; // VSX registers.
9484 return TargetLowering::getConstraintType(Constraint);
9487 /// Examine constraint type and operand type and determine a weight value.
9488 /// This object must already have been set up with the operand type
9489 /// and the current alternative constraint selected.
9490 TargetLowering::ConstraintWeight
9491 PPCTargetLowering::getSingleConstraintMatchWeight(
9492 AsmOperandInfo &info, const char *constraint) const {
9493 ConstraintWeight weight = CW_Invalid;
9494 Value *CallOperandVal = info.CallOperandVal;
9495 // If we don't have a value, we can't do a match,
9496 // but allow it at the lowest weight.
9497 if (!CallOperandVal)
9499 Type *type = CallOperandVal->getType();
9501 // Look at the constraint type.
9502 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9503 return CW_Register; // an individual CR bit.
9504 else if ((StringRef(constraint) == "wa" ||
9505 StringRef(constraint) == "wd" ||
9506 StringRef(constraint) == "wf") &&
9509 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9512 switch (*constraint) {
9514 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9517 if (type->isIntegerTy())
9518 weight = CW_Register;
9521 if (type->isFloatTy())
9522 weight = CW_Register;
9525 if (type->isDoubleTy())
9526 weight = CW_Register;
9529 if (type->isVectorTy())
9530 weight = CW_Register;
9533 weight = CW_Register;
9542 std::pair<unsigned, const TargetRegisterClass*>
9543 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9545 if (Constraint.size() == 1) {
9546 // GCC RS6000 Constraint Letters
9547 switch (Constraint[0]) {
9549 if (VT == MVT::i64 && Subtarget.isPPC64())
9550 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9551 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9553 if (VT == MVT::i64 && Subtarget.isPPC64())
9554 return std::make_pair(0U, &PPC::G8RCRegClass);
9555 return std::make_pair(0U, &PPC::GPRCRegClass);
9557 if (VT == MVT::f32 || VT == MVT::i32)
9558 return std::make_pair(0U, &PPC::F4RCRegClass);
9559 if (VT == MVT::f64 || VT == MVT::i64)
9560 return std::make_pair(0U, &PPC::F8RCRegClass);
9563 return std::make_pair(0U, &PPC::VRRCRegClass);
9565 return std::make_pair(0U, &PPC::CRRCRegClass);
9567 } else if (Constraint == "wc") { // an individual CR bit.
9568 return std::make_pair(0U, &PPC::CRBITRCRegClass);
9569 } else if (Constraint == "wa" || Constraint == "wd" ||
9570 Constraint == "wf") {
9571 return std::make_pair(0U, &PPC::VSRCRegClass);
9572 } else if (Constraint == "ws") {
9573 return std::make_pair(0U, &PPC::VSFRCRegClass);
9576 std::pair<unsigned, const TargetRegisterClass*> R =
9577 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9579 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9580 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9581 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9583 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9584 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9585 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9586 PPC::GPRCRegClass.contains(R.first)) {
9587 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9588 return std::make_pair(TRI->getMatchingSuperReg(R.first,
9589 PPC::sub_32, &PPC::G8RCRegClass),
9590 &PPC::G8RCRegClass);
9593 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9594 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9596 R.second = &PPC::CRRCRegClass;
9603 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9604 /// vector. If it is invalid, don't add anything to Ops.
9605 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9606 std::string &Constraint,
9607 std::vector<SDValue>&Ops,
9608 SelectionDAG &DAG) const {
9611 // Only support length 1 constraints.
9612 if (Constraint.length() > 1) return;
9614 char Letter = Constraint[0];
9625 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9626 if (!CST) return; // Must be an immediate to match.
9627 int64_t Value = CST->getSExtValue();
9628 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9629 // numbers are printed as such.
9631 default: llvm_unreachable("Unknown constraint letter!");
9632 case 'I': // "I" is a signed 16-bit constant.
9633 if (isInt<16>(Value))
9634 Result = DAG.getTargetConstant(Value, TCVT);
9636 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9637 if (isShiftedUInt<16, 16>(Value))
9638 Result = DAG.getTargetConstant(Value, TCVT);
9640 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9641 if (isShiftedInt<16, 16>(Value))
9642 Result = DAG.getTargetConstant(Value, TCVT);
9644 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9645 if (isUInt<16>(Value))
9646 Result = DAG.getTargetConstant(Value, TCVT);
9648 case 'M': // "M" is a constant that is greater than 31.
9650 Result = DAG.getTargetConstant(Value, TCVT);
9652 case 'N': // "N" is a positive constant that is an exact power of two.
9653 if (Value > 0 && isPowerOf2_64(Value))
9654 Result = DAG.getTargetConstant(Value, TCVT);
9656 case 'O': // "O" is the constant zero.
9658 Result = DAG.getTargetConstant(Value, TCVT);
9660 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9661 if (isInt<16>(-Value))
9662 Result = DAG.getTargetConstant(Value, TCVT);
9669 if (Result.getNode()) {
9670 Ops.push_back(Result);
9674 // Handle standard constraint letters.
9675 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9678 // isLegalAddressingMode - Return true if the addressing mode represented
9679 // by AM is legal for this target, for a load/store of the specified type.
9680 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9682 // FIXME: PPC does not allow r+i addressing modes for vectors!
9684 // PPC allows a sign-extended 16-bit immediate field.
9685 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9688 // No global is ever allowed as a base.
9692 // PPC only support r+r,
9694 case 0: // "r+i" or just "i", depending on HasBaseReg.
9697 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9699 // Otherwise we have r+r or r+i.
9702 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9704 // Allow 2*r as r+r.
9707 // No other scales are supported.
9714 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9715 SelectionDAG &DAG) const {
9716 MachineFunction &MF = DAG.getMachineFunction();
9717 MachineFrameInfo *MFI = MF.getFrameInfo();
9718 MFI->setReturnAddressIsTaken(true);
9720 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9724 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9726 // Make sure the function does not optimize away the store of the RA to
9728 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9729 FuncInfo->setLRStoreRequired();
9730 bool isPPC64 = Subtarget.isPPC64();
9731 bool isDarwinABI = Subtarget.isDarwinABI();
9734 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9737 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9738 isPPC64? MVT::i64 : MVT::i32);
9739 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9740 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9742 MachinePointerInfo(), false, false, false, 0);
9745 // Just load the return address off the stack.
9746 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9747 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9748 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9751 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9752 SelectionDAG &DAG) const {
9754 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9756 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9757 bool isPPC64 = PtrVT == MVT::i64;
9759 MachineFunction &MF = DAG.getMachineFunction();
9760 MachineFrameInfo *MFI = MF.getFrameInfo();
9761 MFI->setFrameAddressIsTaken(true);
9763 // Naked functions never have a frame pointer, and so we use r1. For all
9764 // other functions, this decision must be delayed until during PEI.
9766 if (MF.getFunction()->getAttributes().hasAttribute(
9767 AttributeSet::FunctionIndex, Attribute::Naked))
9768 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9770 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9772 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9775 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9776 FrameAddr, MachinePointerInfo(), false, false,
9781 // FIXME? Maybe this could be a TableGen attribute on some registers and
9782 // this table could be generated automatically from RegInfo.
9783 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9785 bool isPPC64 = Subtarget.isPPC64();
9786 bool isDarwinABI = Subtarget.isDarwinABI();
9788 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9789 (!isPPC64 && VT != MVT::i32))
9790 report_fatal_error("Invalid register global variable type");
9792 bool is64Bit = isPPC64 && VT == MVT::i64;
9793 unsigned Reg = StringSwitch<unsigned>(RegName)
9794 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9795 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
9796 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9797 (is64Bit ? PPC::X13 : PPC::R13))
9802 report_fatal_error("Invalid register name global variable");
9806 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9807 // The PowerPC target isn't yet aware of offsets.
9811 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9813 unsigned Intrinsic) const {
9815 switch (Intrinsic) {
9816 case Intrinsic::ppc_altivec_lvx:
9817 case Intrinsic::ppc_altivec_lvxl:
9818 case Intrinsic::ppc_altivec_lvebx:
9819 case Intrinsic::ppc_altivec_lvehx:
9820 case Intrinsic::ppc_altivec_lvewx:
9821 case Intrinsic::ppc_vsx_lxvd2x:
9822 case Intrinsic::ppc_vsx_lxvw4x: {
9824 switch (Intrinsic) {
9825 case Intrinsic::ppc_altivec_lvebx:
9828 case Intrinsic::ppc_altivec_lvehx:
9831 case Intrinsic::ppc_altivec_lvewx:
9834 case Intrinsic::ppc_vsx_lxvd2x:
9842 Info.opc = ISD::INTRINSIC_W_CHAIN;
9844 Info.ptrVal = I.getArgOperand(0);
9845 Info.offset = -VT.getStoreSize()+1;
9846 Info.size = 2*VT.getStoreSize()-1;
9849 Info.readMem = true;
9850 Info.writeMem = false;
9853 case Intrinsic::ppc_altivec_stvx:
9854 case Intrinsic::ppc_altivec_stvxl:
9855 case Intrinsic::ppc_altivec_stvebx:
9856 case Intrinsic::ppc_altivec_stvehx:
9857 case Intrinsic::ppc_altivec_stvewx:
9858 case Intrinsic::ppc_vsx_stxvd2x:
9859 case Intrinsic::ppc_vsx_stxvw4x: {
9861 switch (Intrinsic) {
9862 case Intrinsic::ppc_altivec_stvebx:
9865 case Intrinsic::ppc_altivec_stvehx:
9868 case Intrinsic::ppc_altivec_stvewx:
9871 case Intrinsic::ppc_vsx_stxvd2x:
9879 Info.opc = ISD::INTRINSIC_VOID;
9881 Info.ptrVal = I.getArgOperand(1);
9882 Info.offset = -VT.getStoreSize()+1;
9883 Info.size = 2*VT.getStoreSize()-1;
9886 Info.readMem = false;
9887 Info.writeMem = true;
9897 /// getOptimalMemOpType - Returns the target specific optimal type for load
9898 /// and store operations as a result of memset, memcpy, and memmove
9899 /// lowering. If DstAlign is zero that means it's safe to destination
9900 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9901 /// means there isn't a need to check it against alignment requirement,
9902 /// probably because the source does not need to be loaded. If 'IsMemset' is
9903 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9904 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9905 /// source is constant so it does not need to be loaded.
9906 /// It returns EVT::Other if the type should be determined using generic
9907 /// target-independent logic.
9908 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9909 unsigned DstAlign, unsigned SrcAlign,
9910 bool IsMemset, bool ZeroMemset,
9912 MachineFunction &MF) const {
9913 if (Subtarget.isPPC64()) {
9920 /// \brief Returns true if it is beneficial to convert a load of a constant
9921 /// to just the constant itself.
9922 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9924 assert(Ty->isIntegerTy());
9926 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9927 if (BitSize == 0 || BitSize > 64)
9932 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9933 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9935 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9936 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9937 return NumBits1 == 64 && NumBits2 == 32;
9940 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9941 if (!VT1.isInteger() || !VT2.isInteger())
9943 unsigned NumBits1 = VT1.getSizeInBits();
9944 unsigned NumBits2 = VT2.getSizeInBits();
9945 return NumBits1 == 64 && NumBits2 == 32;
9948 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9949 // Generally speaking, zexts are not free, but they are free when they can be
9950 // folded with other operations.
9951 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
9952 EVT MemVT = LD->getMemoryVT();
9953 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
9954 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
9955 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
9956 LD->getExtensionType() == ISD::ZEXTLOAD))
9960 // FIXME: Add other cases...
9961 // - 32-bit shifts with a zext to i64
9962 // - zext after ctlz, bswap, etc.
9963 // - zext after and by a constant mask
9965 return TargetLowering::isZExtFree(Val, VT2);
9968 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
9969 assert(VT.isFloatingPoint());
9973 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9974 return isInt<16>(Imm) || isUInt<16>(Imm);
9977 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9978 return isInt<16>(Imm) || isUInt<16>(Imm);
9981 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9985 if (DisablePPCUnaligned)
9988 // PowerPC supports unaligned memory access for simple non-vector types.
9989 // Although accessing unaligned addresses is not as efficient as accessing
9990 // aligned addresses, it is generally more efficient than manual expansion,
9991 // and generally only traps for software emulation when crossing page
9997 if (VT.getSimpleVT().isVector()) {
9998 if (Subtarget.hasVSX()) {
9999 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
10000 VT != MVT::v4f32 && VT != MVT::v4i32)
10007 if (VT == MVT::ppcf128)
10016 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
10017 VT = VT.getScalarType();
10019 if (!VT.isSimple())
10022 switch (VT.getSimpleVT().SimpleTy) {
10034 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
10035 // LR is a callee-save register, but we must treat it as clobbered by any call
10036 // site. Hence we include LR in the scratch registers, which are in turn added
10037 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
10038 // to CTR, which is used by any indirect call.
10039 static const MCPhysReg ScratchRegs[] = {
10040 PPC::X12, PPC::LR8, PPC::CTR8, 0
10043 return ScratchRegs;
10047 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
10048 EVT VT , unsigned DefinedValues) const {
10049 if (VT == MVT::v2i64)
10052 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
10055 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
10056 if (DisableILPPref || Subtarget.enableMachineScheduler())
10057 return TargetLowering::getSchedulingPreference(N);
10062 // Create a fast isel object.
10064 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
10065 const TargetLibraryInfo *LibInfo) const {
10066 return PPC::createFastISel(FuncInfo, LibInfo);