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 // Vector popcnt instructions introduced in P8
405 if (Subtarget.hasP8Altivec())
406 setOperationAction(ISD::CTPOP, VT, Legal);
408 setOperationAction(ISD::CTPOP, VT, Expand);
410 // We promote all shuffles to v16i8.
411 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
412 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
414 // We promote all non-typed operations to v4i32.
415 setOperationAction(ISD::AND , VT, Promote);
416 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
417 setOperationAction(ISD::OR , VT, Promote);
418 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
419 setOperationAction(ISD::XOR , VT, Promote);
420 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
421 setOperationAction(ISD::LOAD , VT, Promote);
422 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
423 setOperationAction(ISD::SELECT, VT, Promote);
424 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
425 setOperationAction(ISD::STORE, VT, Promote);
426 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
428 // No other operations are legal.
429 setOperationAction(ISD::MUL , VT, Expand);
430 setOperationAction(ISD::SDIV, VT, Expand);
431 setOperationAction(ISD::SREM, VT, Expand);
432 setOperationAction(ISD::UDIV, VT, Expand);
433 setOperationAction(ISD::UREM, VT, Expand);
434 setOperationAction(ISD::FDIV, VT, Expand);
435 setOperationAction(ISD::FREM, VT, Expand);
436 setOperationAction(ISD::FNEG, VT, Expand);
437 setOperationAction(ISD::FSQRT, VT, Expand);
438 setOperationAction(ISD::FLOG, VT, Expand);
439 setOperationAction(ISD::FLOG10, VT, Expand);
440 setOperationAction(ISD::FLOG2, VT, Expand);
441 setOperationAction(ISD::FEXP, VT, Expand);
442 setOperationAction(ISD::FEXP2, VT, Expand);
443 setOperationAction(ISD::FSIN, VT, Expand);
444 setOperationAction(ISD::FCOS, VT, Expand);
445 setOperationAction(ISD::FABS, VT, Expand);
446 setOperationAction(ISD::FPOWI, VT, Expand);
447 setOperationAction(ISD::FFLOOR, VT, Expand);
448 setOperationAction(ISD::FCEIL, VT, Expand);
449 setOperationAction(ISD::FTRUNC, VT, Expand);
450 setOperationAction(ISD::FRINT, VT, Expand);
451 setOperationAction(ISD::FNEARBYINT, VT, Expand);
452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
453 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
454 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
455 setOperationAction(ISD::MULHU, VT, Expand);
456 setOperationAction(ISD::MULHS, VT, Expand);
457 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
458 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
459 setOperationAction(ISD::UDIVREM, VT, Expand);
460 setOperationAction(ISD::SDIVREM, VT, Expand);
461 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
462 setOperationAction(ISD::FPOW, VT, Expand);
463 setOperationAction(ISD::BSWAP, VT, Expand);
464 setOperationAction(ISD::CTLZ, VT, Expand);
465 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
466 setOperationAction(ISD::CTTZ, VT, Expand);
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
468 setOperationAction(ISD::VSELECT, VT, Expand);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
471 for (MVT InnerVT : MVT::vector_valuetypes()) {
472 setTruncStoreAction(VT, InnerVT, Expand);
473 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
474 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
475 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
479 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
480 // with merges, splats, etc.
481 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
483 setOperationAction(ISD::AND , MVT::v4i32, Legal);
484 setOperationAction(ISD::OR , MVT::v4i32, Legal);
485 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
486 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
487 setOperationAction(ISD::SELECT, MVT::v4i32,
488 Subtarget.useCRBits() ? Legal : Expand);
489 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
490 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
491 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
492 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
493 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
494 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
495 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
496 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
497 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
499 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
500 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
501 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
502 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
504 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
505 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
507 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
508 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
509 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
512 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
513 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
516 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
517 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
519 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
522 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
524 // Altivec does not contain unordered floating-point compare instructions
525 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
526 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
527 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
530 if (Subtarget.hasVSX()) {
531 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
532 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
534 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
535 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
536 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
537 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
538 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
540 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
542 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
543 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
545 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
546 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
548 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
549 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
550 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
551 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
552 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
554 // Share the Altivec comparison restrictions.
555 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
556 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
557 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
558 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
560 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
561 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
563 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
565 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
567 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
568 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
570 // VSX v2i64 only supports non-arithmetic operations.
571 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
572 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
574 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
575 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
576 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
578 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
580 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
581 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
582 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
583 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
585 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
587 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
588 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
589 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
590 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
592 // Vector operation legalization checks the result type of
593 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
594 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
595 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
596 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
597 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
599 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
602 if (Subtarget.hasP8Altivec())
603 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
606 if (Subtarget.has64BitSupport())
607 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
609 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
612 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
613 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
616 setBooleanContents(ZeroOrOneBooleanContent);
617 // Altivec instructions set fields to all zeros or all ones.
618 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
621 // These libcalls are not available in 32-bit.
622 setLibcallName(RTLIB::SHL_I128, nullptr);
623 setLibcallName(RTLIB::SRL_I128, nullptr);
624 setLibcallName(RTLIB::SRA_I128, nullptr);
628 setStackPointerRegisterToSaveRestore(PPC::X1);
629 setExceptionPointerRegister(PPC::X3);
630 setExceptionSelectorRegister(PPC::X4);
632 setStackPointerRegisterToSaveRestore(PPC::R1);
633 setExceptionPointerRegister(PPC::R3);
634 setExceptionSelectorRegister(PPC::R4);
637 // We have target-specific dag combine patterns for the following nodes:
638 setTargetDAGCombine(ISD::SINT_TO_FP);
639 if (Subtarget.hasFPCVT())
640 setTargetDAGCombine(ISD::UINT_TO_FP);
641 setTargetDAGCombine(ISD::LOAD);
642 setTargetDAGCombine(ISD::STORE);
643 setTargetDAGCombine(ISD::BR_CC);
644 if (Subtarget.useCRBits())
645 setTargetDAGCombine(ISD::BRCOND);
646 setTargetDAGCombine(ISD::BSWAP);
647 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
648 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
649 setTargetDAGCombine(ISD::INTRINSIC_VOID);
651 setTargetDAGCombine(ISD::SIGN_EXTEND);
652 setTargetDAGCombine(ISD::ZERO_EXTEND);
653 setTargetDAGCombine(ISD::ANY_EXTEND);
655 if (Subtarget.useCRBits()) {
656 setTargetDAGCombine(ISD::TRUNCATE);
657 setTargetDAGCombine(ISD::SETCC);
658 setTargetDAGCombine(ISD::SELECT_CC);
661 // Use reciprocal estimates.
662 if (TM.Options.UnsafeFPMath) {
663 setTargetDAGCombine(ISD::FDIV);
664 setTargetDAGCombine(ISD::FSQRT);
667 // Darwin long double math library functions have $LDBL128 appended.
668 if (Subtarget.isDarwin()) {
669 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
670 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
671 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
672 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
673 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
674 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
675 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
676 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
677 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
678 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
681 // With 32 condition bits, we don't need to sink (and duplicate) compares
682 // aggressively in CodeGenPrep.
683 if (Subtarget.useCRBits())
684 setHasMultipleConditionRegisters();
686 setMinFunctionAlignment(2);
687 if (Subtarget.isDarwin())
688 setPrefFunctionAlignment(4);
690 switch (Subtarget.getDarwinDirective()) {
694 case PPC::DIR_E500mc:
703 setPrefFunctionAlignment(4);
704 setPrefLoopAlignment(4);
708 setInsertFencesForAtomic(true);
710 if (Subtarget.enableMachineScheduler())
711 setSchedulingPreference(Sched::Source);
713 setSchedulingPreference(Sched::Hybrid);
715 computeRegisterProperties();
717 // The Freescale cores do better with aggressive inlining of memcpy and
718 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
719 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
720 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
721 MaxStoresPerMemset = 32;
722 MaxStoresPerMemsetOptSize = 16;
723 MaxStoresPerMemcpy = 32;
724 MaxStoresPerMemcpyOptSize = 8;
725 MaxStoresPerMemmove = 32;
726 MaxStoresPerMemmoveOptSize = 8;
730 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
731 /// the desired ByVal argument alignment.
732 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
733 unsigned MaxMaxAlign) {
734 if (MaxAlign == MaxMaxAlign)
736 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
737 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
739 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
741 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
742 unsigned EltAlign = 0;
743 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
744 if (EltAlign > MaxAlign)
746 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
747 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
748 unsigned EltAlign = 0;
749 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
750 if (EltAlign > MaxAlign)
752 if (MaxAlign == MaxMaxAlign)
758 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
759 /// function arguments in the caller parameter area.
760 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
761 // Darwin passes everything on 4 byte boundary.
762 if (Subtarget.isDarwin())
765 // 16byte and wider vectors are passed on 16byte boundary.
766 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
767 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
768 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
769 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
773 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
775 default: return nullptr;
776 case PPCISD::FSEL: return "PPCISD::FSEL";
777 case PPCISD::FCFID: return "PPCISD::FCFID";
778 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
779 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
780 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
781 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
782 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
783 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
784 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
785 case PPCISD::FRE: return "PPCISD::FRE";
786 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
787 case PPCISD::STFIWX: return "PPCISD::STFIWX";
788 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
789 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
790 case PPCISD::VPERM: return "PPCISD::VPERM";
791 case PPCISD::CMPB: return "PPCISD::CMPB";
792 case PPCISD::Hi: return "PPCISD::Hi";
793 case PPCISD::Lo: return "PPCISD::Lo";
794 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
795 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
796 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
797 case PPCISD::SRL: return "PPCISD::SRL";
798 case PPCISD::SRA: return "PPCISD::SRA";
799 case PPCISD::SHL: return "PPCISD::SHL";
800 case PPCISD::CALL: return "PPCISD::CALL";
801 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
802 case PPCISD::MTCTR: return "PPCISD::MTCTR";
803 case PPCISD::BCTRL: return "PPCISD::BCTRL";
804 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
805 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
806 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
807 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
808 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
809 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
810 case PPCISD::VCMP: return "PPCISD::VCMP";
811 case PPCISD::VCMPo: return "PPCISD::VCMPo";
812 case PPCISD::LBRX: return "PPCISD::LBRX";
813 case PPCISD::STBRX: return "PPCISD::STBRX";
814 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
815 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
816 case PPCISD::LARX: return "PPCISD::LARX";
817 case PPCISD::STCX: return "PPCISD::STCX";
818 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
819 case PPCISD::BDNZ: return "PPCISD::BDNZ";
820 case PPCISD::BDZ: return "PPCISD::BDZ";
821 case PPCISD::MFFS: return "PPCISD::MFFS";
822 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
823 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
824 case PPCISD::CR6SET: return "PPCISD::CR6SET";
825 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
826 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
827 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
828 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
829 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
830 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
831 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
832 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
833 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
834 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
835 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
836 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
837 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
838 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
839 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
840 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
841 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
842 case PPCISD::SC: return "PPCISD::SC";
846 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
848 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
849 return VT.changeVectorElementTypeToInteger();
852 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
853 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
857 //===----------------------------------------------------------------------===//
858 // Node matching predicates, for use by the tblgen matching code.
859 //===----------------------------------------------------------------------===//
861 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
862 static bool isFloatingPointZero(SDValue Op) {
863 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
864 return CFP->getValueAPF().isZero();
865 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
866 // Maybe this has already been legalized into the constant pool?
867 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
868 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
869 return CFP->getValueAPF().isZero();
874 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
875 /// true if Op is undef or if it matches the specified value.
876 static bool isConstantOrUndef(int Op, int Val) {
877 return Op < 0 || Op == Val;
880 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
881 /// VPKUHUM instruction.
882 /// The ShuffleKind distinguishes between big-endian operations with
883 /// two different inputs (0), either-endian operations with two identical
884 /// inputs (1), and little-endian operantion with two different inputs (2).
885 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
886 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
888 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
889 if (ShuffleKind == 0) {
892 for (unsigned i = 0; i != 16; ++i)
893 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
895 } else if (ShuffleKind == 2) {
898 for (unsigned i = 0; i != 16; ++i)
899 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
901 } else if (ShuffleKind == 1) {
902 unsigned j = IsLE ? 0 : 1;
903 for (unsigned i = 0; i != 8; ++i)
904 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
905 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
911 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
912 /// VPKUWUM instruction.
913 /// The ShuffleKind distinguishes between big-endian operations with
914 /// two different inputs (0), either-endian operations with two identical
915 /// inputs (1), and little-endian operantion with two different inputs (2).
916 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
917 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
919 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
920 if (ShuffleKind == 0) {
923 for (unsigned i = 0; i != 16; i += 2)
924 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
925 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
927 } else if (ShuffleKind == 2) {
930 for (unsigned i = 0; i != 16; i += 2)
931 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
932 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
934 } else if (ShuffleKind == 1) {
935 unsigned j = IsLE ? 0 : 2;
936 for (unsigned i = 0; i != 8; i += 2)
937 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
938 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
939 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
940 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
946 /// isVMerge - Common function, used to match vmrg* shuffles.
948 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
949 unsigned LHSStart, unsigned RHSStart) {
950 if (N->getValueType(0) != MVT::v16i8)
952 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
953 "Unsupported merge size!");
955 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
956 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
957 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
958 LHSStart+j+i*UnitSize) ||
959 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
960 RHSStart+j+i*UnitSize))
966 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
967 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
968 /// The ShuffleKind distinguishes between big-endian merges with two
969 /// different inputs (0), either-endian merges with two identical inputs (1),
970 /// and little-endian merges with two different inputs (2). For the latter,
971 /// the input operands are swapped (see PPCInstrAltivec.td).
972 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
973 unsigned ShuffleKind, SelectionDAG &DAG) {
974 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
975 if (ShuffleKind == 1) // unary
976 return isVMerge(N, UnitSize, 0, 0);
977 else if (ShuffleKind == 2) // swapped
978 return isVMerge(N, UnitSize, 0, 16);
982 if (ShuffleKind == 1) // unary
983 return isVMerge(N, UnitSize, 8, 8);
984 else if (ShuffleKind == 0) // normal
985 return isVMerge(N, UnitSize, 8, 24);
991 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
992 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
993 /// The ShuffleKind distinguishes between big-endian merges with two
994 /// different inputs (0), either-endian merges with two identical inputs (1),
995 /// and little-endian merges with two different inputs (2). For the latter,
996 /// the input operands are swapped (see PPCInstrAltivec.td).
997 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
998 unsigned ShuffleKind, SelectionDAG &DAG) {
999 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1000 if (ShuffleKind == 1) // unary
1001 return isVMerge(N, UnitSize, 8, 8);
1002 else if (ShuffleKind == 2) // swapped
1003 return isVMerge(N, UnitSize, 8, 24);
1007 if (ShuffleKind == 1) // unary
1008 return isVMerge(N, UnitSize, 0, 0);
1009 else if (ShuffleKind == 0) // normal
1010 return isVMerge(N, UnitSize, 0, 16);
1017 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1018 /// amount, otherwise return -1.
1019 /// The ShuffleKind distinguishes between big-endian operations with two
1020 /// different inputs (0), either-endian operations with two identical inputs
1021 /// (1), and little-endian operations with two different inputs (2). For the
1022 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1023 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1024 SelectionDAG &DAG) {
1025 if (N->getValueType(0) != MVT::v16i8)
1028 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1030 // Find the first non-undef value in the shuffle mask.
1032 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1035 if (i == 16) return -1; // all undef.
1037 // Otherwise, check to see if the rest of the elements are consecutively
1038 // numbered from this value.
1039 unsigned ShiftAmt = SVOp->getMaskElt(i);
1040 if (ShiftAmt < i) return -1;
1043 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1045 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1046 // Check the rest of the elements to see if they are consecutive.
1047 for (++i; i != 16; ++i)
1048 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1050 } else if (ShuffleKind == 1) {
1051 // Check the rest of the elements to see if they are consecutive.
1052 for (++i; i != 16; ++i)
1053 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1058 if (ShuffleKind == 2 && isLE)
1059 ShiftAmt = 16 - ShiftAmt;
1064 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1065 /// specifies a splat of a single element that is suitable for input to
1066 /// VSPLTB/VSPLTH/VSPLTW.
1067 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1068 assert(N->getValueType(0) == MVT::v16i8 &&
1069 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1071 // This is a splat operation if each element of the permute is the same, and
1072 // if the value doesn't reference the second vector.
1073 unsigned ElementBase = N->getMaskElt(0);
1075 // FIXME: Handle UNDEF elements too!
1076 if (ElementBase >= 16)
1079 // Check that the indices are consecutive, in the case of a multi-byte element
1080 // splatted with a v16i8 mask.
1081 for (unsigned i = 1; i != EltSize; ++i)
1082 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1085 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1086 if (N->getMaskElt(i) < 0) continue;
1087 for (unsigned j = 0; j != EltSize; ++j)
1088 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1094 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1096 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1097 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1099 APInt APVal, APUndef;
1103 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1104 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1105 return CFP->getValueAPF().isNegZero();
1110 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1111 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1112 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1113 SelectionDAG &DAG) {
1114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1115 assert(isSplatShuffleMask(SVOp, EltSize));
1116 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1117 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1119 return SVOp->getMaskElt(0) / EltSize;
1122 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1123 /// by using a vspltis[bhw] instruction of the specified element size, return
1124 /// the constant being splatted. The ByteSize field indicates the number of
1125 /// bytes of each element [124] -> [bhw].
1126 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1127 SDValue OpVal(nullptr, 0);
1129 // If ByteSize of the splat is bigger than the element size of the
1130 // build_vector, then we have a case where we are checking for a splat where
1131 // multiple elements of the buildvector are folded together into a single
1132 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1133 unsigned EltSize = 16/N->getNumOperands();
1134 if (EltSize < ByteSize) {
1135 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1136 SDValue UniquedVals[4];
1137 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1139 // See if all of the elements in the buildvector agree across.
1140 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1141 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1142 // If the element isn't a constant, bail fully out.
1143 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1146 if (!UniquedVals[i&(Multiple-1)].getNode())
1147 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1148 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1149 return SDValue(); // no match.
1152 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1153 // either constant or undef values that are identical for each chunk. See
1154 // if these chunks can form into a larger vspltis*.
1156 // Check to see if all of the leading entries are either 0 or -1. If
1157 // neither, then this won't fit into the immediate field.
1158 bool LeadingZero = true;
1159 bool LeadingOnes = true;
1160 for (unsigned i = 0; i != Multiple-1; ++i) {
1161 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1163 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1164 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1166 // Finally, check the least significant entry.
1168 if (!UniquedVals[Multiple-1].getNode())
1169 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1170 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1172 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1175 if (!UniquedVals[Multiple-1].getNode())
1176 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1177 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1178 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1179 return DAG.getTargetConstant(Val, MVT::i32);
1185 // Check to see if this buildvec has a single non-undef value in its elements.
1186 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1187 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1188 if (!OpVal.getNode())
1189 OpVal = N->getOperand(i);
1190 else if (OpVal != N->getOperand(i))
1194 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1196 unsigned ValSizeInBytes = EltSize;
1198 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1199 Value = CN->getZExtValue();
1200 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1201 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1202 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1205 // If the splat value is larger than the element value, then we can never do
1206 // this splat. The only case that we could fit the replicated bits into our
1207 // immediate field for would be zero, and we prefer to use vxor for it.
1208 if (ValSizeInBytes < ByteSize) return SDValue();
1210 // If the element value is larger than the splat value, cut it in half and
1211 // check to see if the two halves are equal. Continue doing this until we
1212 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1213 while (ValSizeInBytes > ByteSize) {
1214 ValSizeInBytes >>= 1;
1216 // If the top half equals the bottom half, we're still ok.
1217 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1218 (Value & ((1 << (8*ValSizeInBytes))-1)))
1222 // Properly sign extend the value.
1223 int MaskVal = SignExtend32(Value, ByteSize * 8);
1225 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1226 if (MaskVal == 0) return SDValue();
1228 // Finally, if this value fits in a 5 bit sext field, return it
1229 if (SignExtend32<5>(MaskVal) == MaskVal)
1230 return DAG.getTargetConstant(MaskVal, MVT::i32);
1234 //===----------------------------------------------------------------------===//
1235 // Addressing Mode Selection
1236 //===----------------------------------------------------------------------===//
1238 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1239 /// or 64-bit immediate, and if the value can be accurately represented as a
1240 /// sign extension from a 16-bit value. If so, this returns true and the
1242 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1243 if (!isa<ConstantSDNode>(N))
1246 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1247 if (N->getValueType(0) == MVT::i32)
1248 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1250 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1252 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1253 return isIntS16Immediate(Op.getNode(), Imm);
1257 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1258 /// can be represented as an indexed [r+r] operation. Returns false if it
1259 /// can be more efficiently represented with [r+imm].
1260 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1262 SelectionDAG &DAG) const {
1264 if (N.getOpcode() == ISD::ADD) {
1265 if (isIntS16Immediate(N.getOperand(1), imm))
1266 return false; // r+i
1267 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1268 return false; // r+i
1270 Base = N.getOperand(0);
1271 Index = N.getOperand(1);
1273 } else if (N.getOpcode() == ISD::OR) {
1274 if (isIntS16Immediate(N.getOperand(1), imm))
1275 return false; // r+i can fold it if we can.
1277 // If this is an or of disjoint bitfields, we can codegen this as an add
1278 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1280 APInt LHSKnownZero, LHSKnownOne;
1281 APInt RHSKnownZero, RHSKnownOne;
1282 DAG.computeKnownBits(N.getOperand(0),
1283 LHSKnownZero, LHSKnownOne);
1285 if (LHSKnownZero.getBoolValue()) {
1286 DAG.computeKnownBits(N.getOperand(1),
1287 RHSKnownZero, RHSKnownOne);
1288 // If all of the bits are known zero on the LHS or RHS, the add won't
1290 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1291 Base = N.getOperand(0);
1292 Index = N.getOperand(1);
1301 // If we happen to be doing an i64 load or store into a stack slot that has
1302 // less than a 4-byte alignment, then the frame-index elimination may need to
1303 // use an indexed load or store instruction (because the offset may not be a
1304 // multiple of 4). The extra register needed to hold the offset comes from the
1305 // register scavenger, and it is possible that the scavenger will need to use
1306 // an emergency spill slot. As a result, we need to make sure that a spill slot
1307 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1309 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1310 // FIXME: This does not handle the LWA case.
1314 // NOTE: We'll exclude negative FIs here, which come from argument
1315 // lowering, because there are no known test cases triggering this problem
1316 // using packed structures (or similar). We can remove this exclusion if
1317 // we find such a test case. The reason why this is so test-case driven is
1318 // because this entire 'fixup' is only to prevent crashes (from the
1319 // register scavenger) on not-really-valid inputs. For example, if we have:
1321 // %b = bitcast i1* %a to i64*
1322 // store i64* a, i64 b
1323 // then the store should really be marked as 'align 1', but is not. If it
1324 // were marked as 'align 1' then the indexed form would have been
1325 // instruction-selected initially, and the problem this 'fixup' is preventing
1326 // won't happen regardless.
1330 MachineFunction &MF = DAG.getMachineFunction();
1331 MachineFrameInfo *MFI = MF.getFrameInfo();
1333 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1337 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1338 FuncInfo->setHasNonRISpills();
1341 /// Returns true if the address N can be represented by a base register plus
1342 /// a signed 16-bit displacement [r+imm], and if it is not better
1343 /// represented as reg+reg. If Aligned is true, only accept displacements
1344 /// suitable for STD and friends, i.e. multiples of 4.
1345 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1348 bool Aligned) const {
1349 // FIXME dl should come from parent load or store, not from address
1351 // If this can be more profitably realized as r+r, fail.
1352 if (SelectAddressRegReg(N, Disp, Base, DAG))
1355 if (N.getOpcode() == ISD::ADD) {
1357 if (isIntS16Immediate(N.getOperand(1), imm) &&
1358 (!Aligned || (imm & 3) == 0)) {
1359 Disp = DAG.getTargetConstant(imm, N.getValueType());
1360 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1361 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1362 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1364 Base = N.getOperand(0);
1366 return true; // [r+i]
1367 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1368 // Match LOAD (ADD (X, Lo(G))).
1369 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1370 && "Cannot handle constant offsets yet!");
1371 Disp = N.getOperand(1).getOperand(0); // The global address.
1372 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1373 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1374 Disp.getOpcode() == ISD::TargetConstantPool ||
1375 Disp.getOpcode() == ISD::TargetJumpTable);
1376 Base = N.getOperand(0);
1377 return true; // [&g+r]
1379 } else if (N.getOpcode() == ISD::OR) {
1381 if (isIntS16Immediate(N.getOperand(1), imm) &&
1382 (!Aligned || (imm & 3) == 0)) {
1383 // If this is an or of disjoint bitfields, we can codegen this as an add
1384 // (for better address arithmetic) if the LHS and RHS of the OR are
1385 // provably disjoint.
1386 APInt LHSKnownZero, LHSKnownOne;
1387 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1389 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1390 // If all of the bits are known zero on the LHS or RHS, the add won't
1392 if (FrameIndexSDNode *FI =
1393 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1394 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1395 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1397 Base = N.getOperand(0);
1399 Disp = DAG.getTargetConstant(imm, N.getValueType());
1403 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1404 // Loading from a constant address.
1406 // If this address fits entirely in a 16-bit sext immediate field, codegen
1409 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1410 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1411 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1412 CN->getValueType(0));
1416 // Handle 32-bit sext immediates with LIS + addr mode.
1417 if ((CN->getValueType(0) == MVT::i32 ||
1418 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1419 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1420 int Addr = (int)CN->getZExtValue();
1422 // Otherwise, break this down into an LIS + disp.
1423 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1425 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1426 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1427 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1432 Disp = DAG.getTargetConstant(0, getPointerTy());
1433 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1434 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1435 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1438 return true; // [r+0]
1441 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1442 /// represented as an indexed [r+r] operation.
1443 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1445 SelectionDAG &DAG) const {
1446 // Check to see if we can easily represent this as an [r+r] address. This
1447 // will fail if it thinks that the address is more profitably represented as
1448 // reg+imm, e.g. where imm = 0.
1449 if (SelectAddressRegReg(N, Base, Index, DAG))
1452 // If the operand is an addition, always emit this as [r+r], since this is
1453 // better (for code size, and execution, as the memop does the add for free)
1454 // than emitting an explicit add.
1455 if (N.getOpcode() == ISD::ADD) {
1456 Base = N.getOperand(0);
1457 Index = N.getOperand(1);
1461 // Otherwise, do it the hard way, using R0 as the base register.
1462 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1468 /// getPreIndexedAddressParts - returns true by value, base pointer and
1469 /// offset pointer and addressing mode by reference if the node's address
1470 /// can be legally represented as pre-indexed load / store address.
1471 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1473 ISD::MemIndexedMode &AM,
1474 SelectionDAG &DAG) const {
1475 if (DisablePPCPreinc) return false;
1481 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1482 Ptr = LD->getBasePtr();
1483 VT = LD->getMemoryVT();
1484 Alignment = LD->getAlignment();
1485 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1486 Ptr = ST->getBasePtr();
1487 VT = ST->getMemoryVT();
1488 Alignment = ST->getAlignment();
1493 // PowerPC doesn't have preinc load/store instructions for vectors.
1497 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1499 // Common code will reject creating a pre-inc form if the base pointer
1500 // is a frame index, or if N is a store and the base pointer is either
1501 // the same as or a predecessor of the value being stored. Check for
1502 // those situations here, and try with swapped Base/Offset instead.
1505 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1508 SDValue Val = cast<StoreSDNode>(N)->getValue();
1509 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1514 std::swap(Base, Offset);
1520 // LDU/STU can only handle immediates that are a multiple of 4.
1521 if (VT != MVT::i64) {
1522 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1525 // LDU/STU need an address with at least 4-byte alignment.
1529 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1533 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1534 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1535 // sext i32 to i64 when addr mode is r+i.
1536 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1537 LD->getExtensionType() == ISD::SEXTLOAD &&
1538 isa<ConstantSDNode>(Offset))
1546 //===----------------------------------------------------------------------===//
1547 // LowerOperation implementation
1548 //===----------------------------------------------------------------------===//
1550 /// GetLabelAccessInfo - Return true if we should reference labels using a
1551 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1552 static bool GetLabelAccessInfo(const TargetMachine &TM,
1553 const PPCSubtarget &Subtarget,
1554 unsigned &HiOpFlags, unsigned &LoOpFlags,
1555 const GlobalValue *GV = nullptr) {
1556 HiOpFlags = PPCII::MO_HA;
1557 LoOpFlags = PPCII::MO_LO;
1559 // Don't use the pic base if not in PIC relocation model.
1560 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1563 HiOpFlags |= PPCII::MO_PIC_FLAG;
1564 LoOpFlags |= PPCII::MO_PIC_FLAG;
1567 // If this is a reference to a global value that requires a non-lazy-ptr, make
1568 // sure that instruction lowering adds it.
1569 if (GV && Subtarget.hasLazyResolverStub(GV, TM)) {
1570 HiOpFlags |= PPCII::MO_NLP_FLAG;
1571 LoOpFlags |= PPCII::MO_NLP_FLAG;
1573 if (GV->hasHiddenVisibility()) {
1574 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1575 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1582 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1583 SelectionDAG &DAG) {
1584 EVT PtrVT = HiPart.getValueType();
1585 SDValue Zero = DAG.getConstant(0, PtrVT);
1588 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1589 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1591 // With PIC, the first instruction is actually "GR+hi(&G)".
1593 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1594 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1596 // Generate non-pic code that has direct accesses to the constant pool.
1597 // The address of the global is just (hi(&g)+lo(&g)).
1598 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1601 static void setUsesTOCBasePtr(MachineFunction &MF) {
1602 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1603 FuncInfo->setUsesTOCBasePtr();
1606 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1607 setUsesTOCBasePtr(DAG.getMachineFunction());
1610 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1611 SelectionDAG &DAG) const {
1612 EVT PtrVT = Op.getValueType();
1613 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1614 const Constant *C = CP->getConstVal();
1616 // 64-bit SVR4 ABI code is always position-independent.
1617 // The actual address of the GlobalValue is stored in the TOC.
1618 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1619 setUsesTOCBasePtr(DAG);
1620 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1621 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1622 DAG.getRegister(PPC::X2, MVT::i64));
1625 unsigned MOHiFlag, MOLoFlag;
1627 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1629 if (isPIC && Subtarget.isSVR4ABI()) {
1630 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1631 PPCII::MO_PIC_FLAG);
1633 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1634 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1638 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1640 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1641 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1644 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1645 EVT PtrVT = Op.getValueType();
1646 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1648 // 64-bit SVR4 ABI code is always position-independent.
1649 // The actual address of the GlobalValue is stored in the TOC.
1650 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1651 setUsesTOCBasePtr(DAG);
1652 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1653 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1654 DAG.getRegister(PPC::X2, MVT::i64));
1657 unsigned MOHiFlag, MOLoFlag;
1659 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1661 if (isPIC && Subtarget.isSVR4ABI()) {
1662 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1663 PPCII::MO_PIC_FLAG);
1665 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1666 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1669 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1670 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1671 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1674 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1675 SelectionDAG &DAG) const {
1676 EVT PtrVT = Op.getValueType();
1677 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1678 const BlockAddress *BA = BASDN->getBlockAddress();
1680 // 64-bit SVR4 ABI code is always position-independent.
1681 // The actual BlockAddress is stored in the TOC.
1682 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1683 setUsesTOCBasePtr(DAG);
1684 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1685 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1686 DAG.getRegister(PPC::X2, MVT::i64));
1689 unsigned MOHiFlag, MOLoFlag;
1691 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1692 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1693 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1694 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1697 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1698 SelectionDAG &DAG) const {
1700 // FIXME: TLS addresses currently use medium model code sequences,
1701 // which is the most useful form. Eventually support for small and
1702 // large models could be added if users need it, at the cost of
1703 // additional complexity.
1704 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1706 const GlobalValue *GV = GA->getGlobal();
1707 EVT PtrVT = getPointerTy();
1708 bool is64bit = Subtarget.isPPC64();
1709 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1710 PICLevel::Level picLevel = M->getPICLevel();
1712 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1714 if (Model == TLSModel::LocalExec) {
1715 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1716 PPCII::MO_TPREL_HA);
1717 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1718 PPCII::MO_TPREL_LO);
1719 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1720 is64bit ? MVT::i64 : MVT::i32);
1721 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1722 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1725 if (Model == TLSModel::InitialExec) {
1726 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1727 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1731 setUsesTOCBasePtr(DAG);
1732 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1733 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1734 PtrVT, GOTReg, TGA);
1736 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1737 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1738 PtrVT, TGA, GOTPtr);
1739 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1742 if (Model == TLSModel::GeneralDynamic) {
1743 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1746 setUsesTOCBasePtr(DAG);
1747 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1748 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1751 if (picLevel == PICLevel::Small)
1752 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1754 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1756 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl,
1757 PtrVT, GOTPtr, TGA);
1758 return DAG.getNode(PPCISD::GET_TLS_ADDR, dl, PtrVT, GOTEntry, TGA);
1761 if (Model == TLSModel::LocalDynamic) {
1762 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1765 setUsesTOCBasePtr(DAG);
1766 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1767 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1770 if (picLevel == PICLevel::Small)
1771 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1773 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1775 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1777 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1778 PtrVT, GOTEntry, TGA);
1779 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
1780 PtrVT, TLSAddr, TGA);
1781 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1784 llvm_unreachable("Unknown TLS model!");
1787 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1788 SelectionDAG &DAG) const {
1789 EVT PtrVT = Op.getValueType();
1790 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1792 const GlobalValue *GV = GSDN->getGlobal();
1794 // 64-bit SVR4 ABI code is always position-independent.
1795 // The actual address of the GlobalValue is stored in the TOC.
1796 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1797 setUsesTOCBasePtr(DAG);
1798 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1799 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1800 DAG.getRegister(PPC::X2, MVT::i64));
1803 unsigned MOHiFlag, MOLoFlag;
1805 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
1807 if (isPIC && Subtarget.isSVR4ABI()) {
1808 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1810 PPCII::MO_PIC_FLAG);
1811 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1812 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1816 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1818 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1820 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1822 // If the global reference is actually to a non-lazy-pointer, we have to do an
1823 // extra load to get the address of the global.
1824 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1825 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1826 false, false, false, 0);
1830 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1831 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1834 if (Op.getValueType() == MVT::v2i64) {
1835 // When the operands themselves are v2i64 values, we need to do something
1836 // special because VSX has no underlying comparison operations for these.
1837 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1838 // Equality can be handled by casting to the legal type for Altivec
1839 // comparisons, everything else needs to be expanded.
1840 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1841 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1842 DAG.getSetCC(dl, MVT::v4i32,
1843 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1844 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1851 // We handle most of these in the usual way.
1855 // If we're comparing for equality to zero, expose the fact that this is
1856 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1857 // fold the new nodes.
1858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1859 if (C->isNullValue() && CC == ISD::SETEQ) {
1860 EVT VT = Op.getOperand(0).getValueType();
1861 SDValue Zext = Op.getOperand(0);
1862 if (VT.bitsLT(MVT::i32)) {
1864 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1866 unsigned Log2b = Log2_32(VT.getSizeInBits());
1867 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1868 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1869 DAG.getConstant(Log2b, MVT::i32));
1870 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1872 // Leave comparisons against 0 and -1 alone for now, since they're usually
1873 // optimized. FIXME: revisit this when we can custom lower all setcc
1875 if (C->isAllOnesValue() || C->isNullValue())
1879 // If we have an integer seteq/setne, turn it into a compare against zero
1880 // by xor'ing the rhs with the lhs, which is faster than setting a
1881 // condition register, reading it back out, and masking the correct bit. The
1882 // normal approach here uses sub to do this instead of xor. Using xor exposes
1883 // the result to other bit-twiddling opportunities.
1884 EVT LHSVT = Op.getOperand(0).getValueType();
1885 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1886 EVT VT = Op.getValueType();
1887 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1889 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1894 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1895 const PPCSubtarget &Subtarget) const {
1896 SDNode *Node = Op.getNode();
1897 EVT VT = Node->getValueType(0);
1898 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1899 SDValue InChain = Node->getOperand(0);
1900 SDValue VAListPtr = Node->getOperand(1);
1901 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1904 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1907 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1908 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1909 false, false, false, 0);
1910 InChain = GprIndex.getValue(1);
1912 if (VT == MVT::i64) {
1913 // Check if GprIndex is even
1914 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1915 DAG.getConstant(1, MVT::i32));
1916 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1917 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1918 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1919 DAG.getConstant(1, MVT::i32));
1920 // Align GprIndex to be even if it isn't
1921 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1925 // fpr index is 1 byte after gpr
1926 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1927 DAG.getConstant(1, MVT::i32));
1930 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1931 FprPtr, MachinePointerInfo(SV), MVT::i8,
1932 false, false, false, 0);
1933 InChain = FprIndex.getValue(1);
1935 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1936 DAG.getConstant(8, MVT::i32));
1938 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1939 DAG.getConstant(4, MVT::i32));
1942 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1943 MachinePointerInfo(), false, false,
1945 InChain = OverflowArea.getValue(1);
1947 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1948 MachinePointerInfo(), false, false,
1950 InChain = RegSaveArea.getValue(1);
1952 // select overflow_area if index > 8
1953 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1954 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1956 // adjustment constant gpr_index * 4/8
1957 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1958 VT.isInteger() ? GprIndex : FprIndex,
1959 DAG.getConstant(VT.isInteger() ? 4 : 8,
1962 // OurReg = RegSaveArea + RegConstant
1963 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1966 // Floating types are 32 bytes into RegSaveArea
1967 if (VT.isFloatingPoint())
1968 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1969 DAG.getConstant(32, MVT::i32));
1971 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1972 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1973 VT.isInteger() ? GprIndex : FprIndex,
1974 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1977 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1978 VT.isInteger() ? VAListPtr : FprPtr,
1979 MachinePointerInfo(SV),
1980 MVT::i8, false, false, 0);
1982 // determine if we should load from reg_save_area or overflow_area
1983 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1985 // increase overflow_area by 4/8 if gpr/fpr > 8
1986 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1987 DAG.getConstant(VT.isInteger() ? 4 : 8,
1990 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1993 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1995 MachinePointerInfo(),
1996 MVT::i32, false, false, 0);
1998 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1999 false, false, false, 0);
2002 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2003 const PPCSubtarget &Subtarget) const {
2004 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2006 // We have to copy the entire va_list struct:
2007 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2008 return DAG.getMemcpy(Op.getOperand(0), Op,
2009 Op.getOperand(1), Op.getOperand(2),
2010 DAG.getConstant(12, MVT::i32), 8, false, true,
2011 MachinePointerInfo(), MachinePointerInfo());
2014 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2015 SelectionDAG &DAG) const {
2016 return Op.getOperand(0);
2019 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2020 SelectionDAG &DAG) const {
2021 SDValue Chain = Op.getOperand(0);
2022 SDValue Trmp = Op.getOperand(1); // trampoline
2023 SDValue FPtr = Op.getOperand(2); // nested function
2024 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2027 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2028 bool isPPC64 = (PtrVT == MVT::i64);
2030 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2033 TargetLowering::ArgListTy Args;
2034 TargetLowering::ArgListEntry Entry;
2036 Entry.Ty = IntPtrTy;
2037 Entry.Node = Trmp; Args.push_back(Entry);
2039 // TrampSize == (isPPC64 ? 48 : 40);
2040 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2041 isPPC64 ? MVT::i64 : MVT::i32);
2042 Args.push_back(Entry);
2044 Entry.Node = FPtr; Args.push_back(Entry);
2045 Entry.Node = Nest; Args.push_back(Entry);
2047 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2048 TargetLowering::CallLoweringInfo CLI(DAG);
2049 CLI.setDebugLoc(dl).setChain(Chain)
2050 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2051 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2052 std::move(Args), 0);
2054 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2055 return CallResult.second;
2058 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2059 const PPCSubtarget &Subtarget) const {
2060 MachineFunction &MF = DAG.getMachineFunction();
2061 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2065 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2066 // vastart just stores the address of the VarArgsFrameIndex slot into the
2067 // memory location argument.
2068 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2069 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2070 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2071 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2072 MachinePointerInfo(SV),
2076 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2077 // We suppose the given va_list is already allocated.
2080 // char gpr; /* index into the array of 8 GPRs
2081 // * stored in the register save area
2082 // * gpr=0 corresponds to r3,
2083 // * gpr=1 to r4, etc.
2085 // char fpr; /* index into the array of 8 FPRs
2086 // * stored in the register save area
2087 // * fpr=0 corresponds to f1,
2088 // * fpr=1 to f2, etc.
2090 // char *overflow_arg_area;
2091 // /* location on stack that holds
2092 // * the next overflow argument
2094 // char *reg_save_area;
2095 // /* where r3:r10 and f1:f8 (if saved)
2101 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2102 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2105 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2107 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2109 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2112 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2113 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2115 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2116 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2118 uint64_t FPROffset = 1;
2119 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2121 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2123 // Store first byte : number of int regs
2124 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2126 MachinePointerInfo(SV),
2127 MVT::i8, false, false, 0);
2128 uint64_t nextOffset = FPROffset;
2129 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2132 // Store second byte : number of float regs
2133 SDValue secondStore =
2134 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2135 MachinePointerInfo(SV, nextOffset), MVT::i8,
2137 nextOffset += StackOffset;
2138 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2140 // Store second word : arguments given on stack
2141 SDValue thirdStore =
2142 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2143 MachinePointerInfo(SV, nextOffset),
2145 nextOffset += FrameOffset;
2146 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2148 // Store third word : arguments given in registers
2149 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2150 MachinePointerInfo(SV, nextOffset),
2155 #include "PPCGenCallingConv.inc"
2157 // Function whose sole purpose is to kill compiler warnings
2158 // stemming from unused functions included from PPCGenCallingConv.inc.
2159 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2160 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2163 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2164 CCValAssign::LocInfo &LocInfo,
2165 ISD::ArgFlagsTy &ArgFlags,
2170 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2172 CCValAssign::LocInfo &LocInfo,
2173 ISD::ArgFlagsTy &ArgFlags,
2175 static const MCPhysReg ArgRegs[] = {
2176 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2177 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2179 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2181 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2183 // Skip one register if the first unallocated register has an even register
2184 // number and there are still argument registers available which have not been
2185 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2186 // need to skip a register if RegNum is odd.
2187 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2188 State.AllocateReg(ArgRegs[RegNum]);
2191 // Always return false here, as this function only makes sure that the first
2192 // unallocated register has an odd register number and does not actually
2193 // allocate a register for the current argument.
2197 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2199 CCValAssign::LocInfo &LocInfo,
2200 ISD::ArgFlagsTy &ArgFlags,
2202 static const MCPhysReg ArgRegs[] = {
2203 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2207 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2209 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2211 // If there is only one Floating-point register left we need to put both f64
2212 // values of a split ppc_fp128 value on the stack.
2213 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2214 State.AllocateReg(ArgRegs[RegNum]);
2217 // Always return false here, as this function only makes sure that the two f64
2218 // values a ppc_fp128 value is split into are both passed in registers or both
2219 // passed on the stack and does not actually allocate a register for the
2220 // current argument.
2224 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2226 static const MCPhysReg *GetFPR() {
2227 static const MCPhysReg FPR[] = {
2228 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2229 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2235 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2237 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2238 unsigned PtrByteSize) {
2239 unsigned ArgSize = ArgVT.getStoreSize();
2240 if (Flags.isByVal())
2241 ArgSize = Flags.getByValSize();
2243 // Round up to multiples of the pointer size, except for array members,
2244 // which are always packed.
2245 if (!Flags.isInConsecutiveRegs())
2246 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2251 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2253 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2254 ISD::ArgFlagsTy Flags,
2255 unsigned PtrByteSize) {
2256 unsigned Align = PtrByteSize;
2258 // Altivec parameters are padded to a 16 byte boundary.
2259 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2260 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2261 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2264 // ByVal parameters are aligned as requested.
2265 if (Flags.isByVal()) {
2266 unsigned BVAlign = Flags.getByValAlign();
2267 if (BVAlign > PtrByteSize) {
2268 if (BVAlign % PtrByteSize != 0)
2270 "ByVal alignment is not a multiple of the pointer size");
2276 // Array members are always packed to their original alignment.
2277 if (Flags.isInConsecutiveRegs()) {
2278 // If the array member was split into multiple registers, the first
2279 // needs to be aligned to the size of the full type. (Except for
2280 // ppcf128, which is only aligned as its f64 components.)
2281 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2282 Align = OrigVT.getStoreSize();
2284 Align = ArgVT.getStoreSize();
2290 /// CalculateStackSlotUsed - Return whether this argument will use its
2291 /// stack slot (instead of being passed in registers). ArgOffset,
2292 /// AvailableFPRs, and AvailableVRs must hold the current argument
2293 /// position, and will be updated to account for this argument.
2294 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2295 ISD::ArgFlagsTy Flags,
2296 unsigned PtrByteSize,
2297 unsigned LinkageSize,
2298 unsigned ParamAreaSize,
2299 unsigned &ArgOffset,
2300 unsigned &AvailableFPRs,
2301 unsigned &AvailableVRs) {
2302 bool UseMemory = false;
2304 // Respect alignment of argument on the stack.
2306 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2307 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2308 // If there's no space left in the argument save area, we must
2309 // use memory (this check also catches zero-sized arguments).
2310 if (ArgOffset >= LinkageSize + ParamAreaSize)
2313 // Allocate argument on the stack.
2314 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2315 if (Flags.isInConsecutiveRegsLast())
2316 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2317 // If we overran the argument save area, we must use memory
2318 // (this check catches arguments passed partially in memory)
2319 if (ArgOffset > LinkageSize + ParamAreaSize)
2322 // However, if the argument is actually passed in an FPR or a VR,
2323 // we don't use memory after all.
2324 if (!Flags.isByVal()) {
2325 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2326 if (AvailableFPRs > 0) {
2330 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2331 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2332 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2333 if (AvailableVRs > 0) {
2342 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2343 /// ensure minimum alignment required for target.
2344 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2345 unsigned NumBytes) {
2346 unsigned TargetAlign = Lowering->getStackAlignment();
2347 unsigned AlignMask = TargetAlign - 1;
2348 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2353 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2354 CallingConv::ID CallConv, bool isVarArg,
2355 const SmallVectorImpl<ISD::InputArg>
2357 SDLoc dl, SelectionDAG &DAG,
2358 SmallVectorImpl<SDValue> &InVals)
2360 if (Subtarget.isSVR4ABI()) {
2361 if (Subtarget.isPPC64())
2362 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2365 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2368 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2374 PPCTargetLowering::LowerFormalArguments_32SVR4(
2376 CallingConv::ID CallConv, bool isVarArg,
2377 const SmallVectorImpl<ISD::InputArg>
2379 SDLoc dl, SelectionDAG &DAG,
2380 SmallVectorImpl<SDValue> &InVals) const {
2382 // 32-bit SVR4 ABI Stack Frame Layout:
2383 // +-----------------------------------+
2384 // +--> | Back chain |
2385 // | +-----------------------------------+
2386 // | | Floating-point register save area |
2387 // | +-----------------------------------+
2388 // | | General register save area |
2389 // | +-----------------------------------+
2390 // | | CR save word |
2391 // | +-----------------------------------+
2392 // | | VRSAVE save word |
2393 // | +-----------------------------------+
2394 // | | Alignment padding |
2395 // | +-----------------------------------+
2396 // | | Vector register save area |
2397 // | +-----------------------------------+
2398 // | | Local variable space |
2399 // | +-----------------------------------+
2400 // | | Parameter list area |
2401 // | +-----------------------------------+
2402 // | | LR save word |
2403 // | +-----------------------------------+
2404 // SP--> +--- | Back chain |
2405 // +-----------------------------------+
2408 // System V Application Binary Interface PowerPC Processor Supplement
2409 // AltiVec Technology Programming Interface Manual
2411 MachineFunction &MF = DAG.getMachineFunction();
2412 MachineFrameInfo *MFI = MF.getFrameInfo();
2413 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2415 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2416 // Potential tail calls could cause overwriting of argument stack slots.
2417 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2418 (CallConv == CallingConv::Fast));
2419 unsigned PtrByteSize = 4;
2421 // Assign locations to all of the incoming arguments.
2422 SmallVector<CCValAssign, 16> ArgLocs;
2423 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2426 // Reserve space for the linkage area on the stack.
2427 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2428 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2430 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2432 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2433 CCValAssign &VA = ArgLocs[i];
2435 // Arguments stored in registers.
2436 if (VA.isRegLoc()) {
2437 const TargetRegisterClass *RC;
2438 EVT ValVT = VA.getValVT();
2440 switch (ValVT.getSimpleVT().SimpleTy) {
2442 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2445 RC = &PPC::GPRCRegClass;
2448 RC = &PPC::F4RCRegClass;
2451 if (Subtarget.hasVSX())
2452 RC = &PPC::VSFRCRegClass;
2454 RC = &PPC::F8RCRegClass;
2460 RC = &PPC::VRRCRegClass;
2464 RC = &PPC::VSHRCRegClass;
2468 // Transform the arguments stored in physical registers into virtual ones.
2469 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2470 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2471 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2473 if (ValVT == MVT::i1)
2474 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2476 InVals.push_back(ArgValue);
2478 // Argument stored in memory.
2479 assert(VA.isMemLoc());
2481 unsigned ArgSize = VA.getLocVT().getStoreSize();
2482 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2485 // Create load nodes to retrieve arguments from the stack.
2486 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2487 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2488 MachinePointerInfo(),
2489 false, false, false, 0));
2493 // Assign locations to all of the incoming aggregate by value arguments.
2494 // Aggregates passed by value are stored in the local variable space of the
2495 // caller's stack frame, right above the parameter list area.
2496 SmallVector<CCValAssign, 16> ByValArgLocs;
2497 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2498 ByValArgLocs, *DAG.getContext());
2500 // Reserve stack space for the allocations in CCInfo.
2501 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2503 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2505 // Area that is at least reserved in the caller of this function.
2506 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2507 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2509 // Set the size that is at least reserved in caller of this function. Tail
2510 // call optimized function's reserved stack space needs to be aligned so that
2511 // taking the difference between two stack areas will result in an aligned
2514 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2515 FuncInfo->setMinReservedArea(MinReservedArea);
2517 SmallVector<SDValue, 8> MemOps;
2519 // If the function takes variable number of arguments, make a frame index for
2520 // the start of the first vararg value... for expansion of llvm.va_start.
2522 static const MCPhysReg GPArgRegs[] = {
2523 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2524 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2526 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2528 static const MCPhysReg FPArgRegs[] = {
2529 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2532 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2533 if (DisablePPCFloatInVariadic)
2536 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2538 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2541 // Make room for NumGPArgRegs and NumFPArgRegs.
2542 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2543 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2545 FuncInfo->setVarArgsStackOffset(
2546 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2547 CCInfo.getNextStackOffset(), true));
2549 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2550 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2552 // The fixed integer arguments of a variadic function are stored to the
2553 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2554 // the result of va_next.
2555 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2556 // Get an existing live-in vreg, or add a new one.
2557 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2559 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2561 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2562 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2563 MachinePointerInfo(), false, false, 0);
2564 MemOps.push_back(Store);
2565 // Increment the address by four for the next argument to store
2566 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2567 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2570 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2572 // The double arguments are stored to the VarArgsFrameIndex
2574 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2575 // Get an existing live-in vreg, or add a new one.
2576 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2578 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2580 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2581 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2582 MachinePointerInfo(), false, false, 0);
2583 MemOps.push_back(Store);
2584 // Increment the address by eight for the next argument to store
2585 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2587 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2591 if (!MemOps.empty())
2592 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2597 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2598 // value to MVT::i64 and then truncate to the correct register size.
2600 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2601 SelectionDAG &DAG, SDValue ArgVal,
2604 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2605 DAG.getValueType(ObjectVT));
2606 else if (Flags.isZExt())
2607 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2608 DAG.getValueType(ObjectVT));
2610 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2614 PPCTargetLowering::LowerFormalArguments_64SVR4(
2616 CallingConv::ID CallConv, bool isVarArg,
2617 const SmallVectorImpl<ISD::InputArg>
2619 SDLoc dl, SelectionDAG &DAG,
2620 SmallVectorImpl<SDValue> &InVals) const {
2621 // TODO: add description of PPC stack frame format, or at least some docs.
2623 bool isELFv2ABI = Subtarget.isELFv2ABI();
2624 bool isLittleEndian = Subtarget.isLittleEndian();
2625 MachineFunction &MF = DAG.getMachineFunction();
2626 MachineFrameInfo *MFI = MF.getFrameInfo();
2627 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2629 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2630 "fastcc not supported on varargs functions");
2632 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2633 // Potential tail calls could cause overwriting of argument stack slots.
2634 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2635 (CallConv == CallingConv::Fast));
2636 unsigned PtrByteSize = 8;
2638 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2641 static const MCPhysReg GPR[] = {
2642 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2643 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2646 static const MCPhysReg *FPR = GetFPR();
2648 static const MCPhysReg VR[] = {
2649 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2650 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2652 static const MCPhysReg VSRH[] = {
2653 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2654 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2657 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2658 const unsigned Num_FPR_Regs = 13;
2659 const unsigned Num_VR_Regs = array_lengthof(VR);
2661 // Do a first pass over the arguments to determine whether the ABI
2662 // guarantees that our caller has allocated the parameter save area
2663 // on its stack frame. In the ELFv1 ABI, this is always the case;
2664 // in the ELFv2 ABI, it is true if this is a vararg function or if
2665 // any parameter is located in a stack slot.
2667 bool HasParameterArea = !isELFv2ABI || isVarArg;
2668 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2669 unsigned NumBytes = LinkageSize;
2670 unsigned AvailableFPRs = Num_FPR_Regs;
2671 unsigned AvailableVRs = Num_VR_Regs;
2672 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2673 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2674 PtrByteSize, LinkageSize, ParamAreaSize,
2675 NumBytes, AvailableFPRs, AvailableVRs))
2676 HasParameterArea = true;
2678 // Add DAG nodes to load the arguments or copy them out of registers. On
2679 // entry to a function on PPC, the arguments start after the linkage area,
2680 // although the first ones are often in registers.
2682 unsigned ArgOffset = LinkageSize;
2683 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2684 SmallVector<SDValue, 8> MemOps;
2685 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2686 unsigned CurArgIdx = 0;
2687 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2689 bool needsLoad = false;
2690 EVT ObjectVT = Ins[ArgNo].VT;
2691 EVT OrigVT = Ins[ArgNo].ArgVT;
2692 unsigned ObjSize = ObjectVT.getStoreSize();
2693 unsigned ArgSize = ObjSize;
2694 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2695 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2696 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2698 // We re-align the argument offset for each argument, except when using the
2699 // fast calling convention, when we need to make sure we do that only when
2700 // we'll actually use a stack slot.
2701 unsigned CurArgOffset, Align;
2702 auto ComputeArgOffset = [&]() {
2703 /* Respect alignment of argument on the stack. */
2704 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2705 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2706 CurArgOffset = ArgOffset;
2709 if (CallConv != CallingConv::Fast) {
2712 /* Compute GPR index associated with argument offset. */
2713 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2714 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2717 // FIXME the codegen can be much improved in some cases.
2718 // We do not have to keep everything in memory.
2719 if (Flags.isByVal()) {
2720 if (CallConv == CallingConv::Fast)
2723 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2724 ObjSize = Flags.getByValSize();
2725 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2726 // Empty aggregate parameters do not take up registers. Examples:
2730 // etc. However, we have to provide a place-holder in InVals, so
2731 // pretend we have an 8-byte item at the current address for that
2734 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2735 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2736 InVals.push_back(FIN);
2740 // Create a stack object covering all stack doublewords occupied
2741 // by the argument. If the argument is (fully or partially) on
2742 // the stack, or if the argument is fully in registers but the
2743 // caller has allocated the parameter save anyway, we can refer
2744 // directly to the caller's stack frame. Otherwise, create a
2745 // local copy in our own frame.
2747 if (HasParameterArea ||
2748 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2749 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2751 FI = MFI->CreateStackObject(ArgSize, Align, false);
2752 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2754 // Handle aggregates smaller than 8 bytes.
2755 if (ObjSize < PtrByteSize) {
2756 // The value of the object is its address, which differs from the
2757 // address of the enclosing doubleword on big-endian systems.
2759 if (!isLittleEndian) {
2760 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2761 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2763 InVals.push_back(Arg);
2765 if (GPR_idx != Num_GPR_Regs) {
2766 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2767 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2770 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2771 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2772 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2773 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2774 MachinePointerInfo(FuncArg),
2775 ObjType, false, false, 0);
2777 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2778 // store the whole register as-is to the parameter save area
2780 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2781 MachinePointerInfo(FuncArg),
2785 MemOps.push_back(Store);
2787 // Whether we copied from a register or not, advance the offset
2788 // into the parameter save area by a full doubleword.
2789 ArgOffset += PtrByteSize;
2793 // The value of the object is its address, which is the address of
2794 // its first stack doubleword.
2795 InVals.push_back(FIN);
2797 // Store whatever pieces of the object are in registers to memory.
2798 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2799 if (GPR_idx == Num_GPR_Regs)
2802 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2803 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2806 SDValue Off = DAG.getConstant(j, PtrVT);
2807 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2809 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2810 MachinePointerInfo(FuncArg, j),
2812 MemOps.push_back(Store);
2815 ArgOffset += ArgSize;
2819 switch (ObjectVT.getSimpleVT().SimpleTy) {
2820 default: llvm_unreachable("Unhandled argument type!");
2824 // These can be scalar arguments or elements of an integer array type
2825 // passed directly. Clang may use those instead of "byval" aggregate
2826 // types to avoid forcing arguments to memory unnecessarily.
2827 if (GPR_idx != Num_GPR_Regs) {
2828 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2829 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2831 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2832 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2833 // value to MVT::i64 and then truncate to the correct register size.
2834 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2836 if (CallConv == CallingConv::Fast)
2840 ArgSize = PtrByteSize;
2842 if (CallConv != CallingConv::Fast || needsLoad)
2848 // These can be scalar arguments or elements of a float array type
2849 // passed directly. The latter are used to implement ELFv2 homogenous
2850 // float aggregates.
2851 if (FPR_idx != Num_FPR_Regs) {
2854 if (ObjectVT == MVT::f32)
2855 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2857 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
2858 ? &PPC::VSFRCRegClass
2859 : &PPC::F8RCRegClass);
2861 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2863 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
2864 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
2865 // once we support fp <-> gpr moves.
2867 // This can only ever happen in the presence of f32 array types,
2868 // since otherwise we never run out of FPRs before running out
2870 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2871 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2873 if (ObjectVT == MVT::f32) {
2874 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2875 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2876 DAG.getConstant(32, MVT::i32));
2877 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2880 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2882 if (CallConv == CallingConv::Fast)
2888 // When passing an array of floats, the array occupies consecutive
2889 // space in the argument area; only round up to the next doubleword
2890 // at the end of the array. Otherwise, each float takes 8 bytes.
2891 if (CallConv != CallingConv::Fast || needsLoad) {
2892 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2893 ArgOffset += ArgSize;
2894 if (Flags.isInConsecutiveRegsLast())
2895 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2904 // These can be scalar arguments or elements of a vector array type
2905 // passed directly. The latter are used to implement ELFv2 homogenous
2906 // vector aggregates.
2907 if (VR_idx != Num_VR_Regs) {
2908 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2909 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2910 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2911 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2914 if (CallConv == CallingConv::Fast)
2919 if (CallConv != CallingConv::Fast || needsLoad)
2924 // We need to load the argument to a virtual register if we determined
2925 // above that we ran out of physical registers of the appropriate type.
2927 if (ObjSize < ArgSize && !isLittleEndian)
2928 CurArgOffset += ArgSize - ObjSize;
2929 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2930 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2931 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2932 false, false, false, 0);
2935 InVals.push_back(ArgVal);
2938 // Area that is at least reserved in the caller of this function.
2939 unsigned MinReservedArea;
2940 if (HasParameterArea)
2941 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2943 MinReservedArea = LinkageSize;
2945 // Set the size that is at least reserved in caller of this function. Tail
2946 // call optimized functions' reserved stack space needs to be aligned so that
2947 // taking the difference between two stack areas will result in an aligned
2950 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2951 FuncInfo->setMinReservedArea(MinReservedArea);
2953 // If the function takes variable number of arguments, make a frame index for
2954 // the start of the first vararg value... for expansion of llvm.va_start.
2956 int Depth = ArgOffset;
2958 FuncInfo->setVarArgsFrameIndex(
2959 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2960 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2962 // If this function is vararg, store any remaining integer argument regs
2963 // to their spots on the stack so that they may be loaded by deferencing the
2964 // result of va_next.
2965 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2966 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2967 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2968 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2969 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2970 MachinePointerInfo(), false, false, 0);
2971 MemOps.push_back(Store);
2972 // Increment the address by four for the next argument to store
2973 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2974 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2978 if (!MemOps.empty())
2979 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2985 PPCTargetLowering::LowerFormalArguments_Darwin(
2987 CallingConv::ID CallConv, bool isVarArg,
2988 const SmallVectorImpl<ISD::InputArg>
2990 SDLoc dl, SelectionDAG &DAG,
2991 SmallVectorImpl<SDValue> &InVals) const {
2992 // TODO: add description of PPC stack frame format, or at least some docs.
2994 MachineFunction &MF = DAG.getMachineFunction();
2995 MachineFrameInfo *MFI = MF.getFrameInfo();
2996 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2998 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2999 bool isPPC64 = PtrVT == MVT::i64;
3000 // Potential tail calls could cause overwriting of argument stack slots.
3001 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3002 (CallConv == CallingConv::Fast));
3003 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3005 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
3007 unsigned ArgOffset = LinkageSize;
3008 // Area that is at least reserved in caller of this function.
3009 unsigned MinReservedArea = ArgOffset;
3011 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3012 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3013 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3015 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3016 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3017 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3020 static const MCPhysReg *FPR = GetFPR();
3022 static const MCPhysReg VR[] = {
3023 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3024 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3027 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3028 const unsigned Num_FPR_Regs = 13;
3029 const unsigned Num_VR_Regs = array_lengthof( VR);
3031 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3033 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3035 // In 32-bit non-varargs functions, the stack space for vectors is after the
3036 // stack space for non-vectors. We do not use this space unless we have
3037 // too many vectors to fit in registers, something that only occurs in
3038 // constructed examples:), but we have to walk the arglist to figure
3039 // that out...for the pathological case, compute VecArgOffset as the
3040 // start of the vector parameter area. Computing VecArgOffset is the
3041 // entire point of the following loop.
3042 unsigned VecArgOffset = ArgOffset;
3043 if (!isVarArg && !isPPC64) {
3044 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3046 EVT ObjectVT = Ins[ArgNo].VT;
3047 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3049 if (Flags.isByVal()) {
3050 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3051 unsigned ObjSize = Flags.getByValSize();
3053 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3054 VecArgOffset += ArgSize;
3058 switch(ObjectVT.getSimpleVT().SimpleTy) {
3059 default: llvm_unreachable("Unhandled argument type!");
3065 case MVT::i64: // PPC64
3067 // FIXME: We are guaranteed to be !isPPC64 at this point.
3068 // Does MVT::i64 apply?
3075 // Nothing to do, we're only looking at Nonvector args here.
3080 // We've found where the vector parameter area in memory is. Skip the
3081 // first 12 parameters; these don't use that memory.
3082 VecArgOffset = ((VecArgOffset+15)/16)*16;
3083 VecArgOffset += 12*16;
3085 // Add DAG nodes to load the arguments or copy them out of registers. On
3086 // entry to a function on PPC, the arguments start after the linkage area,
3087 // although the first ones are often in registers.
3089 SmallVector<SDValue, 8> MemOps;
3090 unsigned nAltivecParamsAtEnd = 0;
3091 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3092 unsigned CurArgIdx = 0;
3093 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3095 bool needsLoad = false;
3096 EVT ObjectVT = Ins[ArgNo].VT;
3097 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3098 unsigned ArgSize = ObjSize;
3099 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3100 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3101 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3103 unsigned CurArgOffset = ArgOffset;
3105 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3106 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3107 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3108 if (isVarArg || isPPC64) {
3109 MinReservedArea = ((MinReservedArea+15)/16)*16;
3110 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3113 } else nAltivecParamsAtEnd++;
3115 // Calculate min reserved area.
3116 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3120 // FIXME the codegen can be much improved in some cases.
3121 // We do not have to keep everything in memory.
3122 if (Flags.isByVal()) {
3123 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3124 ObjSize = Flags.getByValSize();
3125 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3126 // Objects of size 1 and 2 are right justified, everything else is
3127 // left justified. This means the memory address is adjusted forwards.
3128 if (ObjSize==1 || ObjSize==2) {
3129 CurArgOffset = CurArgOffset + (4 - ObjSize);
3131 // The value of the object is its address.
3132 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3133 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3134 InVals.push_back(FIN);
3135 if (ObjSize==1 || ObjSize==2) {
3136 if (GPR_idx != Num_GPR_Regs) {
3139 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3141 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3142 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3143 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3144 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3145 MachinePointerInfo(FuncArg),
3146 ObjType, false, false, 0);
3147 MemOps.push_back(Store);
3151 ArgOffset += PtrByteSize;
3155 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3156 // Store whatever pieces of the object are in registers
3157 // to memory. ArgOffset will be the address of the beginning
3159 if (GPR_idx != Num_GPR_Regs) {
3162 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3164 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3165 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3166 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3167 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3168 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3169 MachinePointerInfo(FuncArg, j),
3171 MemOps.push_back(Store);
3173 ArgOffset += PtrByteSize;
3175 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3182 switch (ObjectVT.getSimpleVT().SimpleTy) {
3183 default: llvm_unreachable("Unhandled argument type!");
3187 if (GPR_idx != Num_GPR_Regs) {
3188 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3189 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3191 if (ObjectVT == MVT::i1)
3192 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3197 ArgSize = PtrByteSize;
3199 // All int arguments reserve stack space in the Darwin ABI.
3200 ArgOffset += PtrByteSize;
3204 case MVT::i64: // PPC64
3205 if (GPR_idx != Num_GPR_Regs) {
3206 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3207 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3209 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3210 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3211 // value to MVT::i64 and then truncate to the correct register size.
3212 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3217 ArgSize = PtrByteSize;
3219 // All int arguments reserve stack space in the Darwin ABI.
3225 // Every 4 bytes of argument space consumes one of the GPRs available for
3226 // argument passing.
3227 if (GPR_idx != Num_GPR_Regs) {
3229 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3232 if (FPR_idx != Num_FPR_Regs) {
3235 if (ObjectVT == MVT::f32)
3236 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3238 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3240 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3246 // All FP arguments reserve stack space in the Darwin ABI.
3247 ArgOffset += isPPC64 ? 8 : ObjSize;
3253 // Note that vector arguments in registers don't reserve stack space,
3254 // except in varargs functions.
3255 if (VR_idx != Num_VR_Regs) {
3256 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3257 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3259 while ((ArgOffset % 16) != 0) {
3260 ArgOffset += PtrByteSize;
3261 if (GPR_idx != Num_GPR_Regs)
3265 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3269 if (!isVarArg && !isPPC64) {
3270 // Vectors go after all the nonvectors.
3271 CurArgOffset = VecArgOffset;
3274 // Vectors are aligned.
3275 ArgOffset = ((ArgOffset+15)/16)*16;
3276 CurArgOffset = ArgOffset;
3284 // We need to load the argument to a virtual register if we determined above
3285 // that we ran out of physical registers of the appropriate type.
3287 int FI = MFI->CreateFixedObject(ObjSize,
3288 CurArgOffset + (ArgSize - ObjSize),
3290 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3291 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3292 false, false, false, 0);
3295 InVals.push_back(ArgVal);
3298 // Allow for Altivec parameters at the end, if needed.
3299 if (nAltivecParamsAtEnd) {
3300 MinReservedArea = ((MinReservedArea+15)/16)*16;
3301 MinReservedArea += 16*nAltivecParamsAtEnd;
3304 // Area that is at least reserved in the caller of this function.
3305 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3307 // Set the size that is at least reserved in caller of this function. Tail
3308 // call optimized functions' reserved stack space needs to be aligned so that
3309 // taking the difference between two stack areas will result in an aligned
3312 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3313 FuncInfo->setMinReservedArea(MinReservedArea);
3315 // If the function takes variable number of arguments, make a frame index for
3316 // the start of the first vararg value... for expansion of llvm.va_start.
3318 int Depth = ArgOffset;
3320 FuncInfo->setVarArgsFrameIndex(
3321 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3323 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3325 // If this function is vararg, store any remaining integer argument regs
3326 // to their spots on the stack so that they may be loaded by deferencing the
3327 // result of va_next.
3328 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3332 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3334 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3336 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3337 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3338 MachinePointerInfo(), false, false, 0);
3339 MemOps.push_back(Store);
3340 // Increment the address by four for the next argument to store
3341 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3342 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3346 if (!MemOps.empty())
3347 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3352 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3353 /// adjusted to accommodate the arguments for the tailcall.
3354 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3355 unsigned ParamSize) {
3357 if (!isTailCall) return 0;
3359 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3360 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3361 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3362 // Remember only if the new adjustement is bigger.
3363 if (SPDiff < FI->getTailCallSPDelta())
3364 FI->setTailCallSPDelta(SPDiff);
3369 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3370 /// for tail call optimization. Targets which want to do tail call
3371 /// optimization should implement this function.
3373 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3374 CallingConv::ID CalleeCC,
3376 const SmallVectorImpl<ISD::InputArg> &Ins,
3377 SelectionDAG& DAG) const {
3378 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3381 // Variable argument functions are not supported.
3385 MachineFunction &MF = DAG.getMachineFunction();
3386 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3387 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3388 // Functions containing by val parameters are not supported.
3389 for (unsigned i = 0; i != Ins.size(); i++) {
3390 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3391 if (Flags.isByVal()) return false;
3394 // Non-PIC/GOT tail calls are supported.
3395 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3398 // At the moment we can only do local tail calls (in same module, hidden
3399 // or protected) if we are generating PIC.
3400 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3401 return G->getGlobal()->hasHiddenVisibility()
3402 || G->getGlobal()->hasProtectedVisibility();
3408 /// isCallCompatibleAddress - Return the immediate to use if the specified
3409 /// 32-bit value is representable in the immediate field of a BxA instruction.
3410 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3411 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3412 if (!C) return nullptr;
3414 int Addr = C->getZExtValue();
3415 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3416 SignExtend32<26>(Addr) != Addr)
3417 return nullptr; // Top 6 bits have to be sext of immediate.
3419 return DAG.getConstant((int)C->getZExtValue() >> 2,
3420 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3425 struct TailCallArgumentInfo {
3430 TailCallArgumentInfo() : FrameIdx(0) {}
3435 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3437 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3439 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3440 SmallVectorImpl<SDValue> &MemOpChains,
3442 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3443 SDValue Arg = TailCallArgs[i].Arg;
3444 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3445 int FI = TailCallArgs[i].FrameIdx;
3446 // Store relative to framepointer.
3447 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3448 MachinePointerInfo::getFixedStack(FI),
3453 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3454 /// the appropriate stack slot for the tail call optimized function call.
3455 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3456 MachineFunction &MF,
3465 // Calculate the new stack slot for the return address.
3466 int SlotSize = isPPC64 ? 8 : 4;
3467 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3469 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3470 NewRetAddrLoc, true);
3471 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3472 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3473 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3474 MachinePointerInfo::getFixedStack(NewRetAddr),
3477 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3478 // slot as the FP is never overwritten.
3481 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3482 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3484 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3485 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3486 MachinePointerInfo::getFixedStack(NewFPIdx),
3493 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3494 /// the position of the argument.
3496 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3497 SDValue Arg, int SPDiff, unsigned ArgOffset,
3498 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3499 int Offset = ArgOffset + SPDiff;
3500 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3501 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3502 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3503 SDValue FIN = DAG.getFrameIndex(FI, VT);
3504 TailCallArgumentInfo Info;
3506 Info.FrameIdxOp = FIN;
3508 TailCallArguments.push_back(Info);
3511 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3512 /// stack slot. Returns the chain as result and the loaded frame pointers in
3513 /// LROpOut/FPOpout. Used when tail calling.
3514 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3522 // Load the LR and FP stack slot for later adjusting.
3523 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3524 LROpOut = getReturnAddrFrameIndex(DAG);
3525 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3526 false, false, false, 0);
3527 Chain = SDValue(LROpOut.getNode(), 1);
3529 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3530 // slot as the FP is never overwritten.
3532 FPOpOut = getFramePointerFrameIndex(DAG);
3533 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3534 false, false, false, 0);
3535 Chain = SDValue(FPOpOut.getNode(), 1);
3541 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3542 /// by "Src" to address "Dst" of size "Size". Alignment information is
3543 /// specified by the specific parameter attribute. The copy will be passed as
3544 /// a byval function parameter.
3545 /// Sometimes what we are copying is the end of a larger object, the part that
3546 /// does not fit in registers.
3548 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3549 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3551 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3552 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3553 false, false, MachinePointerInfo(),
3554 MachinePointerInfo());
3557 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3560 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3561 SDValue Arg, SDValue PtrOff, int SPDiff,
3562 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3563 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3564 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3566 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3571 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3573 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3574 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3575 DAG.getConstant(ArgOffset, PtrVT));
3577 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3578 MachinePointerInfo(), false, false, 0));
3579 // Calculate and remember argument location.
3580 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3585 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3586 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3587 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3588 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3589 MachineFunction &MF = DAG.getMachineFunction();
3591 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3592 // might overwrite each other in case of tail call optimization.
3593 SmallVector<SDValue, 8> MemOpChains2;
3594 // Do not flag preceding copytoreg stuff together with the following stuff.
3596 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3598 if (!MemOpChains2.empty())
3599 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3601 // Store the return address to the appropriate stack slot.
3602 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3603 isPPC64, isDarwinABI, dl);
3605 // Emit callseq_end just before tailcall node.
3606 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3607 DAG.getIntPtrConstant(0, true), InFlag, dl);
3608 InFlag = Chain.getValue(1);
3611 // Is this global address that of a function that can be called by name? (as
3612 // opposed to something that must hold a descriptor for an indirect call).
3613 static bool isFunctionGlobalAddress(SDValue Callee) {
3614 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3615 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3616 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3619 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3626 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3627 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3628 bool isTailCall, bool IsPatchPoint,
3629 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3630 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3631 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3633 bool isPPC64 = Subtarget.isPPC64();
3634 bool isSVR4ABI = Subtarget.isSVR4ABI();
3635 bool isELFv2ABI = Subtarget.isELFv2ABI();
3637 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3638 NodeTys.push_back(MVT::Other); // Returns a chain
3639 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3641 unsigned CallOpc = PPCISD::CALL;
3643 bool needIndirectCall = true;
3644 if (!isSVR4ABI || !isPPC64)
3645 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3646 // If this is an absolute destination address, use the munged value.
3647 Callee = SDValue(Dest, 0);
3648 needIndirectCall = false;
3651 if (isFunctionGlobalAddress(Callee)) {
3652 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3653 // A call to a TLS address is actually an indirect call to a
3654 // thread-specific pointer.
3655 unsigned OpFlags = 0;
3656 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3657 (Subtarget.getTargetTriple().isMacOSX() &&
3658 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3659 (G->getGlobal()->isDeclaration() ||
3660 G->getGlobal()->isWeakForLinker())) ||
3661 (Subtarget.isTargetELF() && !isPPC64 &&
3662 !G->getGlobal()->hasLocalLinkage() &&
3663 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3664 // PC-relative references to external symbols should go through $stub,
3665 // unless we're building with the leopard linker or later, which
3666 // automatically synthesizes these stubs.
3667 OpFlags = PPCII::MO_PLT_OR_STUB;
3670 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3671 // every direct call is) turn it into a TargetGlobalAddress /
3672 // TargetExternalSymbol node so that legalize doesn't hack it.
3673 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3674 Callee.getValueType(), 0, OpFlags);
3675 needIndirectCall = false;
3678 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3679 unsigned char OpFlags = 0;
3681 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3682 (Subtarget.getTargetTriple().isMacOSX() &&
3683 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3684 (Subtarget.isTargetELF() && !isPPC64 &&
3685 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3686 // PC-relative references to external symbols should go through $stub,
3687 // unless we're building with the leopard linker or later, which
3688 // automatically synthesizes these stubs.
3689 OpFlags = PPCII::MO_PLT_OR_STUB;
3692 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3694 needIndirectCall = false;
3698 // We'll form an invalid direct call when lowering a patchpoint; the full
3699 // sequence for an indirect call is complicated, and many of the
3700 // instructions introduced might have side effects (and, thus, can't be
3701 // removed later). The call itself will be removed as soon as the
3702 // argument/return lowering is complete, so the fact that it has the wrong
3703 // kind of operands should not really matter.
3704 needIndirectCall = false;
3707 if (needIndirectCall) {
3708 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3709 // to do the call, we can't use PPCISD::CALL.
3710 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3712 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3713 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3714 // entry point, but to the function descriptor (the function entry point
3715 // address is part of the function descriptor though).
3716 // The function descriptor is a three doubleword structure with the
3717 // following fields: function entry point, TOC base address and
3718 // environment pointer.
3719 // Thus for a call through a function pointer, the following actions need
3721 // 1. Save the TOC of the caller in the TOC save area of its stack
3722 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3723 // 2. Load the address of the function entry point from the function
3725 // 3. Load the TOC of the callee from the function descriptor into r2.
3726 // 4. Load the environment pointer from the function descriptor into
3728 // 5. Branch to the function entry point address.
3729 // 6. On return of the callee, the TOC of the caller needs to be
3730 // restored (this is done in FinishCall()).
3732 // The loads are scheduled at the beginning of the call sequence, and the
3733 // register copies are flagged together to ensure that no other
3734 // operations can be scheduled in between. E.g. without flagging the
3735 // copies together, a TOC access in the caller could be scheduled between
3736 // the assignment of the callee TOC and the branch to the callee, which
3737 // results in the TOC access going through the TOC of the callee instead
3738 // of going through the TOC of the caller, which leads to incorrect code.
3740 // Load the address of the function entry point from the function
3742 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
3743 if (LDChain.getValueType() == MVT::Glue)
3744 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
3746 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
3748 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
3749 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
3750 false, false, LoadsInv, 8);
3752 // Load environment pointer into r11.
3753 SDValue PtrOff = DAG.getIntPtrConstant(16);
3754 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3755 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
3756 MPI.getWithOffset(16), false, false,
3759 SDValue TOCOff = DAG.getIntPtrConstant(8);
3760 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3761 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
3762 MPI.getWithOffset(8), false, false,
3765 setUsesTOCBasePtr(DAG);
3766 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
3768 Chain = TOCVal.getValue(0);
3769 InFlag = TOCVal.getValue(1);
3771 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3774 Chain = EnvVal.getValue(0);
3775 InFlag = EnvVal.getValue(1);
3777 MTCTROps[0] = Chain;
3778 MTCTROps[1] = LoadFuncPtr;
3779 MTCTROps[2] = InFlag;
3782 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3783 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3784 InFlag = Chain.getValue(1);
3787 NodeTys.push_back(MVT::Other);
3788 NodeTys.push_back(MVT::Glue);
3789 Ops.push_back(Chain);
3790 CallOpc = PPCISD::BCTRL;
3791 Callee.setNode(nullptr);
3792 // Add use of X11 (holding environment pointer)
3793 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3794 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3795 // Add CTR register as callee so a bctr can be emitted later.
3797 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3800 // If this is a direct call, pass the chain and the callee.
3801 if (Callee.getNode()) {
3802 Ops.push_back(Chain);
3803 Ops.push_back(Callee);
3805 // If this is a tail call add stack pointer delta.
3807 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3809 // Add argument registers to the end of the list so that they are known live
3811 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3812 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3813 RegsToPass[i].second.getValueType()));
3815 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
3817 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
3818 setUsesTOCBasePtr(DAG);
3819 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3826 bool isLocalCall(const SDValue &Callee)
3828 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3829 return !G->getGlobal()->isDeclaration() &&
3830 !G->getGlobal()->isWeakForLinker();
3835 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3836 CallingConv::ID CallConv, bool isVarArg,
3837 const SmallVectorImpl<ISD::InputArg> &Ins,
3838 SDLoc dl, SelectionDAG &DAG,
3839 SmallVectorImpl<SDValue> &InVals) const {
3841 SmallVector<CCValAssign, 16> RVLocs;
3842 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3844 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3846 // Copy all of the result registers out of their specified physreg.
3847 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3848 CCValAssign &VA = RVLocs[i];
3849 assert(VA.isRegLoc() && "Can only return in registers!");
3851 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3852 VA.getLocReg(), VA.getLocVT(), InFlag);
3853 Chain = Val.getValue(1);
3854 InFlag = Val.getValue(2);
3856 switch (VA.getLocInfo()) {
3857 default: llvm_unreachable("Unknown loc info!");
3858 case CCValAssign::Full: break;
3859 case CCValAssign::AExt:
3860 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3862 case CCValAssign::ZExt:
3863 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3864 DAG.getValueType(VA.getValVT()));
3865 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3867 case CCValAssign::SExt:
3868 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3869 DAG.getValueType(VA.getValVT()));
3870 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3874 InVals.push_back(Val);
3881 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3882 bool isTailCall, bool isVarArg, bool IsPatchPoint,
3884 SmallVector<std::pair<unsigned, SDValue>, 8>
3886 SDValue InFlag, SDValue Chain,
3887 SDValue CallSeqStart, SDValue &Callee,
3888 int SPDiff, unsigned NumBytes,
3889 const SmallVectorImpl<ISD::InputArg> &Ins,
3890 SmallVectorImpl<SDValue> &InVals,
3891 ImmutableCallSite *CS) const {
3893 bool isELFv2ABI = Subtarget.isELFv2ABI();
3894 std::vector<EVT> NodeTys;
3895 SmallVector<SDValue, 8> Ops;
3896 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
3897 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
3898 Ops, NodeTys, CS, Subtarget);
3900 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3901 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3902 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3904 // When performing tail call optimization the callee pops its arguments off
3905 // the stack. Account for this here so these bytes can be pushed back on in
3906 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3907 int BytesCalleePops =
3908 (CallConv == CallingConv::Fast &&
3909 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3911 // Add a register mask operand representing the call-preserved registers.
3912 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3913 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3914 assert(Mask && "Missing call preserved mask for calling convention");
3915 Ops.push_back(DAG.getRegisterMask(Mask));
3917 if (InFlag.getNode())
3918 Ops.push_back(InFlag);
3922 assert(((Callee.getOpcode() == ISD::Register &&
3923 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3924 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3925 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3926 isa<ConstantSDNode>(Callee)) &&
3927 "Expecting an global address, external symbol, absolute value or register");
3929 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3932 // Add a NOP immediately after the branch instruction when using the 64-bit
3933 // SVR4 ABI. At link time, if caller and callee are in a different module and
3934 // thus have a different TOC, the call will be replaced with a call to a stub
3935 // function which saves the current TOC, loads the TOC of the callee and
3936 // branches to the callee. The NOP will be replaced with a load instruction
3937 // which restores the TOC of the caller from the TOC save slot of the current
3938 // stack frame. If caller and callee belong to the same module (and have the
3939 // same TOC), the NOP will remain unchanged.
3941 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
3943 if (CallOpc == PPCISD::BCTRL) {
3944 // This is a call through a function pointer.
3945 // Restore the caller TOC from the save area into R2.
3946 // See PrepareCall() for more information about calls through function
3947 // pointers in the 64-bit SVR4 ABI.
3948 // We are using a target-specific load with r2 hard coded, because the
3949 // result of a target-independent load would never go directly into r2,
3950 // since r2 is a reserved register (which prevents the register allocator
3951 // from allocating it), resulting in an additional register being
3952 // allocated and an unnecessary move instruction being generated.
3953 CallOpc = PPCISD::BCTRL_LOAD_TOC;
3955 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3956 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3957 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3958 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3959 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3961 // The address needs to go after the chain input but before the flag (or
3962 // any other variadic arguments).
3963 Ops.insert(std::next(Ops.begin()), AddTOC);
3964 } else if ((CallOpc == PPCISD::CALL) &&
3965 (!isLocalCall(Callee) ||
3966 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
3967 // Otherwise insert NOP for non-local calls.
3968 CallOpc = PPCISD::CALL_NOP;
3971 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3972 InFlag = Chain.getValue(1);
3974 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3975 DAG.getIntPtrConstant(BytesCalleePops, true),
3978 InFlag = Chain.getValue(1);
3980 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3981 Ins, dl, DAG, InVals);
3985 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3986 SmallVectorImpl<SDValue> &InVals) const {
3987 SelectionDAG &DAG = CLI.DAG;
3989 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3990 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3991 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3992 SDValue Chain = CLI.Chain;
3993 SDValue Callee = CLI.Callee;
3994 bool &isTailCall = CLI.IsTailCall;
3995 CallingConv::ID CallConv = CLI.CallConv;
3996 bool isVarArg = CLI.IsVarArg;
3997 bool IsPatchPoint = CLI.IsPatchPoint;
3998 ImmutableCallSite *CS = CLI.CS;
4001 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4004 if (!isTailCall && CS && CS->isMustTailCall())
4005 report_fatal_error("failed to perform tail call elimination on a call "
4006 "site marked musttail");
4008 if (Subtarget.isSVR4ABI()) {
4009 if (Subtarget.isPPC64())
4010 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4011 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4012 dl, DAG, InVals, CS);
4014 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4015 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4016 dl, DAG, InVals, CS);
4019 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4020 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4021 dl, DAG, InVals, CS);
4025 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4026 CallingConv::ID CallConv, bool isVarArg,
4027 bool isTailCall, bool IsPatchPoint,
4028 const SmallVectorImpl<ISD::OutputArg> &Outs,
4029 const SmallVectorImpl<SDValue> &OutVals,
4030 const SmallVectorImpl<ISD::InputArg> &Ins,
4031 SDLoc dl, SelectionDAG &DAG,
4032 SmallVectorImpl<SDValue> &InVals,
4033 ImmutableCallSite *CS) const {
4034 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4035 // of the 32-bit SVR4 ABI stack frame layout.
4037 assert((CallConv == CallingConv::C ||
4038 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4040 unsigned PtrByteSize = 4;
4042 MachineFunction &MF = DAG.getMachineFunction();
4044 // Mark this function as potentially containing a function that contains a
4045 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4046 // and restoring the callers stack pointer in this functions epilog. This is
4047 // done because by tail calling the called function might overwrite the value
4048 // in this function's (MF) stack pointer stack slot 0(SP).
4049 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4050 CallConv == CallingConv::Fast)
4051 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4053 // Count how many bytes are to be pushed on the stack, including the linkage
4054 // area, parameter list area and the part of the local variable space which
4055 // contains copies of aggregates which are passed by value.
4057 // Assign locations to all of the outgoing arguments.
4058 SmallVector<CCValAssign, 16> ArgLocs;
4059 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4062 // Reserve space for the linkage area on the stack.
4063 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4067 // Handle fixed and variable vector arguments differently.
4068 // Fixed vector arguments go into registers as long as registers are
4069 // available. Variable vector arguments always go into memory.
4070 unsigned NumArgs = Outs.size();
4072 for (unsigned i = 0; i != NumArgs; ++i) {
4073 MVT ArgVT = Outs[i].VT;
4074 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4077 if (Outs[i].IsFixed) {
4078 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4081 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4087 errs() << "Call operand #" << i << " has unhandled type "
4088 << EVT(ArgVT).getEVTString() << "\n";
4090 llvm_unreachable(nullptr);
4094 // All arguments are treated the same.
4095 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4098 // Assign locations to all of the outgoing aggregate by value arguments.
4099 SmallVector<CCValAssign, 16> ByValArgLocs;
4100 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4101 ByValArgLocs, *DAG.getContext());
4103 // Reserve stack space for the allocations in CCInfo.
4104 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4106 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4108 // Size of the linkage area, parameter list area and the part of the local
4109 // space variable where copies of aggregates which are passed by value are
4111 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4113 // Calculate by how many bytes the stack has to be adjusted in case of tail
4114 // call optimization.
4115 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4117 // Adjust the stack pointer for the new arguments...
4118 // These operations are automatically eliminated by the prolog/epilog pass
4119 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4121 SDValue CallSeqStart = Chain;
4123 // Load the return address and frame pointer so it can be moved somewhere else
4126 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4129 // Set up a copy of the stack pointer for use loading and storing any
4130 // arguments that may not fit in the registers available for argument
4132 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4134 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4135 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4136 SmallVector<SDValue, 8> MemOpChains;
4138 bool seenFloatArg = false;
4139 // Walk the register/memloc assignments, inserting copies/loads.
4140 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4143 CCValAssign &VA = ArgLocs[i];
4144 SDValue Arg = OutVals[i];
4145 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4147 if (Flags.isByVal()) {
4148 // Argument is an aggregate which is passed by value, thus we need to
4149 // create a copy of it in the local variable space of the current stack
4150 // frame (which is the stack frame of the caller) and pass the address of
4151 // this copy to the callee.
4152 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4153 CCValAssign &ByValVA = ByValArgLocs[j++];
4154 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4156 // Memory reserved in the local variable space of the callers stack frame.
4157 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4159 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4160 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4162 // Create a copy of the argument in the local area of the current
4164 SDValue MemcpyCall =
4165 CreateCopyOfByValArgument(Arg, PtrOff,
4166 CallSeqStart.getNode()->getOperand(0),
4169 // This must go outside the CALLSEQ_START..END.
4170 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4171 CallSeqStart.getNode()->getOperand(1),
4173 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4174 NewCallSeqStart.getNode());
4175 Chain = CallSeqStart = NewCallSeqStart;
4177 // Pass the address of the aggregate copy on the stack either in a
4178 // physical register or in the parameter list area of the current stack
4179 // frame to the callee.
4183 if (VA.isRegLoc()) {
4184 if (Arg.getValueType() == MVT::i1)
4185 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4187 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4188 // Put argument in a physical register.
4189 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4191 // Put argument in the parameter list area of the current stack frame.
4192 assert(VA.isMemLoc());
4193 unsigned LocMemOffset = VA.getLocMemOffset();
4196 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4197 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4199 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4200 MachinePointerInfo(),
4203 // Calculate and remember argument location.
4204 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4210 if (!MemOpChains.empty())
4211 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4213 // Build a sequence of copy-to-reg nodes chained together with token chain
4214 // and flag operands which copy the outgoing args into the appropriate regs.
4216 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4217 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4218 RegsToPass[i].second, InFlag);
4219 InFlag = Chain.getValue(1);
4222 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4225 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4226 SDValue Ops[] = { Chain, InFlag };
4228 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4229 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4231 InFlag = Chain.getValue(1);
4235 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4236 false, TailCallArguments);
4238 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4239 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4240 NumBytes, Ins, InVals, CS);
4243 // Copy an argument into memory, being careful to do this outside the
4244 // call sequence for the call to which the argument belongs.
4246 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4247 SDValue CallSeqStart,
4248 ISD::ArgFlagsTy Flags,
4251 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4252 CallSeqStart.getNode()->getOperand(0),
4254 // The MEMCPY must go outside the CALLSEQ_START..END.
4255 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4256 CallSeqStart.getNode()->getOperand(1),
4258 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4259 NewCallSeqStart.getNode());
4260 return NewCallSeqStart;
4264 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4265 CallingConv::ID CallConv, bool isVarArg,
4266 bool isTailCall, bool IsPatchPoint,
4267 const SmallVectorImpl<ISD::OutputArg> &Outs,
4268 const SmallVectorImpl<SDValue> &OutVals,
4269 const SmallVectorImpl<ISD::InputArg> &Ins,
4270 SDLoc dl, SelectionDAG &DAG,
4271 SmallVectorImpl<SDValue> &InVals,
4272 ImmutableCallSite *CS) const {
4274 bool isELFv2ABI = Subtarget.isELFv2ABI();
4275 bool isLittleEndian = Subtarget.isLittleEndian();
4276 unsigned NumOps = Outs.size();
4278 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4279 unsigned PtrByteSize = 8;
4281 MachineFunction &MF = DAG.getMachineFunction();
4283 // Mark this function as potentially containing a function that contains a
4284 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4285 // and restoring the callers stack pointer in this functions epilog. This is
4286 // done because by tail calling the called function might overwrite the value
4287 // in this function's (MF) stack pointer stack slot 0(SP).
4288 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4289 CallConv == CallingConv::Fast)
4290 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4292 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4293 "fastcc not supported on varargs functions");
4295 // Count how many bytes are to be pushed on the stack, including the linkage
4296 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4297 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4298 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4299 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4301 unsigned NumBytes = LinkageSize;
4302 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4304 static const MCPhysReg GPR[] = {
4305 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4306 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4308 static const MCPhysReg *FPR = GetFPR();
4310 static const MCPhysReg VR[] = {
4311 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4312 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4314 static const MCPhysReg VSRH[] = {
4315 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4316 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4319 const unsigned NumGPRs = array_lengthof(GPR);
4320 const unsigned NumFPRs = 13;
4321 const unsigned NumVRs = array_lengthof(VR);
4323 // When using the fast calling convention, we don't provide backing for
4324 // arguments that will be in registers.
4325 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4327 // Add up all the space actually used.
4328 for (unsigned i = 0; i != NumOps; ++i) {
4329 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4330 EVT ArgVT = Outs[i].VT;
4331 EVT OrigVT = Outs[i].ArgVT;
4333 if (CallConv == CallingConv::Fast) {
4334 if (Flags.isByVal())
4335 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4337 switch (ArgVT.getSimpleVT().SimpleTy) {
4338 default: llvm_unreachable("Unexpected ValueType for argument!");
4342 if (++NumGPRsUsed <= NumGPRs)
4347 if (++NumFPRsUsed <= NumFPRs)
4356 if (++NumVRsUsed <= NumVRs)
4362 /* Respect alignment of argument on the stack. */
4364 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4365 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4367 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4368 if (Flags.isInConsecutiveRegsLast())
4369 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4372 unsigned NumBytesActuallyUsed = NumBytes;
4374 // The prolog code of the callee may store up to 8 GPR argument registers to
4375 // the stack, allowing va_start to index over them in memory if its varargs.
4376 // Because we cannot tell if this is needed on the caller side, we have to
4377 // conservatively assume that it is needed. As such, make sure we have at
4378 // least enough stack space for the caller to store the 8 GPRs.
4379 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4380 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4382 // Tail call needs the stack to be aligned.
4383 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4384 CallConv == CallingConv::Fast)
4385 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4387 // Calculate by how many bytes the stack has to be adjusted in case of tail
4388 // call optimization.
4389 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4391 // To protect arguments on the stack from being clobbered in a tail call,
4392 // force all the loads to happen before doing any other lowering.
4394 Chain = DAG.getStackArgumentTokenFactor(Chain);
4396 // Adjust the stack pointer for the new arguments...
4397 // These operations are automatically eliminated by the prolog/epilog pass
4398 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4400 SDValue CallSeqStart = Chain;
4402 // Load the return address and frame pointer so it can be move somewhere else
4405 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4408 // Set up a copy of the stack pointer for use loading and storing any
4409 // arguments that may not fit in the registers available for argument
4411 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4413 // Figure out which arguments are going to go in registers, and which in
4414 // memory. Also, if this is a vararg function, floating point operations
4415 // must be stored to our stack, and loaded into integer regs as well, if
4416 // any integer regs are available for argument passing.
4417 unsigned ArgOffset = LinkageSize;
4419 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4420 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4422 SmallVector<SDValue, 8> MemOpChains;
4423 for (unsigned i = 0; i != NumOps; ++i) {
4424 SDValue Arg = OutVals[i];
4425 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4426 EVT ArgVT = Outs[i].VT;
4427 EVT OrigVT = Outs[i].ArgVT;
4429 // PtrOff will be used to store the current argument to the stack if a
4430 // register cannot be found for it.
4433 // We re-align the argument offset for each argument, except when using the
4434 // fast calling convention, when we need to make sure we do that only when
4435 // we'll actually use a stack slot.
4436 auto ComputePtrOff = [&]() {
4437 /* Respect alignment of argument on the stack. */
4439 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4440 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4442 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4444 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4447 if (CallConv != CallingConv::Fast) {
4450 /* Compute GPR index associated with argument offset. */
4451 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4452 GPR_idx = std::min(GPR_idx, NumGPRs);
4455 // Promote integers to 64-bit values.
4456 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4457 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4458 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4459 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4462 // FIXME memcpy is used way more than necessary. Correctness first.
4463 // Note: "by value" is code for passing a structure by value, not
4465 if (Flags.isByVal()) {
4466 // Note: Size includes alignment padding, so
4467 // struct x { short a; char b; }
4468 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4469 // These are the proper values we need for right-justifying the
4470 // aggregate in a parameter register.
4471 unsigned Size = Flags.getByValSize();
4473 // An empty aggregate parameter takes up no storage and no
4478 if (CallConv == CallingConv::Fast)
4481 // All aggregates smaller than 8 bytes must be passed right-justified.
4482 if (Size==1 || Size==2 || Size==4) {
4483 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4484 if (GPR_idx != NumGPRs) {
4485 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4486 MachinePointerInfo(), VT,
4487 false, false, false, 0);
4488 MemOpChains.push_back(Load.getValue(1));
4489 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4491 ArgOffset += PtrByteSize;
4496 if (GPR_idx == NumGPRs && Size < 8) {
4497 SDValue AddPtr = PtrOff;
4498 if (!isLittleEndian) {
4499 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4500 PtrOff.getValueType());
4501 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4503 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4506 ArgOffset += PtrByteSize;
4509 // Copy entire object into memory. There are cases where gcc-generated
4510 // code assumes it is there, even if it could be put entirely into
4511 // registers. (This is not what the doc says.)
4513 // FIXME: The above statement is likely due to a misunderstanding of the
4514 // documents. All arguments must be copied into the parameter area BY
4515 // THE CALLEE in the event that the callee takes the address of any
4516 // formal argument. That has not yet been implemented. However, it is
4517 // reasonable to use the stack area as a staging area for the register
4520 // Skip this for small aggregates, as we will use the same slot for a
4521 // right-justified copy, below.
4523 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4527 // When a register is available, pass a small aggregate right-justified.
4528 if (Size < 8 && GPR_idx != NumGPRs) {
4529 // The easiest way to get this right-justified in a register
4530 // is to copy the structure into the rightmost portion of a
4531 // local variable slot, then load the whole slot into the
4533 // FIXME: The memcpy seems to produce pretty awful code for
4534 // small aggregates, particularly for packed ones.
4535 // FIXME: It would be preferable to use the slot in the
4536 // parameter save area instead of a new local variable.
4537 SDValue AddPtr = PtrOff;
4538 if (!isLittleEndian) {
4539 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4540 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4542 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4546 // Load the slot into the register.
4547 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4548 MachinePointerInfo(),
4549 false, false, false, 0);
4550 MemOpChains.push_back(Load.getValue(1));
4551 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4553 // Done with this argument.
4554 ArgOffset += PtrByteSize;
4558 // For aggregates larger than PtrByteSize, copy the pieces of the
4559 // object that fit into registers from the parameter save area.
4560 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4561 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4562 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4563 if (GPR_idx != NumGPRs) {
4564 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4565 MachinePointerInfo(),
4566 false, false, false, 0);
4567 MemOpChains.push_back(Load.getValue(1));
4568 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4569 ArgOffset += PtrByteSize;
4571 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4578 switch (Arg.getSimpleValueType().SimpleTy) {
4579 default: llvm_unreachable("Unexpected ValueType for argument!");
4583 // These can be scalar arguments or elements of an integer array type
4584 // passed directly. Clang may use those instead of "byval" aggregate
4585 // types to avoid forcing arguments to memory unnecessarily.
4586 if (GPR_idx != NumGPRs) {
4587 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4589 if (CallConv == CallingConv::Fast)
4592 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4593 true, isTailCall, false, MemOpChains,
4594 TailCallArguments, dl);
4595 if (CallConv == CallingConv::Fast)
4596 ArgOffset += PtrByteSize;
4598 if (CallConv != CallingConv::Fast)
4599 ArgOffset += PtrByteSize;
4603 // These can be scalar arguments or elements of a float array type
4604 // passed directly. The latter are used to implement ELFv2 homogenous
4605 // float aggregates.
4607 // Named arguments go into FPRs first, and once they overflow, the
4608 // remaining arguments go into GPRs and then the parameter save area.
4609 // Unnamed arguments for vararg functions always go to GPRs and
4610 // then the parameter save area. For now, put all arguments to vararg
4611 // routines always in both locations (FPR *and* GPR or stack slot).
4612 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4613 bool NeededLoad = false;
4615 // First load the argument into the next available FPR.
4616 if (FPR_idx != NumFPRs)
4617 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4619 // Next, load the argument into GPR or stack slot if needed.
4620 if (!NeedGPROrStack)
4622 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4623 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4624 // once we support fp <-> gpr moves.
4626 // In the non-vararg case, this can only ever happen in the
4627 // presence of f32 array types, since otherwise we never run
4628 // out of FPRs before running out of GPRs.
4631 // Double values are always passed in a single GPR.
4632 if (Arg.getValueType() != MVT::f32) {
4633 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4635 // Non-array float values are extended and passed in a GPR.
4636 } else if (!Flags.isInConsecutiveRegs()) {
4637 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4638 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4640 // If we have an array of floats, we collect every odd element
4641 // together with its predecessor into one GPR.
4642 } else if (ArgOffset % PtrByteSize != 0) {
4644 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4645 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4646 if (!isLittleEndian)
4648 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4650 // The final element, if even, goes into the first half of a GPR.
4651 } else if (Flags.isInConsecutiveRegsLast()) {
4652 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4653 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4654 if (!isLittleEndian)
4655 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4656 DAG.getConstant(32, MVT::i32));
4658 // Non-final even elements are skipped; they will be handled
4659 // together the with subsequent argument on the next go-around.
4663 if (ArgVal.getNode())
4664 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4666 if (CallConv == CallingConv::Fast)
4669 // Single-precision floating-point values are mapped to the
4670 // second (rightmost) word of the stack doubleword.
4671 if (Arg.getValueType() == MVT::f32 &&
4672 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4673 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4674 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4677 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4678 true, isTailCall, false, MemOpChains,
4679 TailCallArguments, dl);
4683 // When passing an array of floats, the array occupies consecutive
4684 // space in the argument area; only round up to the next doubleword
4685 // at the end of the array. Otherwise, each float takes 8 bytes.
4686 if (CallConv != CallingConv::Fast || NeededLoad) {
4687 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4688 Flags.isInConsecutiveRegs()) ? 4 : 8;
4689 if (Flags.isInConsecutiveRegsLast())
4690 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4700 // These can be scalar arguments or elements of a vector array type
4701 // passed directly. The latter are used to implement ELFv2 homogenous
4702 // vector aggregates.
4704 // For a varargs call, named arguments go into VRs or on the stack as
4705 // usual; unnamed arguments always go to the stack or the corresponding
4706 // GPRs when within range. For now, we always put the value in both
4707 // locations (or even all three).
4709 // We could elide this store in the case where the object fits
4710 // entirely in R registers. Maybe later.
4711 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4712 MachinePointerInfo(), false, false, 0);
4713 MemOpChains.push_back(Store);
4714 if (VR_idx != NumVRs) {
4715 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4716 MachinePointerInfo(),
4717 false, false, false, 0);
4718 MemOpChains.push_back(Load.getValue(1));
4720 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4721 Arg.getSimpleValueType() == MVT::v2i64) ?
4722 VSRH[VR_idx] : VR[VR_idx];
4725 RegsToPass.push_back(std::make_pair(VReg, Load));
4728 for (unsigned i=0; i<16; i+=PtrByteSize) {
4729 if (GPR_idx == NumGPRs)
4731 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4732 DAG.getConstant(i, PtrVT));
4733 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4734 false, false, false, 0);
4735 MemOpChains.push_back(Load.getValue(1));
4736 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4741 // Non-varargs Altivec params go into VRs or on the stack.
4742 if (VR_idx != NumVRs) {
4743 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4744 Arg.getSimpleValueType() == MVT::v2i64) ?
4745 VSRH[VR_idx] : VR[VR_idx];
4748 RegsToPass.push_back(std::make_pair(VReg, Arg));
4750 if (CallConv == CallingConv::Fast)
4753 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4754 true, isTailCall, true, MemOpChains,
4755 TailCallArguments, dl);
4756 if (CallConv == CallingConv::Fast)
4760 if (CallConv != CallingConv::Fast)
4766 assert(NumBytesActuallyUsed == ArgOffset);
4767 (void)NumBytesActuallyUsed;
4769 if (!MemOpChains.empty())
4770 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4772 // Check if this is an indirect call (MTCTR/BCTRL).
4773 // See PrepareCall() for more information about calls through function
4774 // pointers in the 64-bit SVR4 ABI.
4775 if (!isTailCall && !IsPatchPoint &&
4776 !isFunctionGlobalAddress(Callee) &&
4777 !isa<ExternalSymbolSDNode>(Callee)) {
4778 // Load r2 into a virtual register and store it to the TOC save area.
4779 setUsesTOCBasePtr(DAG);
4780 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4781 // TOC save area offset.
4782 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4783 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4784 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4785 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
4786 MachinePointerInfo::getStack(TOCSaveOffset),
4788 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4789 // This does not mean the MTCTR instruction must use R12; it's easier
4790 // to model this as an extra parameter, so do that.
4791 if (isELFv2ABI && !IsPatchPoint)
4792 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4795 // Build a sequence of copy-to-reg nodes chained together with token chain
4796 // and flag operands which copy the outgoing args into the appropriate regs.
4798 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4799 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4800 RegsToPass[i].second, InFlag);
4801 InFlag = Chain.getValue(1);
4805 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4806 FPOp, true, TailCallArguments);
4808 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4809 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4810 NumBytes, Ins, InVals, CS);
4814 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4815 CallingConv::ID CallConv, bool isVarArg,
4816 bool isTailCall, bool IsPatchPoint,
4817 const SmallVectorImpl<ISD::OutputArg> &Outs,
4818 const SmallVectorImpl<SDValue> &OutVals,
4819 const SmallVectorImpl<ISD::InputArg> &Ins,
4820 SDLoc dl, SelectionDAG &DAG,
4821 SmallVectorImpl<SDValue> &InVals,
4822 ImmutableCallSite *CS) const {
4824 unsigned NumOps = Outs.size();
4826 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4827 bool isPPC64 = PtrVT == MVT::i64;
4828 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4830 MachineFunction &MF = DAG.getMachineFunction();
4832 // Mark this function as potentially containing a function that contains a
4833 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4834 // and restoring the callers stack pointer in this functions epilog. This is
4835 // done because by tail calling the called function might overwrite the value
4836 // in this function's (MF) stack pointer stack slot 0(SP).
4837 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4838 CallConv == CallingConv::Fast)
4839 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4841 // Count how many bytes are to be pushed on the stack, including the linkage
4842 // area, and parameter passing area. We start with 24/48 bytes, which is
4843 // prereserved space for [SP][CR][LR][3 x unused].
4844 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4846 unsigned NumBytes = LinkageSize;
4848 // Add up all the space actually used.
4849 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4850 // they all go in registers, but we must reserve stack space for them for
4851 // possible use by the caller. In varargs or 64-bit calls, parameters are
4852 // assigned stack space in order, with padding so Altivec parameters are
4854 unsigned nAltivecParamsAtEnd = 0;
4855 for (unsigned i = 0; i != NumOps; ++i) {
4856 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4857 EVT ArgVT = Outs[i].VT;
4858 // Varargs Altivec parameters are padded to a 16 byte boundary.
4859 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4860 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4861 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4862 if (!isVarArg && !isPPC64) {
4863 // Non-varargs Altivec parameters go after all the non-Altivec
4864 // parameters; handle those later so we know how much padding we need.
4865 nAltivecParamsAtEnd++;
4868 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4869 NumBytes = ((NumBytes+15)/16)*16;
4871 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4874 // Allow for Altivec parameters at the end, if needed.
4875 if (nAltivecParamsAtEnd) {
4876 NumBytes = ((NumBytes+15)/16)*16;
4877 NumBytes += 16*nAltivecParamsAtEnd;
4880 // The prolog code of the callee may store up to 8 GPR argument registers to
4881 // the stack, allowing va_start to index over them in memory if its varargs.
4882 // Because we cannot tell if this is needed on the caller side, we have to
4883 // conservatively assume that it is needed. As such, make sure we have at
4884 // least enough stack space for the caller to store the 8 GPRs.
4885 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4887 // Tail call needs the stack to be aligned.
4888 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4889 CallConv == CallingConv::Fast)
4890 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4892 // Calculate by how many bytes the stack has to be adjusted in case of tail
4893 // call optimization.
4894 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4896 // To protect arguments on the stack from being clobbered in a tail call,
4897 // force all the loads to happen before doing any other lowering.
4899 Chain = DAG.getStackArgumentTokenFactor(Chain);
4901 // Adjust the stack pointer for the new arguments...
4902 // These operations are automatically eliminated by the prolog/epilog pass
4903 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4905 SDValue CallSeqStart = Chain;
4907 // Load the return address and frame pointer so it can be move somewhere else
4910 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4913 // Set up a copy of the stack pointer for use loading and storing any
4914 // arguments that may not fit in the registers available for argument
4918 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4920 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4922 // Figure out which arguments are going to go in registers, and which in
4923 // memory. Also, if this is a vararg function, floating point operations
4924 // must be stored to our stack, and loaded into integer regs as well, if
4925 // any integer regs are available for argument passing.
4926 unsigned ArgOffset = LinkageSize;
4927 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4929 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4930 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4931 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4933 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4934 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4935 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4937 static const MCPhysReg *FPR = GetFPR();
4939 static const MCPhysReg VR[] = {
4940 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4941 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4943 const unsigned NumGPRs = array_lengthof(GPR_32);
4944 const unsigned NumFPRs = 13;
4945 const unsigned NumVRs = array_lengthof(VR);
4947 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4949 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4950 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4952 SmallVector<SDValue, 8> MemOpChains;
4953 for (unsigned i = 0; i != NumOps; ++i) {
4954 SDValue Arg = OutVals[i];
4955 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4957 // PtrOff will be used to store the current argument to the stack if a
4958 // register cannot be found for it.
4961 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4963 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4965 // On PPC64, promote integers to 64-bit values.
4966 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4967 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4968 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4969 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4972 // FIXME memcpy is used way more than necessary. Correctness first.
4973 // Note: "by value" is code for passing a structure by value, not
4975 if (Flags.isByVal()) {
4976 unsigned Size = Flags.getByValSize();
4977 // Very small objects are passed right-justified. Everything else is
4978 // passed left-justified.
4979 if (Size==1 || Size==2) {
4980 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4981 if (GPR_idx != NumGPRs) {
4982 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4983 MachinePointerInfo(), VT,
4984 false, false, false, 0);
4985 MemOpChains.push_back(Load.getValue(1));
4986 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4988 ArgOffset += PtrByteSize;
4990 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4991 PtrOff.getValueType());
4992 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4993 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4996 ArgOffset += PtrByteSize;
5000 // Copy entire object into memory. There are cases where gcc-generated
5001 // code assumes it is there, even if it could be put entirely into
5002 // registers. (This is not what the doc says.)
5003 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5007 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5008 // copy the pieces of the object that fit into registers from the
5009 // parameter save area.
5010 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5011 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5012 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5013 if (GPR_idx != NumGPRs) {
5014 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5015 MachinePointerInfo(),
5016 false, false, false, 0);
5017 MemOpChains.push_back(Load.getValue(1));
5018 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5019 ArgOffset += PtrByteSize;
5021 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5028 switch (Arg.getSimpleValueType().SimpleTy) {
5029 default: llvm_unreachable("Unexpected ValueType for argument!");
5033 if (GPR_idx != NumGPRs) {
5034 if (Arg.getValueType() == MVT::i1)
5035 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5037 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5039 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5040 isPPC64, isTailCall, false, MemOpChains,
5041 TailCallArguments, dl);
5043 ArgOffset += PtrByteSize;
5047 if (FPR_idx != NumFPRs) {
5048 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5051 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5052 MachinePointerInfo(), false, false, 0);
5053 MemOpChains.push_back(Store);
5055 // Float varargs are always shadowed in available integer registers
5056 if (GPR_idx != NumGPRs) {
5057 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5058 MachinePointerInfo(), false, false,
5060 MemOpChains.push_back(Load.getValue(1));
5061 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5063 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5064 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5065 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5066 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5067 MachinePointerInfo(),
5068 false, false, false, 0);
5069 MemOpChains.push_back(Load.getValue(1));
5070 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5073 // If we have any FPRs remaining, we may also have GPRs remaining.
5074 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5076 if (GPR_idx != NumGPRs)
5078 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5079 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5083 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5084 isPPC64, isTailCall, false, MemOpChains,
5085 TailCallArguments, dl);
5089 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5096 // These go aligned on the stack, or in the corresponding R registers
5097 // when within range. The Darwin PPC ABI doc claims they also go in
5098 // V registers; in fact gcc does this only for arguments that are
5099 // prototyped, not for those that match the ... We do it for all
5100 // arguments, seems to work.
5101 while (ArgOffset % 16 !=0) {
5102 ArgOffset += PtrByteSize;
5103 if (GPR_idx != NumGPRs)
5106 // We could elide this store in the case where the object fits
5107 // entirely in R registers. Maybe later.
5108 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5109 DAG.getConstant(ArgOffset, PtrVT));
5110 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5111 MachinePointerInfo(), false, false, 0);
5112 MemOpChains.push_back(Store);
5113 if (VR_idx != NumVRs) {
5114 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5115 MachinePointerInfo(),
5116 false, false, false, 0);
5117 MemOpChains.push_back(Load.getValue(1));
5118 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5121 for (unsigned i=0; i<16; i+=PtrByteSize) {
5122 if (GPR_idx == NumGPRs)
5124 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5125 DAG.getConstant(i, PtrVT));
5126 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5127 false, false, false, 0);
5128 MemOpChains.push_back(Load.getValue(1));
5129 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5134 // Non-varargs Altivec params generally go in registers, but have
5135 // stack space allocated at the end.
5136 if (VR_idx != NumVRs) {
5137 // Doesn't have GPR space allocated.
5138 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5139 } else if (nAltivecParamsAtEnd==0) {
5140 // We are emitting Altivec params in order.
5141 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5142 isPPC64, isTailCall, true, MemOpChains,
5143 TailCallArguments, dl);
5149 // If all Altivec parameters fit in registers, as they usually do,
5150 // they get stack space following the non-Altivec parameters. We
5151 // don't track this here because nobody below needs it.
5152 // If there are more Altivec parameters than fit in registers emit
5154 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5156 // Offset is aligned; skip 1st 12 params which go in V registers.
5157 ArgOffset = ((ArgOffset+15)/16)*16;
5159 for (unsigned i = 0; i != NumOps; ++i) {
5160 SDValue Arg = OutVals[i];
5161 EVT ArgType = Outs[i].VT;
5162 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5163 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5166 // We are emitting Altivec params in order.
5167 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5168 isPPC64, isTailCall, true, MemOpChains,
5169 TailCallArguments, dl);
5176 if (!MemOpChains.empty())
5177 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5179 // On Darwin, R12 must contain the address of an indirect callee. This does
5180 // not mean the MTCTR instruction must use R12; it's easier to model this as
5181 // an extra parameter, so do that.
5183 !isFunctionGlobalAddress(Callee) &&
5184 !isa<ExternalSymbolSDNode>(Callee) &&
5185 !isBLACompatibleAddress(Callee, DAG))
5186 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5187 PPC::R12), Callee));
5189 // Build a sequence of copy-to-reg nodes chained together with token chain
5190 // and flag operands which copy the outgoing args into the appropriate regs.
5192 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5193 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5194 RegsToPass[i].second, InFlag);
5195 InFlag = Chain.getValue(1);
5199 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5200 FPOp, true, TailCallArguments);
5202 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5203 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5204 NumBytes, Ins, InVals, CS);
5208 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5209 MachineFunction &MF, bool isVarArg,
5210 const SmallVectorImpl<ISD::OutputArg> &Outs,
5211 LLVMContext &Context) const {
5212 SmallVector<CCValAssign, 16> RVLocs;
5213 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5214 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5218 PPCTargetLowering::LowerReturn(SDValue Chain,
5219 CallingConv::ID CallConv, bool isVarArg,
5220 const SmallVectorImpl<ISD::OutputArg> &Outs,
5221 const SmallVectorImpl<SDValue> &OutVals,
5222 SDLoc dl, SelectionDAG &DAG) const {
5224 SmallVector<CCValAssign, 16> RVLocs;
5225 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5227 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5230 SmallVector<SDValue, 4> RetOps(1, Chain);
5232 // Copy the result values into the output registers.
5233 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5234 CCValAssign &VA = RVLocs[i];
5235 assert(VA.isRegLoc() && "Can only return in registers!");
5237 SDValue Arg = OutVals[i];
5239 switch (VA.getLocInfo()) {
5240 default: llvm_unreachable("Unknown loc info!");
5241 case CCValAssign::Full: break;
5242 case CCValAssign::AExt:
5243 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5245 case CCValAssign::ZExt:
5246 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5248 case CCValAssign::SExt:
5249 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5253 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5254 Flag = Chain.getValue(1);
5255 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5258 RetOps[0] = Chain; // Update chain.
5260 // Add the flag if we have it.
5262 RetOps.push_back(Flag);
5264 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5267 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5268 const PPCSubtarget &Subtarget) const {
5269 // When we pop the dynamic allocation we need to restore the SP link.
5272 // Get the corect type for pointers.
5273 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5275 // Construct the stack pointer operand.
5276 bool isPPC64 = Subtarget.isPPC64();
5277 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5278 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5280 // Get the operands for the STACKRESTORE.
5281 SDValue Chain = Op.getOperand(0);
5282 SDValue SaveSP = Op.getOperand(1);
5284 // Load the old link SP.
5285 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5286 MachinePointerInfo(),
5287 false, false, false, 0);
5289 // Restore the stack pointer.
5290 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5292 // Store the old link SP.
5293 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5300 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5301 MachineFunction &MF = DAG.getMachineFunction();
5302 bool isPPC64 = Subtarget.isPPC64();
5303 bool isDarwinABI = Subtarget.isDarwinABI();
5304 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5306 // Get current frame pointer save index. The users of this index will be
5307 // primarily DYNALLOC instructions.
5308 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5309 int RASI = FI->getReturnAddrSaveIndex();
5311 // If the frame pointer save index hasn't been defined yet.
5313 // Find out what the fix offset of the frame pointer save area.
5314 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5315 // Allocate the frame index for frame pointer save area.
5316 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5318 FI->setReturnAddrSaveIndex(RASI);
5320 return DAG.getFrameIndex(RASI, PtrVT);
5324 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5325 MachineFunction &MF = DAG.getMachineFunction();
5326 bool isPPC64 = Subtarget.isPPC64();
5327 bool isDarwinABI = Subtarget.isDarwinABI();
5328 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5330 // Get current frame pointer save index. The users of this index will be
5331 // primarily DYNALLOC instructions.
5332 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5333 int FPSI = FI->getFramePointerSaveIndex();
5335 // If the frame pointer save index hasn't been defined yet.
5337 // Find out what the fix offset of the frame pointer save area.
5338 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5341 // Allocate the frame index for frame pointer save area.
5342 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5344 FI->setFramePointerSaveIndex(FPSI);
5346 return DAG.getFrameIndex(FPSI, PtrVT);
5349 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5351 const PPCSubtarget &Subtarget) const {
5353 SDValue Chain = Op.getOperand(0);
5354 SDValue Size = Op.getOperand(1);
5357 // Get the corect type for pointers.
5358 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5360 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5361 DAG.getConstant(0, PtrVT), Size);
5362 // Construct a node for the frame pointer save index.
5363 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5364 // Build a DYNALLOC node.
5365 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5366 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5367 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5370 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5371 SelectionDAG &DAG) const {
5373 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5374 DAG.getVTList(MVT::i32, MVT::Other),
5375 Op.getOperand(0), Op.getOperand(1));
5378 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5379 SelectionDAG &DAG) const {
5381 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5382 Op.getOperand(0), Op.getOperand(1));
5385 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5386 assert(Op.getValueType() == MVT::i1 &&
5387 "Custom lowering only for i1 loads");
5389 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5392 LoadSDNode *LD = cast<LoadSDNode>(Op);
5394 SDValue Chain = LD->getChain();
5395 SDValue BasePtr = LD->getBasePtr();
5396 MachineMemOperand *MMO = LD->getMemOperand();
5398 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5399 BasePtr, MVT::i8, MMO);
5400 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5402 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5403 return DAG.getMergeValues(Ops, dl);
5406 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5407 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5408 "Custom lowering only for i1 stores");
5410 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5413 StoreSDNode *ST = cast<StoreSDNode>(Op);
5415 SDValue Chain = ST->getChain();
5416 SDValue BasePtr = ST->getBasePtr();
5417 SDValue Value = ST->getValue();
5418 MachineMemOperand *MMO = ST->getMemOperand();
5420 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5421 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5424 // FIXME: Remove this once the ANDI glue bug is fixed:
5425 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5426 assert(Op.getValueType() == MVT::i1 &&
5427 "Custom lowering only for i1 results");
5430 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5434 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5436 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5437 // Not FP? Not a fsel.
5438 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5439 !Op.getOperand(2).getValueType().isFloatingPoint())
5442 // We might be able to do better than this under some circumstances, but in
5443 // general, fsel-based lowering of select is a finite-math-only optimization.
5444 // For more information, see section F.3 of the 2.06 ISA specification.
5445 if (!DAG.getTarget().Options.NoInfsFPMath ||
5446 !DAG.getTarget().Options.NoNaNsFPMath)
5449 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5451 EVT ResVT = Op.getValueType();
5452 EVT CmpVT = Op.getOperand(0).getValueType();
5453 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5454 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5457 // If the RHS of the comparison is a 0.0, we don't need to do the
5458 // subtraction at all.
5460 if (isFloatingPointZero(RHS))
5462 default: break; // SETUO etc aren't handled by fsel.
5466 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5467 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5468 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5469 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5470 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5471 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5472 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5475 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5478 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5479 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5480 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5483 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5486 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5487 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5488 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5489 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5494 default: break; // SETUO etc aren't handled by fsel.
5498 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5499 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5500 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5501 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5502 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5503 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5504 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5505 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5508 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5509 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5510 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5511 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5514 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5515 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5516 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5517 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5520 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5521 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5522 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5523 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5526 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5527 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5528 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5529 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5534 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5537 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5538 SDValue Src = Op.getOperand(0);
5539 if (Src.getValueType() == MVT::f32)
5540 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5543 switch (Op.getSimpleValueType().SimpleTy) {
5544 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5547 Op.getOpcode() == ISD::FP_TO_SINT
5549 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5553 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5554 "i64 FP_TO_UINT is supported only with FPCVT");
5555 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5561 // Convert the FP value to an int value through memory.
5562 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5563 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5564 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5565 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5566 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5568 // Emit a store to the stack slot.
5571 MachineFunction &MF = DAG.getMachineFunction();
5572 MachineMemOperand *MMO =
5573 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5574 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5575 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5576 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5578 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5579 MPI, false, false, 0);
5581 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5583 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5584 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5585 DAG.getConstant(4, FIPtr.getValueType()));
5586 MPI = MPI.getWithOffset(4);
5594 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5597 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5599 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5600 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5604 // We're trying to insert a regular store, S, and then a load, L. If the
5605 // incoming value, O, is a load, we might just be able to have our load use the
5606 // address used by O. However, we don't know if anything else will store to
5607 // that address before we can load from it. To prevent this situation, we need
5608 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5609 // the same chain operand as O, we create a token factor from the chain results
5610 // of O and L, and we replace all uses of O's chain result with that token
5611 // factor (see spliceIntoChain below for this last part).
5612 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5615 ISD::LoadExtType ET) const {
5617 if (ET == ISD::NON_EXTLOAD &&
5618 (Op.getOpcode() == ISD::FP_TO_UINT ||
5619 Op.getOpcode() == ISD::FP_TO_SINT) &&
5620 isOperationLegalOrCustom(Op.getOpcode(),
5621 Op.getOperand(0).getValueType())) {
5623 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5627 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5628 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5629 LD->isNonTemporal())
5631 if (LD->getMemoryVT() != MemVT)
5634 RLI.Ptr = LD->getBasePtr();
5635 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5636 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5637 "Non-pre-inc AM on PPC?");
5638 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5642 RLI.Chain = LD->getChain();
5643 RLI.MPI = LD->getPointerInfo();
5644 RLI.IsInvariant = LD->isInvariant();
5645 RLI.Alignment = LD->getAlignment();
5646 RLI.AAInfo = LD->getAAInfo();
5647 RLI.Ranges = LD->getRanges();
5649 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5653 // Given the head of the old chain, ResChain, insert a token factor containing
5654 // it and NewResChain, and make users of ResChain now be users of that token
5656 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5657 SDValue NewResChain,
5658 SelectionDAG &DAG) const {
5662 SDLoc dl(NewResChain);
5664 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5665 NewResChain, DAG.getUNDEF(MVT::Other));
5666 assert(TF.getNode() != NewResChain.getNode() &&
5667 "A new TF really is required here");
5669 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5670 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5673 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5674 SelectionDAG &DAG) const {
5676 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5677 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5680 if (Op.getOperand(0).getValueType() == MVT::i1)
5681 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5682 DAG.getConstantFP(1.0, Op.getValueType()),
5683 DAG.getConstantFP(0.0, Op.getValueType()));
5685 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5686 "UINT_TO_FP is supported only with FPCVT");
5688 // If we have FCFIDS, then use it when converting to single-precision.
5689 // Otherwise, convert to double-precision and then round.
5690 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5691 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
5693 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
5695 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5699 if (Op.getOperand(0).getValueType() == MVT::i64) {
5700 SDValue SINT = Op.getOperand(0);
5701 // When converting to single-precision, we actually need to convert
5702 // to double-precision first and then round to single-precision.
5703 // To avoid double-rounding effects during that operation, we have
5704 // to prepare the input operand. Bits that might be truncated when
5705 // converting to double-precision are replaced by a bit that won't
5706 // be lost at this stage, but is below the single-precision rounding
5709 // However, if -enable-unsafe-fp-math is in effect, accept double
5710 // rounding to avoid the extra overhead.
5711 if (Op.getValueType() == MVT::f32 &&
5712 !Subtarget.hasFPCVT() &&
5713 !DAG.getTarget().Options.UnsafeFPMath) {
5715 // Twiddle input to make sure the low 11 bits are zero. (If this
5716 // is the case, we are guaranteed the value will fit into the 53 bit
5717 // mantissa of an IEEE double-precision value without rounding.)
5718 // If any of those low 11 bits were not zero originally, make sure
5719 // bit 12 (value 2048) is set instead, so that the final rounding
5720 // to single-precision gets the correct result.
5721 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5722 SINT, DAG.getConstant(2047, MVT::i64));
5723 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5724 Round, DAG.getConstant(2047, MVT::i64));
5725 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5726 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5727 Round, DAG.getConstant(-2048, MVT::i64));
5729 // However, we cannot use that value unconditionally: if the magnitude
5730 // of the input value is small, the bit-twiddling we did above might
5731 // end up visibly changing the output. Fortunately, in that case, we
5732 // don't need to twiddle bits since the original input will convert
5733 // exactly to double-precision floating-point already. Therefore,
5734 // construct a conditional to use the original value if the top 11
5735 // bits are all sign-bit copies, and use the rounded value computed
5737 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5738 SINT, DAG.getConstant(53, MVT::i32));
5739 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5740 Cond, DAG.getConstant(1, MVT::i64));
5741 Cond = DAG.getSetCC(dl, MVT::i32,
5742 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5744 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5750 MachineFunction &MF = DAG.getMachineFunction();
5751 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5752 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5753 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5755 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5756 } else if (Subtarget.hasLFIWAX() &&
5757 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5758 MachineMemOperand *MMO =
5759 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5760 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5761 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5762 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5763 DAG.getVTList(MVT::f64, MVT::Other),
5764 Ops, MVT::i32, MMO);
5765 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5766 } else if (Subtarget.hasFPCVT() &&
5767 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5768 MachineMemOperand *MMO =
5769 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5770 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5771 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5772 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5773 DAG.getVTList(MVT::f64, MVT::Other),
5774 Ops, MVT::i32, MMO);
5775 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5776 } else if (((Subtarget.hasLFIWAX() &&
5777 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5778 (Subtarget.hasFPCVT() &&
5779 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5780 SINT.getOperand(0).getValueType() == MVT::i32) {
5781 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5782 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5784 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5785 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5788 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5789 MachinePointerInfo::getFixedStack(FrameIdx),
5792 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5793 "Expected an i32 store");
5797 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5800 MachineMemOperand *MMO =
5801 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5802 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5803 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5804 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5805 PPCISD::LFIWZX : PPCISD::LFIWAX,
5806 dl, DAG.getVTList(MVT::f64, MVT::Other),
5807 Ops, MVT::i32, MMO);
5809 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5811 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5813 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5814 FP = DAG.getNode(ISD::FP_ROUND, dl,
5815 MVT::f32, FP, DAG.getIntPtrConstant(0));
5819 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5820 "Unhandled INT_TO_FP type in custom expander!");
5821 // Since we only generate this in 64-bit mode, we can take advantage of
5822 // 64-bit registers. In particular, sign extend the input value into the
5823 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5824 // then lfd it and fcfid it.
5825 MachineFunction &MF = DAG.getMachineFunction();
5826 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5827 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5830 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5833 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5835 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5836 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5838 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5839 MachinePointerInfo::getFixedStack(FrameIdx),
5842 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5843 "Expected an i32 store");
5847 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5851 MachineMemOperand *MMO =
5852 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5853 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5854 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5855 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5856 PPCISD::LFIWZX : PPCISD::LFIWAX,
5857 dl, DAG.getVTList(MVT::f64, MVT::Other),
5858 Ops, MVT::i32, MMO);
5860 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5862 assert(Subtarget.isPPC64() &&
5863 "i32->FP without LFIWAX supported only on PPC64");
5865 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5866 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5868 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5871 // STD the extended value into the stack slot.
5872 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5873 MachinePointerInfo::getFixedStack(FrameIdx),
5876 // Load the value as a double.
5877 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5878 MachinePointerInfo::getFixedStack(FrameIdx),
5879 false, false, false, 0);
5882 // FCFID it and return it.
5883 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5884 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5885 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5889 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5890 SelectionDAG &DAG) const {
5893 The rounding mode is in bits 30:31 of FPSR, and has the following
5900 FLT_ROUNDS, on the other hand, expects the following:
5907 To perform the conversion, we do:
5908 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5911 MachineFunction &MF = DAG.getMachineFunction();
5912 EVT VT = Op.getValueType();
5913 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5915 // Save FP Control Word to register
5917 MVT::f64, // return register
5918 MVT::Glue // unused in this context
5920 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5922 // Save FP register to stack slot
5923 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5924 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5925 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5926 StackSlot, MachinePointerInfo(), false, false,0);
5928 // Load FP Control Word from low 32 bits of stack slot.
5929 SDValue Four = DAG.getConstant(4, PtrVT);
5930 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5931 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5932 false, false, false, 0);
5934 // Transform as necessary
5936 DAG.getNode(ISD::AND, dl, MVT::i32,
5937 CWD, DAG.getConstant(3, MVT::i32));
5939 DAG.getNode(ISD::SRL, dl, MVT::i32,
5940 DAG.getNode(ISD::AND, dl, MVT::i32,
5941 DAG.getNode(ISD::XOR, dl, MVT::i32,
5942 CWD, DAG.getConstant(3, MVT::i32)),
5943 DAG.getConstant(3, MVT::i32)),
5944 DAG.getConstant(1, MVT::i32));
5947 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5949 return DAG.getNode((VT.getSizeInBits() < 16 ?
5950 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5953 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5954 EVT VT = Op.getValueType();
5955 unsigned BitWidth = VT.getSizeInBits();
5957 assert(Op.getNumOperands() == 3 &&
5958 VT == Op.getOperand(1).getValueType() &&
5961 // Expand into a bunch of logical ops. Note that these ops
5962 // depend on the PPC behavior for oversized shift amounts.
5963 SDValue Lo = Op.getOperand(0);
5964 SDValue Hi = Op.getOperand(1);
5965 SDValue Amt = Op.getOperand(2);
5966 EVT AmtVT = Amt.getValueType();
5968 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5969 DAG.getConstant(BitWidth, AmtVT), Amt);
5970 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5971 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5972 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5973 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5974 DAG.getConstant(-BitWidth, AmtVT));
5975 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5976 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5977 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5978 SDValue OutOps[] = { OutLo, OutHi };
5979 return DAG.getMergeValues(OutOps, dl);
5982 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5983 EVT VT = Op.getValueType();
5985 unsigned BitWidth = VT.getSizeInBits();
5986 assert(Op.getNumOperands() == 3 &&
5987 VT == Op.getOperand(1).getValueType() &&
5990 // Expand into a bunch of logical ops. Note that these ops
5991 // depend on the PPC behavior for oversized shift amounts.
5992 SDValue Lo = Op.getOperand(0);
5993 SDValue Hi = Op.getOperand(1);
5994 SDValue Amt = Op.getOperand(2);
5995 EVT AmtVT = Amt.getValueType();
5997 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5998 DAG.getConstant(BitWidth, AmtVT), Amt);
5999 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6000 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6001 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6002 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6003 DAG.getConstant(-BitWidth, AmtVT));
6004 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6005 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6006 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6007 SDValue OutOps[] = { OutLo, OutHi };
6008 return DAG.getMergeValues(OutOps, dl);
6011 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6013 EVT VT = Op.getValueType();
6014 unsigned BitWidth = VT.getSizeInBits();
6015 assert(Op.getNumOperands() == 3 &&
6016 VT == Op.getOperand(1).getValueType() &&
6019 // Expand into a bunch of logical ops, followed by a select_cc.
6020 SDValue Lo = Op.getOperand(0);
6021 SDValue Hi = Op.getOperand(1);
6022 SDValue Amt = Op.getOperand(2);
6023 EVT AmtVT = Amt.getValueType();
6025 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6026 DAG.getConstant(BitWidth, AmtVT), Amt);
6027 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6028 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6029 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6030 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6031 DAG.getConstant(-BitWidth, AmtVT));
6032 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6033 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6034 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6035 Tmp4, Tmp6, ISD::SETLE);
6036 SDValue OutOps[] = { OutLo, OutHi };
6037 return DAG.getMergeValues(OutOps, dl);
6040 //===----------------------------------------------------------------------===//
6041 // Vector related lowering.
6044 /// BuildSplatI - Build a canonical splati of Val with an element size of
6045 /// SplatSize. Cast the result to VT.
6046 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6047 SelectionDAG &DAG, SDLoc dl) {
6048 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6050 static const EVT VTys[] = { // canonical VT to use for each size.
6051 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6054 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6056 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6060 EVT CanonicalVT = VTys[SplatSize-1];
6062 // Build a canonical splat for this value.
6063 SDValue Elt = DAG.getConstant(Val, MVT::i32);
6064 SmallVector<SDValue, 8> Ops;
6065 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6066 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6067 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6070 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6071 /// specified intrinsic ID.
6072 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6073 SelectionDAG &DAG, SDLoc dl,
6074 EVT DestVT = MVT::Other) {
6075 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6076 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6077 DAG.getConstant(IID, MVT::i32), Op);
6080 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6081 /// specified intrinsic ID.
6082 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6083 SelectionDAG &DAG, SDLoc dl,
6084 EVT DestVT = MVT::Other) {
6085 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6086 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6087 DAG.getConstant(IID, MVT::i32), LHS, RHS);
6090 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6091 /// specified intrinsic ID.
6092 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6093 SDValue Op2, SelectionDAG &DAG,
6094 SDLoc dl, EVT DestVT = MVT::Other) {
6095 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6096 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6097 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6101 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6102 /// amount. The result has the specified value type.
6103 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6104 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6105 // Force LHS/RHS to be the right type.
6106 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6107 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6110 for (unsigned i = 0; i != 16; ++i)
6112 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6113 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6116 // If this is a case we can't handle, return null and let the default
6117 // expansion code take care of it. If we CAN select this case, and if it
6118 // selects to a single instruction, return Op. Otherwise, if we can codegen
6119 // this case more efficiently than a constant pool load, lower it to the
6120 // sequence of ops that should be used.
6121 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6122 SelectionDAG &DAG) const {
6124 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6125 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6127 // Check if this is a splat of a constant value.
6128 APInt APSplatBits, APSplatUndef;
6129 unsigned SplatBitSize;
6131 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6132 HasAnyUndefs, 0, true) || SplatBitSize > 32)
6135 unsigned SplatBits = APSplatBits.getZExtValue();
6136 unsigned SplatUndef = APSplatUndef.getZExtValue();
6137 unsigned SplatSize = SplatBitSize / 8;
6139 // First, handle single instruction cases.
6142 if (SplatBits == 0) {
6143 // Canonicalize all zero vectors to be v4i32.
6144 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6145 SDValue Z = DAG.getConstant(0, MVT::i32);
6146 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6147 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6152 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6153 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6155 if (SextVal >= -16 && SextVal <= 15)
6156 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6159 // Two instruction sequences.
6161 // If this value is in the range [-32,30] and is even, use:
6162 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6163 // If this value is in the range [17,31] and is odd, use:
6164 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6165 // If this value is in the range [-31,-17] and is odd, use:
6166 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6167 // Note the last two are three-instruction sequences.
6168 if (SextVal >= -32 && SextVal <= 31) {
6169 // To avoid having these optimizations undone by constant folding,
6170 // we convert to a pseudo that will be expanded later into one of
6172 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6173 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6174 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6175 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6176 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6177 if (VT == Op.getValueType())
6180 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6183 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6184 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6186 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6187 // Make -1 and vspltisw -1:
6188 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6190 // Make the VSLW intrinsic, computing 0x8000_0000.
6191 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6194 // xor by OnesV to invert it.
6195 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6196 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6199 // The remaining cases assume either big endian element order or
6200 // a splat-size that equates to the element size of the vector
6201 // to be built. An example that doesn't work for little endian is
6202 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6203 // and a vector element size of 16 bits. The code below will
6204 // produce the vector in big endian element order, which for little
6205 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6207 // For now, just avoid these optimizations in that case.
6208 // FIXME: Develop correct optimizations for LE with mismatched
6209 // splat and element sizes.
6211 if (Subtarget.isLittleEndian() &&
6212 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6215 // Check to see if this is a wide variety of vsplti*, binop self cases.
6216 static const signed char SplatCsts[] = {
6217 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6218 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6221 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6222 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6223 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6224 int i = SplatCsts[idx];
6226 // Figure out what shift amount will be used by altivec if shifted by i in
6228 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6230 // vsplti + shl self.
6231 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6232 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6233 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6234 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6235 Intrinsic::ppc_altivec_vslw
6237 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6238 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6241 // vsplti + srl self.
6242 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6243 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6244 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6245 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6246 Intrinsic::ppc_altivec_vsrw
6248 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6249 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6252 // vsplti + sra self.
6253 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6254 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6255 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6256 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6257 Intrinsic::ppc_altivec_vsraw
6259 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6260 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6263 // vsplti + rol self.
6264 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6265 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6266 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6267 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6268 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6269 Intrinsic::ppc_altivec_vrlw
6271 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6272 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6275 // t = vsplti c, result = vsldoi t, t, 1
6276 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6277 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6278 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6280 // t = vsplti c, result = vsldoi t, t, 2
6281 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6282 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6283 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6285 // t = vsplti c, result = vsldoi t, t, 3
6286 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6287 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6288 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6295 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6296 /// the specified operations to build the shuffle.
6297 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6298 SDValue RHS, SelectionDAG &DAG,
6300 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6301 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6302 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6305 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6317 if (OpNum == OP_COPY) {
6318 if (LHSID == (1*9+2)*9+3) return LHS;
6319 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6323 SDValue OpLHS, OpRHS;
6324 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6325 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6329 default: llvm_unreachable("Unknown i32 permute!");
6331 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6332 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6333 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6334 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6337 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6338 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6339 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6340 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6343 for (unsigned i = 0; i != 16; ++i)
6344 ShufIdxs[i] = (i&3)+0;
6347 for (unsigned i = 0; i != 16; ++i)
6348 ShufIdxs[i] = (i&3)+4;
6351 for (unsigned i = 0; i != 16; ++i)
6352 ShufIdxs[i] = (i&3)+8;
6355 for (unsigned i = 0; i != 16; ++i)
6356 ShufIdxs[i] = (i&3)+12;
6359 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6361 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6363 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6365 EVT VT = OpLHS.getValueType();
6366 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6367 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6368 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6369 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6372 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6373 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6374 /// return the code it can be lowered into. Worst case, it can always be
6375 /// lowered into a vperm.
6376 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6377 SelectionDAG &DAG) const {
6379 SDValue V1 = Op.getOperand(0);
6380 SDValue V2 = Op.getOperand(1);
6381 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6382 EVT VT = Op.getValueType();
6383 bool isLittleEndian = Subtarget.isLittleEndian();
6385 // Cases that are handled by instructions that take permute immediates
6386 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6387 // selected by the instruction selector.
6388 if (V2.getOpcode() == ISD::UNDEF) {
6389 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6390 PPC::isSplatShuffleMask(SVOp, 2) ||
6391 PPC::isSplatShuffleMask(SVOp, 4) ||
6392 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6393 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6394 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6395 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6396 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6397 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6398 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6399 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6400 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6405 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6406 // and produce a fixed permutation. If any of these match, do not lower to
6408 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6409 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6410 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6411 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6412 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6413 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6414 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6415 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6416 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6417 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6420 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6421 // perfect shuffle table to emit an optimal matching sequence.
6422 ArrayRef<int> PermMask = SVOp->getMask();
6424 unsigned PFIndexes[4];
6425 bool isFourElementShuffle = true;
6426 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6427 unsigned EltNo = 8; // Start out undef.
6428 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6429 if (PermMask[i*4+j] < 0)
6430 continue; // Undef, ignore it.
6432 unsigned ByteSource = PermMask[i*4+j];
6433 if ((ByteSource & 3) != j) {
6434 isFourElementShuffle = false;
6439 EltNo = ByteSource/4;
6440 } else if (EltNo != ByteSource/4) {
6441 isFourElementShuffle = false;
6445 PFIndexes[i] = EltNo;
6448 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6449 // perfect shuffle vector to determine if it is cost effective to do this as
6450 // discrete instructions, or whether we should use a vperm.
6451 // For now, we skip this for little endian until such time as we have a
6452 // little-endian perfect shuffle table.
6453 if (isFourElementShuffle && !isLittleEndian) {
6454 // Compute the index in the perfect shuffle table.
6455 unsigned PFTableIndex =
6456 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6458 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6459 unsigned Cost = (PFEntry >> 30);
6461 // Determining when to avoid vperm is tricky. Many things affect the cost
6462 // of vperm, particularly how many times the perm mask needs to be computed.
6463 // For example, if the perm mask can be hoisted out of a loop or is already
6464 // used (perhaps because there are multiple permutes with the same shuffle
6465 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6466 // the loop requires an extra register.
6468 // As a compromise, we only emit discrete instructions if the shuffle can be
6469 // generated in 3 or fewer operations. When we have loop information
6470 // available, if this block is within a loop, we should avoid using vperm
6471 // for 3-operation perms and use a constant pool load instead.
6473 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6476 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6477 // vector that will get spilled to the constant pool.
6478 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6480 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6481 // that it is in input element units, not in bytes. Convert now.
6483 // For little endian, the order of the input vectors is reversed, and
6484 // the permutation mask is complemented with respect to 31. This is
6485 // necessary to produce proper semantics with the big-endian-biased vperm
6487 EVT EltVT = V1.getValueType().getVectorElementType();
6488 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6490 SmallVector<SDValue, 16> ResultMask;
6491 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6492 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6494 for (unsigned j = 0; j != BytesPerElement; ++j)
6496 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6499 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6503 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6506 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6509 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6513 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6514 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6515 /// information about the intrinsic.
6516 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6518 unsigned IntrinsicID =
6519 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6522 switch (IntrinsicID) {
6523 default: return false;
6524 // Comparison predicates.
6525 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6526 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6527 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6528 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6529 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6530 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6531 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6532 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6533 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6534 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6535 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6536 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6537 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6539 // Normal Comparisons.
6540 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6541 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6542 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6543 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6544 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6545 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6546 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6547 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6548 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6549 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6550 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6551 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6552 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6557 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6558 /// lower, do it, otherwise return null.
6559 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6560 SelectionDAG &DAG) const {
6561 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6562 // opcode number of the comparison.
6566 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6567 return SDValue(); // Don't custom lower most intrinsics.
6569 // If this is a non-dot comparison, make the VCMP node and we are done.
6571 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6572 Op.getOperand(1), Op.getOperand(2),
6573 DAG.getConstant(CompareOpc, MVT::i32));
6574 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6577 // Create the PPCISD altivec 'dot' comparison node.
6579 Op.getOperand(2), // LHS
6580 Op.getOperand(3), // RHS
6581 DAG.getConstant(CompareOpc, MVT::i32)
6583 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6584 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6586 // Now that we have the comparison, emit a copy from the CR to a GPR.
6587 // This is flagged to the above dot comparison.
6588 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6589 DAG.getRegister(PPC::CR6, MVT::i32),
6590 CompNode.getValue(1));
6592 // Unpack the result based on how the target uses it.
6593 unsigned BitNo; // Bit # of CR6.
6594 bool InvertBit; // Invert result?
6595 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6596 default: // Can't happen, don't crash on invalid number though.
6597 case 0: // Return the value of the EQ bit of CR6.
6598 BitNo = 0; InvertBit = false;
6600 case 1: // Return the inverted value of the EQ bit of CR6.
6601 BitNo = 0; InvertBit = true;
6603 case 2: // Return the value of the LT bit of CR6.
6604 BitNo = 2; InvertBit = false;
6606 case 3: // Return the inverted value of the LT bit of CR6.
6607 BitNo = 2; InvertBit = true;
6611 // Shift the bit into the low position.
6612 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6613 DAG.getConstant(8-(3-BitNo), MVT::i32));
6615 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6616 DAG.getConstant(1, MVT::i32));
6618 // If we are supposed to, toggle the bit.
6620 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6621 DAG.getConstant(1, MVT::i32));
6625 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6626 SelectionDAG &DAG) const {
6628 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6629 // instructions), but for smaller types, we need to first extend up to v2i32
6630 // before doing going farther.
6631 if (Op.getValueType() == MVT::v2i64) {
6632 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6633 if (ExtVT != MVT::v2i32) {
6634 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6635 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6636 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6637 ExtVT.getVectorElementType(), 4)));
6638 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6639 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6640 DAG.getValueType(MVT::v2i32));
6649 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6650 SelectionDAG &DAG) const {
6652 // Create a stack slot that is 16-byte aligned.
6653 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6654 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6655 EVT PtrVT = getPointerTy();
6656 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6658 // Store the input value into Value#0 of the stack slot.
6659 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6660 Op.getOperand(0), FIdx, MachinePointerInfo(),
6663 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6664 false, false, false, 0);
6667 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6669 if (Op.getValueType() == MVT::v4i32) {
6670 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6672 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6673 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6675 SDValue RHSSwap = // = vrlw RHS, 16
6676 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6678 // Shrinkify inputs to v8i16.
6679 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6680 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6681 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6683 // Low parts multiplied together, generating 32-bit results (we ignore the
6685 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6686 LHS, RHS, DAG, dl, MVT::v4i32);
6688 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6689 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6690 // Shift the high parts up 16 bits.
6691 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6693 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6694 } else if (Op.getValueType() == MVT::v8i16) {
6695 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6697 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6699 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6700 LHS, RHS, Zero, DAG, dl);
6701 } else if (Op.getValueType() == MVT::v16i8) {
6702 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6703 bool isLittleEndian = Subtarget.isLittleEndian();
6705 // Multiply the even 8-bit parts, producing 16-bit sums.
6706 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6707 LHS, RHS, DAG, dl, MVT::v8i16);
6708 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6710 // Multiply the odd 8-bit parts, producing 16-bit sums.
6711 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6712 LHS, RHS, DAG, dl, MVT::v8i16);
6713 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6715 // Merge the results together. Because vmuleub and vmuloub are
6716 // instructions with a big-endian bias, we must reverse the
6717 // element numbering and reverse the meaning of "odd" and "even"
6718 // when generating little endian code.
6720 for (unsigned i = 0; i != 8; ++i) {
6721 if (isLittleEndian) {
6723 Ops[i*2+1] = 2*i+16;
6726 Ops[i*2+1] = 2*i+1+16;
6730 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6732 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6734 llvm_unreachable("Unknown mul to lower!");
6738 /// LowerOperation - Provide custom lowering hooks for some operations.
6740 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6741 switch (Op.getOpcode()) {
6742 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6743 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6744 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6745 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6746 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6747 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6748 case ISD::SETCC: return LowerSETCC(Op, DAG);
6749 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6750 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6752 return LowerVASTART(Op, DAG, Subtarget);
6755 return LowerVAARG(Op, DAG, Subtarget);
6758 return LowerVACOPY(Op, DAG, Subtarget);
6760 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6761 case ISD::DYNAMIC_STACKALLOC:
6762 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6764 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6765 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6767 case ISD::LOAD: return LowerLOAD(Op, DAG);
6768 case ISD::STORE: return LowerSTORE(Op, DAG);
6769 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6770 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6771 case ISD::FP_TO_UINT:
6772 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6774 case ISD::UINT_TO_FP:
6775 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6776 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6778 // Lower 64-bit shifts.
6779 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6780 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6781 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6783 // Vector-related lowering.
6784 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6785 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6786 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6787 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6788 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6789 case ISD::MUL: return LowerMUL(Op, DAG);
6791 // For counter-based loop handling.
6792 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6794 // Frame & Return address.
6795 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6796 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6800 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6801 SmallVectorImpl<SDValue>&Results,
6802 SelectionDAG &DAG) const {
6804 switch (N->getOpcode()) {
6806 llvm_unreachable("Do not know how to custom type legalize this operation!");
6807 case ISD::READCYCLECOUNTER: {
6808 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6809 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6811 Results.push_back(RTB);
6812 Results.push_back(RTB.getValue(1));
6813 Results.push_back(RTB.getValue(2));
6816 case ISD::INTRINSIC_W_CHAIN: {
6817 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6818 Intrinsic::ppc_is_decremented_ctr_nonzero)
6821 assert(N->getValueType(0) == MVT::i1 &&
6822 "Unexpected result type for CTR decrement intrinsic");
6823 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6824 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6825 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6828 Results.push_back(NewInt);
6829 Results.push_back(NewInt.getValue(1));
6833 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
6836 EVT VT = N->getValueType(0);
6838 if (VT == MVT::i64) {
6839 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6841 Results.push_back(NewNode);
6842 Results.push_back(NewNode.getValue(1));
6846 case ISD::FP_ROUND_INREG: {
6847 assert(N->getValueType(0) == MVT::ppcf128);
6848 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6849 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6850 MVT::f64, N->getOperand(0),
6851 DAG.getIntPtrConstant(0));
6852 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6853 MVT::f64, N->getOperand(0),
6854 DAG.getIntPtrConstant(1));
6856 // Add the two halves of the long double in round-to-zero mode.
6857 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6859 // We know the low half is about to be thrown away, so just use something
6861 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6865 case ISD::FP_TO_SINT:
6866 // LowerFP_TO_INT() can only handle f32 and f64.
6867 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6869 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6875 //===----------------------------------------------------------------------===//
6876 // Other Lowering Code
6877 //===----------------------------------------------------------------------===//
6879 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6880 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6881 Function *Func = Intrinsic::getDeclaration(M, Id);
6882 return Builder.CreateCall(Func);
6885 // The mappings for emitLeading/TrailingFence is taken from
6886 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6887 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6888 AtomicOrdering Ord, bool IsStore,
6889 bool IsLoad) const {
6890 if (Ord == SequentiallyConsistent)
6891 return callIntrinsic(Builder, Intrinsic::ppc_sync);
6892 else if (isAtLeastRelease(Ord))
6893 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6898 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6899 AtomicOrdering Ord, bool IsStore,
6900 bool IsLoad) const {
6901 if (IsLoad && isAtLeastAcquire(Ord))
6902 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6903 // FIXME: this is too conservative, a dependent branch + isync is enough.
6904 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6905 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6906 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6912 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6913 bool is64bit, unsigned BinOpcode) const {
6914 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6915 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6917 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6918 MachineFunction *F = BB->getParent();
6919 MachineFunction::iterator It = BB;
6922 unsigned dest = MI->getOperand(0).getReg();
6923 unsigned ptrA = MI->getOperand(1).getReg();
6924 unsigned ptrB = MI->getOperand(2).getReg();
6925 unsigned incr = MI->getOperand(3).getReg();
6926 DebugLoc dl = MI->getDebugLoc();
6928 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6929 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6930 F->insert(It, loopMBB);
6931 F->insert(It, exitMBB);
6932 exitMBB->splice(exitMBB->begin(), BB,
6933 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6934 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6936 MachineRegisterInfo &RegInfo = F->getRegInfo();
6937 unsigned TmpReg = (!BinOpcode) ? incr :
6938 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6939 : &PPC::GPRCRegClass);
6943 // fallthrough --> loopMBB
6944 BB->addSuccessor(loopMBB);
6947 // l[wd]arx dest, ptr
6948 // add r0, dest, incr
6949 // st[wd]cx. r0, ptr
6951 // fallthrough --> exitMBB
6953 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6954 .addReg(ptrA).addReg(ptrB);
6956 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6957 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6958 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6959 BuildMI(BB, dl, TII->get(PPC::BCC))
6960 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6961 BB->addSuccessor(loopMBB);
6962 BB->addSuccessor(exitMBB);
6971 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6972 MachineBasicBlock *BB,
6973 bool is8bit, // operation
6974 unsigned BinOpcode) const {
6975 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6976 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6977 // In 64 bit mode we have to use 64 bits for addresses, even though the
6978 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6979 // registers without caring whether they're 32 or 64, but here we're
6980 // doing actual arithmetic on the addresses.
6981 bool is64bit = Subtarget.isPPC64();
6982 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6984 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6985 MachineFunction *F = BB->getParent();
6986 MachineFunction::iterator It = BB;
6989 unsigned dest = MI->getOperand(0).getReg();
6990 unsigned ptrA = MI->getOperand(1).getReg();
6991 unsigned ptrB = MI->getOperand(2).getReg();
6992 unsigned incr = MI->getOperand(3).getReg();
6993 DebugLoc dl = MI->getDebugLoc();
6995 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6996 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6997 F->insert(It, loopMBB);
6998 F->insert(It, exitMBB);
6999 exitMBB->splice(exitMBB->begin(), BB,
7000 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7001 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7003 MachineRegisterInfo &RegInfo = F->getRegInfo();
7004 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7005 : &PPC::GPRCRegClass;
7006 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7007 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7008 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7009 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7010 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7011 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7012 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7013 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7014 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7015 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7016 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7018 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7022 // fallthrough --> loopMBB
7023 BB->addSuccessor(loopMBB);
7025 // The 4-byte load must be aligned, while a char or short may be
7026 // anywhere in the word. Hence all this nasty bookkeeping code.
7027 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7028 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7029 // xori shift, shift1, 24 [16]
7030 // rlwinm ptr, ptr1, 0, 0, 29
7031 // slw incr2, incr, shift
7032 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7033 // slw mask, mask2, shift
7035 // lwarx tmpDest, ptr
7036 // add tmp, tmpDest, incr2
7037 // andc tmp2, tmpDest, mask
7038 // and tmp3, tmp, mask
7039 // or tmp4, tmp3, tmp2
7042 // fallthrough --> exitMBB
7043 // srw dest, tmpDest, shift
7044 if (ptrA != ZeroReg) {
7045 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7046 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7047 .addReg(ptrA).addReg(ptrB);
7051 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7052 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7053 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7054 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7056 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7057 .addReg(Ptr1Reg).addImm(0).addImm(61);
7059 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7060 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7061 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7062 .addReg(incr).addReg(ShiftReg);
7064 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7066 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7067 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7069 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7070 .addReg(Mask2Reg).addReg(ShiftReg);
7073 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7074 .addReg(ZeroReg).addReg(PtrReg);
7076 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7077 .addReg(Incr2Reg).addReg(TmpDestReg);
7078 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7079 .addReg(TmpDestReg).addReg(MaskReg);
7080 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7081 .addReg(TmpReg).addReg(MaskReg);
7082 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7083 .addReg(Tmp3Reg).addReg(Tmp2Reg);
7084 BuildMI(BB, dl, TII->get(PPC::STWCX))
7085 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7086 BuildMI(BB, dl, TII->get(PPC::BCC))
7087 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7088 BB->addSuccessor(loopMBB);
7089 BB->addSuccessor(exitMBB);
7094 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7099 llvm::MachineBasicBlock*
7100 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7101 MachineBasicBlock *MBB) const {
7102 DebugLoc DL = MI->getDebugLoc();
7103 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7105 MachineFunction *MF = MBB->getParent();
7106 MachineRegisterInfo &MRI = MF->getRegInfo();
7108 const BasicBlock *BB = MBB->getBasicBlock();
7109 MachineFunction::iterator I = MBB;
7113 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7114 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7116 unsigned DstReg = MI->getOperand(0).getReg();
7117 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7118 assert(RC->hasType(MVT::i32) && "Invalid destination!");
7119 unsigned mainDstReg = MRI.createVirtualRegister(RC);
7120 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7122 MVT PVT = getPointerTy();
7123 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7124 "Invalid Pointer Size!");
7125 // For v = setjmp(buf), we generate
7128 // SjLjSetup mainMBB
7134 // buf[LabelOffset] = LR
7138 // v = phi(main, restore)
7141 MachineBasicBlock *thisMBB = MBB;
7142 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7143 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7144 MF->insert(I, mainMBB);
7145 MF->insert(I, sinkMBB);
7147 MachineInstrBuilder MIB;
7149 // Transfer the remainder of BB and its successor edges to sinkMBB.
7150 sinkMBB->splice(sinkMBB->begin(), MBB,
7151 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7152 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7154 // Note that the structure of the jmp_buf used here is not compatible
7155 // with that used by libc, and is not designed to be. Specifically, it
7156 // stores only those 'reserved' registers that LLVM does not otherwise
7157 // understand how to spill. Also, by convention, by the time this
7158 // intrinsic is called, Clang has already stored the frame address in the
7159 // first slot of the buffer and stack address in the third. Following the
7160 // X86 target code, we'll store the jump address in the second slot. We also
7161 // need to save the TOC pointer (R2) to handle jumps between shared
7162 // libraries, and that will be stored in the fourth slot. The thread
7163 // identifier (R13) is not affected.
7166 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7167 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7168 const int64_t BPOffset = 4 * PVT.getStoreSize();
7170 // Prepare IP either in reg.
7171 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7172 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7173 unsigned BufReg = MI->getOperand(1).getReg();
7175 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7176 setUsesTOCBasePtr(*MBB->getParent());
7177 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7181 MIB.setMemRefs(MMOBegin, MMOEnd);
7184 // Naked functions never have a base pointer, and so we use r1. For all
7185 // other functions, this decision must be delayed until during PEI.
7187 if (MF->getFunction()->getAttributes().hasAttribute(
7188 AttributeSet::FunctionIndex, Attribute::Naked))
7189 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7191 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7193 MIB = BuildMI(*thisMBB, MI, DL,
7194 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7198 MIB.setMemRefs(MMOBegin, MMOEnd);
7201 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7202 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7203 MIB.addRegMask(TRI->getNoPreservedMask());
7205 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7207 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7209 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7211 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7212 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7217 BuildMI(mainMBB, DL,
7218 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7221 if (Subtarget.isPPC64()) {
7222 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7224 .addImm(LabelOffset)
7227 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7229 .addImm(LabelOffset)
7233 MIB.setMemRefs(MMOBegin, MMOEnd);
7235 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7236 mainMBB->addSuccessor(sinkMBB);
7239 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7240 TII->get(PPC::PHI), DstReg)
7241 .addReg(mainDstReg).addMBB(mainMBB)
7242 .addReg(restoreDstReg).addMBB(thisMBB);
7244 MI->eraseFromParent();
7249 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7250 MachineBasicBlock *MBB) const {
7251 DebugLoc DL = MI->getDebugLoc();
7252 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7254 MachineFunction *MF = MBB->getParent();
7255 MachineRegisterInfo &MRI = MF->getRegInfo();
7258 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7259 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7261 MVT PVT = getPointerTy();
7262 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7263 "Invalid Pointer Size!");
7265 const TargetRegisterClass *RC =
7266 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7267 unsigned Tmp = MRI.createVirtualRegister(RC);
7268 // Since FP is only updated here but NOT referenced, it's treated as GPR.
7269 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7270 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7274 : (Subtarget.isSVR4ABI() &&
7275 MF->getTarget().getRelocationModel() == Reloc::PIC_
7279 MachineInstrBuilder MIB;
7281 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7282 const int64_t SPOffset = 2 * PVT.getStoreSize();
7283 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7284 const int64_t BPOffset = 4 * PVT.getStoreSize();
7286 unsigned BufReg = MI->getOperand(0).getReg();
7288 // Reload FP (the jumped-to function may not have had a
7289 // frame pointer, and if so, then its r31 will be restored
7291 if (PVT == MVT::i64) {
7292 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7296 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7300 MIB.setMemRefs(MMOBegin, MMOEnd);
7303 if (PVT == MVT::i64) {
7304 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7305 .addImm(LabelOffset)
7308 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7309 .addImm(LabelOffset)
7312 MIB.setMemRefs(MMOBegin, MMOEnd);
7315 if (PVT == MVT::i64) {
7316 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7320 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7324 MIB.setMemRefs(MMOBegin, MMOEnd);
7327 if (PVT == MVT::i64) {
7328 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7332 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7336 MIB.setMemRefs(MMOBegin, MMOEnd);
7339 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7340 setUsesTOCBasePtr(*MBB->getParent());
7341 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7345 MIB.setMemRefs(MMOBegin, MMOEnd);
7349 BuildMI(*MBB, MI, DL,
7350 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7351 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7353 MI->eraseFromParent();
7358 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7359 MachineBasicBlock *BB) const {
7360 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
7361 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7362 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
7363 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7364 // Call lowering should have added an r2 operand to indicate a dependence
7365 // on the TOC base pointer value. It can't however, because there is no
7366 // way to mark the dependence as implicit there, and so the stackmap code
7367 // will confuse it with a regular operand. Instead, add the dependence
7369 setUsesTOCBasePtr(*BB->getParent());
7370 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
7373 return emitPatchPoint(MI, BB);
7376 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7377 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7378 return emitEHSjLjSetJmp(MI, BB);
7379 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7380 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7381 return emitEHSjLjLongJmp(MI, BB);
7384 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7386 // To "insert" these instructions we actually have to insert their
7387 // control-flow patterns.
7388 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7389 MachineFunction::iterator It = BB;
7392 MachineFunction *F = BB->getParent();
7394 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7395 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7396 MI->getOpcode() == PPC::SELECT_I4 ||
7397 MI->getOpcode() == PPC::SELECT_I8)) {
7398 SmallVector<MachineOperand, 2> Cond;
7399 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7400 MI->getOpcode() == PPC::SELECT_CC_I8)
7401 Cond.push_back(MI->getOperand(4));
7403 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7404 Cond.push_back(MI->getOperand(1));
7406 DebugLoc dl = MI->getDebugLoc();
7407 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7408 Cond, MI->getOperand(2).getReg(),
7409 MI->getOperand(3).getReg());
7410 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7411 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7412 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7413 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7414 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7415 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7416 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7417 MI->getOpcode() == PPC::SELECT_I4 ||
7418 MI->getOpcode() == PPC::SELECT_I8 ||
7419 MI->getOpcode() == PPC::SELECT_F4 ||
7420 MI->getOpcode() == PPC::SELECT_F8 ||
7421 MI->getOpcode() == PPC::SELECT_VRRC ||
7422 MI->getOpcode() == PPC::SELECT_VSFRC ||
7423 MI->getOpcode() == PPC::SELECT_VSRC) {
7424 // The incoming instruction knows the destination vreg to set, the
7425 // condition code register to branch on, the true/false values to
7426 // select between, and a branch opcode to use.
7431 // cmpTY ccX, r1, r2
7433 // fallthrough --> copy0MBB
7434 MachineBasicBlock *thisMBB = BB;
7435 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7436 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7437 DebugLoc dl = MI->getDebugLoc();
7438 F->insert(It, copy0MBB);
7439 F->insert(It, sinkMBB);
7441 // Transfer the remainder of BB and its successor edges to sinkMBB.
7442 sinkMBB->splice(sinkMBB->begin(), BB,
7443 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7444 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7446 // Next, add the true and fallthrough blocks as its successors.
7447 BB->addSuccessor(copy0MBB);
7448 BB->addSuccessor(sinkMBB);
7450 if (MI->getOpcode() == PPC::SELECT_I4 ||
7451 MI->getOpcode() == PPC::SELECT_I8 ||
7452 MI->getOpcode() == PPC::SELECT_F4 ||
7453 MI->getOpcode() == PPC::SELECT_F8 ||
7454 MI->getOpcode() == PPC::SELECT_VRRC ||
7455 MI->getOpcode() == PPC::SELECT_VSFRC ||
7456 MI->getOpcode() == PPC::SELECT_VSRC) {
7457 BuildMI(BB, dl, TII->get(PPC::BC))
7458 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7460 unsigned SelectPred = MI->getOperand(4).getImm();
7461 BuildMI(BB, dl, TII->get(PPC::BCC))
7462 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7466 // %FalseValue = ...
7467 // # fallthrough to sinkMBB
7470 // Update machine-CFG edges
7471 BB->addSuccessor(sinkMBB);
7474 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7477 BuildMI(*BB, BB->begin(), dl,
7478 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7479 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7480 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7481 } else if (MI->getOpcode() == PPC::ReadTB) {
7482 // To read the 64-bit time-base register on a 32-bit target, we read the
7483 // two halves. Should the counter have wrapped while it was being read, we
7484 // need to try again.
7487 // mfspr Rx,TBU # load from TBU
7488 // mfspr Ry,TB # load from TB
7489 // mfspr Rz,TBU # load from TBU
7490 // cmpw crX,Rx,Rz # check if ‘old’=’new’
7491 // bne readLoop # branch if they're not equal
7494 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7495 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7496 DebugLoc dl = MI->getDebugLoc();
7497 F->insert(It, readMBB);
7498 F->insert(It, sinkMBB);
7500 // Transfer the remainder of BB and its successor edges to sinkMBB.
7501 sinkMBB->splice(sinkMBB->begin(), BB,
7502 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7503 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7505 BB->addSuccessor(readMBB);
7508 MachineRegisterInfo &RegInfo = F->getRegInfo();
7509 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7510 unsigned LoReg = MI->getOperand(0).getReg();
7511 unsigned HiReg = MI->getOperand(1).getReg();
7513 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7514 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7515 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7517 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7519 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7520 .addReg(HiReg).addReg(ReadAgainReg);
7521 BuildMI(BB, dl, TII->get(PPC::BCC))
7522 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7524 BB->addSuccessor(readMBB);
7525 BB->addSuccessor(sinkMBB);
7527 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7528 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7529 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7530 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7531 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7532 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7533 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7534 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7536 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7537 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7538 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7539 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7540 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7541 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7542 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7543 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7545 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7546 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7547 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7548 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7549 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7550 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7551 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7552 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7554 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7555 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7556 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7557 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7558 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7559 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7560 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7561 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7563 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7564 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7565 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7566 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7567 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7568 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7569 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7570 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7572 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7573 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7574 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7575 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7576 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7577 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7578 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7579 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7581 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7582 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7583 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7584 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7585 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7586 BB = EmitAtomicBinary(MI, BB, false, 0);
7587 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7588 BB = EmitAtomicBinary(MI, BB, true, 0);
7590 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7591 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7592 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7594 unsigned dest = MI->getOperand(0).getReg();
7595 unsigned ptrA = MI->getOperand(1).getReg();
7596 unsigned ptrB = MI->getOperand(2).getReg();
7597 unsigned oldval = MI->getOperand(3).getReg();
7598 unsigned newval = MI->getOperand(4).getReg();
7599 DebugLoc dl = MI->getDebugLoc();
7601 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7602 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7603 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7604 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7605 F->insert(It, loop1MBB);
7606 F->insert(It, loop2MBB);
7607 F->insert(It, midMBB);
7608 F->insert(It, exitMBB);
7609 exitMBB->splice(exitMBB->begin(), BB,
7610 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7611 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7615 // fallthrough --> loopMBB
7616 BB->addSuccessor(loop1MBB);
7619 // l[wd]arx dest, ptr
7620 // cmp[wd] dest, oldval
7623 // st[wd]cx. newval, ptr
7627 // st[wd]cx. dest, ptr
7630 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7631 .addReg(ptrA).addReg(ptrB);
7632 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7633 .addReg(oldval).addReg(dest);
7634 BuildMI(BB, dl, TII->get(PPC::BCC))
7635 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7636 BB->addSuccessor(loop2MBB);
7637 BB->addSuccessor(midMBB);
7640 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7641 .addReg(newval).addReg(ptrA).addReg(ptrB);
7642 BuildMI(BB, dl, TII->get(PPC::BCC))
7643 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7644 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7645 BB->addSuccessor(loop1MBB);
7646 BB->addSuccessor(exitMBB);
7649 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7650 .addReg(dest).addReg(ptrA).addReg(ptrB);
7651 BB->addSuccessor(exitMBB);
7656 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7657 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7658 // We must use 64-bit registers for addresses when targeting 64-bit,
7659 // since we're actually doing arithmetic on them. Other registers
7661 bool is64bit = Subtarget.isPPC64();
7662 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7664 unsigned dest = MI->getOperand(0).getReg();
7665 unsigned ptrA = MI->getOperand(1).getReg();
7666 unsigned ptrB = MI->getOperand(2).getReg();
7667 unsigned oldval = MI->getOperand(3).getReg();
7668 unsigned newval = MI->getOperand(4).getReg();
7669 DebugLoc dl = MI->getDebugLoc();
7671 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7672 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7673 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7674 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7675 F->insert(It, loop1MBB);
7676 F->insert(It, loop2MBB);
7677 F->insert(It, midMBB);
7678 F->insert(It, exitMBB);
7679 exitMBB->splice(exitMBB->begin(), BB,
7680 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7681 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7683 MachineRegisterInfo &RegInfo = F->getRegInfo();
7684 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7685 : &PPC::GPRCRegClass;
7686 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7687 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7688 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7689 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7690 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7691 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7692 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7693 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7694 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7695 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7696 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7697 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7698 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7700 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7701 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7704 // fallthrough --> loopMBB
7705 BB->addSuccessor(loop1MBB);
7707 // The 4-byte load must be aligned, while a char or short may be
7708 // anywhere in the word. Hence all this nasty bookkeeping code.
7709 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7710 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7711 // xori shift, shift1, 24 [16]
7712 // rlwinm ptr, ptr1, 0, 0, 29
7713 // slw newval2, newval, shift
7714 // slw oldval2, oldval,shift
7715 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7716 // slw mask, mask2, shift
7717 // and newval3, newval2, mask
7718 // and oldval3, oldval2, mask
7720 // lwarx tmpDest, ptr
7721 // and tmp, tmpDest, mask
7722 // cmpw tmp, oldval3
7725 // andc tmp2, tmpDest, mask
7726 // or tmp4, tmp2, newval3
7731 // stwcx. tmpDest, ptr
7733 // srw dest, tmpDest, shift
7734 if (ptrA != ZeroReg) {
7735 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7736 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7737 .addReg(ptrA).addReg(ptrB);
7741 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7742 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7743 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7744 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7746 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7747 .addReg(Ptr1Reg).addImm(0).addImm(61);
7749 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7750 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7751 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7752 .addReg(newval).addReg(ShiftReg);
7753 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7754 .addReg(oldval).addReg(ShiftReg);
7756 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7758 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7759 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7760 .addReg(Mask3Reg).addImm(65535);
7762 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7763 .addReg(Mask2Reg).addReg(ShiftReg);
7764 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7765 .addReg(NewVal2Reg).addReg(MaskReg);
7766 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7767 .addReg(OldVal2Reg).addReg(MaskReg);
7770 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7771 .addReg(ZeroReg).addReg(PtrReg);
7772 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7773 .addReg(TmpDestReg).addReg(MaskReg);
7774 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7775 .addReg(TmpReg).addReg(OldVal3Reg);
7776 BuildMI(BB, dl, TII->get(PPC::BCC))
7777 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7778 BB->addSuccessor(loop2MBB);
7779 BB->addSuccessor(midMBB);
7782 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7783 .addReg(TmpDestReg).addReg(MaskReg);
7784 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7785 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7786 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7787 .addReg(ZeroReg).addReg(PtrReg);
7788 BuildMI(BB, dl, TII->get(PPC::BCC))
7789 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7790 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7791 BB->addSuccessor(loop1MBB);
7792 BB->addSuccessor(exitMBB);
7795 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7796 .addReg(ZeroReg).addReg(PtrReg);
7797 BB->addSuccessor(exitMBB);
7802 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7804 } else if (MI->getOpcode() == PPC::FADDrtz) {
7805 // This pseudo performs an FADD with rounding mode temporarily forced
7806 // to round-to-zero. We emit this via custom inserter since the FPSCR
7807 // is not modeled at the SelectionDAG level.
7808 unsigned Dest = MI->getOperand(0).getReg();
7809 unsigned Src1 = MI->getOperand(1).getReg();
7810 unsigned Src2 = MI->getOperand(2).getReg();
7811 DebugLoc dl = MI->getDebugLoc();
7813 MachineRegisterInfo &RegInfo = F->getRegInfo();
7814 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7816 // Save FPSCR value.
7817 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7819 // Set rounding mode to round-to-zero.
7820 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7821 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7823 // Perform addition.
7824 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7826 // Restore FPSCR value.
7827 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
7828 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7829 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7830 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7831 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7832 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7833 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7834 PPC::ANDIo8 : PPC::ANDIo;
7835 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7836 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7838 MachineRegisterInfo &RegInfo = F->getRegInfo();
7839 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7840 &PPC::GPRCRegClass :
7841 &PPC::G8RCRegClass);
7843 DebugLoc dl = MI->getDebugLoc();
7844 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7845 .addReg(MI->getOperand(1).getReg()).addImm(1);
7846 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7847 MI->getOperand(0).getReg())
7848 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7850 llvm_unreachable("Unexpected instr type to insert");
7853 MI->eraseFromParent(); // The pseudo instruction is gone now.
7857 //===----------------------------------------------------------------------===//
7858 // Target Optimization Hooks
7859 //===----------------------------------------------------------------------===//
7861 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7862 DAGCombinerInfo &DCI,
7863 unsigned &RefinementSteps,
7864 bool &UseOneConstNR) const {
7865 EVT VT = Operand.getValueType();
7866 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7867 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7868 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7869 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7870 // Convergence is quadratic, so we essentially double the number of digits
7871 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7872 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7873 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7874 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7875 if (VT.getScalarType() == MVT::f64)
7877 UseOneConstNR = true;
7878 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7883 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7884 DAGCombinerInfo &DCI,
7885 unsigned &RefinementSteps) const {
7886 EVT VT = Operand.getValueType();
7887 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7888 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7889 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7890 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7891 // Convergence is quadratic, so we essentially double the number of digits
7892 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7893 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7894 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7895 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7896 if (VT.getScalarType() == MVT::f64)
7898 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7903 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7904 // Note: This functionality is used only when unsafe-fp-math is enabled, and
7905 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7906 // enabled for division), this functionality is redundant with the default
7907 // combiner logic (once the division -> reciprocal/multiply transformation
7908 // has taken place). As a result, this matters more for older cores than for
7911 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7912 // reciprocal if there are two or more FDIVs (for embedded cores with only
7913 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7914 switch (Subtarget.getDarwinDirective()) {
7916 return NumUsers > 2;
7919 case PPC::DIR_E500mc:
7920 case PPC::DIR_E5500:
7921 return NumUsers > 1;
7925 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7926 unsigned Bytes, int Dist,
7927 SelectionDAG &DAG) {
7928 if (VT.getSizeInBits() / 8 != Bytes)
7931 SDValue BaseLoc = Base->getBasePtr();
7932 if (Loc.getOpcode() == ISD::FrameIndex) {
7933 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7935 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7936 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7937 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7938 int FS = MFI->getObjectSize(FI);
7939 int BFS = MFI->getObjectSize(BFI);
7940 if (FS != BFS || FS != (int)Bytes) return false;
7941 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7945 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7946 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7950 const GlobalValue *GV1 = nullptr;
7951 const GlobalValue *GV2 = nullptr;
7952 int64_t Offset1 = 0;
7953 int64_t Offset2 = 0;
7954 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7955 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7956 if (isGA1 && isGA2 && GV1 == GV2)
7957 return Offset1 == (Offset2 + Dist*Bytes);
7961 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7962 // not enforce equality of the chain operands.
7963 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7964 unsigned Bytes, int Dist,
7965 SelectionDAG &DAG) {
7966 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7967 EVT VT = LS->getMemoryVT();
7968 SDValue Loc = LS->getBasePtr();
7969 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7972 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7974 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7975 default: return false;
7976 case Intrinsic::ppc_altivec_lvx:
7977 case Intrinsic::ppc_altivec_lvxl:
7978 case Intrinsic::ppc_vsx_lxvw4x:
7981 case Intrinsic::ppc_vsx_lxvd2x:
7984 case Intrinsic::ppc_altivec_lvebx:
7987 case Intrinsic::ppc_altivec_lvehx:
7990 case Intrinsic::ppc_altivec_lvewx:
7995 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7998 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8000 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8001 default: return false;
8002 case Intrinsic::ppc_altivec_stvx:
8003 case Intrinsic::ppc_altivec_stvxl:
8004 case Intrinsic::ppc_vsx_stxvw4x:
8007 case Intrinsic::ppc_vsx_stxvd2x:
8010 case Intrinsic::ppc_altivec_stvebx:
8013 case Intrinsic::ppc_altivec_stvehx:
8016 case Intrinsic::ppc_altivec_stvewx:
8021 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8027 // Return true is there is a nearyby consecutive load to the one provided
8028 // (regardless of alignment). We search up and down the chain, looking though
8029 // token factors and other loads (but nothing else). As a result, a true result
8030 // indicates that it is safe to create a new consecutive load adjacent to the
8032 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8033 SDValue Chain = LD->getChain();
8034 EVT VT = LD->getMemoryVT();
8036 SmallSet<SDNode *, 16> LoadRoots;
8037 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8038 SmallSet<SDNode *, 16> Visited;
8040 // First, search up the chain, branching to follow all token-factor operands.
8041 // If we find a consecutive load, then we're done, otherwise, record all
8042 // nodes just above the top-level loads and token factors.
8043 while (!Queue.empty()) {
8044 SDNode *ChainNext = Queue.pop_back_val();
8045 if (!Visited.insert(ChainNext).second)
8048 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8049 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8052 if (!Visited.count(ChainLD->getChain().getNode()))
8053 Queue.push_back(ChainLD->getChain().getNode());
8054 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8055 for (const SDUse &O : ChainNext->ops())
8056 if (!Visited.count(O.getNode()))
8057 Queue.push_back(O.getNode());
8059 LoadRoots.insert(ChainNext);
8062 // Second, search down the chain, starting from the top-level nodes recorded
8063 // in the first phase. These top-level nodes are the nodes just above all
8064 // loads and token factors. Starting with their uses, recursively look though
8065 // all loads (just the chain uses) and token factors to find a consecutive
8070 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8071 IE = LoadRoots.end(); I != IE; ++I) {
8072 Queue.push_back(*I);
8074 while (!Queue.empty()) {
8075 SDNode *LoadRoot = Queue.pop_back_val();
8076 if (!Visited.insert(LoadRoot).second)
8079 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8080 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8083 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8084 UE = LoadRoot->use_end(); UI != UE; ++UI)
8085 if (((isa<MemSDNode>(*UI) &&
8086 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8087 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8088 Queue.push_back(*UI);
8095 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8096 DAGCombinerInfo &DCI) const {
8097 SelectionDAG &DAG = DCI.DAG;
8100 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8101 // If we're tracking CR bits, we need to be careful that we don't have:
8102 // trunc(binary-ops(zext(x), zext(y)))
8104 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8105 // such that we're unnecessarily moving things into GPRs when it would be
8106 // better to keep them in CR bits.
8108 // Note that trunc here can be an actual i1 trunc, or can be the effective
8109 // truncation that comes from a setcc or select_cc.
8110 if (N->getOpcode() == ISD::TRUNCATE &&
8111 N->getValueType(0) != MVT::i1)
8114 if (N->getOperand(0).getValueType() != MVT::i32 &&
8115 N->getOperand(0).getValueType() != MVT::i64)
8118 if (N->getOpcode() == ISD::SETCC ||
8119 N->getOpcode() == ISD::SELECT_CC) {
8120 // If we're looking at a comparison, then we need to make sure that the
8121 // high bits (all except for the first) don't matter the result.
8123 cast<CondCodeSDNode>(N->getOperand(
8124 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8125 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8127 if (ISD::isSignedIntSetCC(CC)) {
8128 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
8129 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
8131 } else if (ISD::isUnsignedIntSetCC(CC)) {
8132 if (!DAG.MaskedValueIsZero(N->getOperand(0),
8133 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
8134 !DAG.MaskedValueIsZero(N->getOperand(1),
8135 APInt::getHighBitsSet(OpBits, OpBits-1)))
8138 // This is neither a signed nor an unsigned comparison, just make sure
8139 // that the high bits are equal.
8140 APInt Op1Zero, Op1One;
8141 APInt Op2Zero, Op2One;
8142 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8143 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8145 // We don't really care about what is known about the first bit (if
8146 // anything), so clear it in all masks prior to comparing them.
8147 Op1Zero.clearBit(0); Op1One.clearBit(0);
8148 Op2Zero.clearBit(0); Op2One.clearBit(0);
8150 if (Op1Zero != Op2Zero || Op1One != Op2One)
8155 // We now know that the higher-order bits are irrelevant, we just need to
8156 // make sure that all of the intermediate operations are bit operations, and
8157 // all inputs are extensions.
8158 if (N->getOperand(0).getOpcode() != ISD::AND &&
8159 N->getOperand(0).getOpcode() != ISD::OR &&
8160 N->getOperand(0).getOpcode() != ISD::XOR &&
8161 N->getOperand(0).getOpcode() != ISD::SELECT &&
8162 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8163 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8164 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8165 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8166 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8169 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8170 N->getOperand(1).getOpcode() != ISD::AND &&
8171 N->getOperand(1).getOpcode() != ISD::OR &&
8172 N->getOperand(1).getOpcode() != ISD::XOR &&
8173 N->getOperand(1).getOpcode() != ISD::SELECT &&
8174 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8175 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8176 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8177 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8178 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8181 SmallVector<SDValue, 4> Inputs;
8182 SmallVector<SDValue, 8> BinOps, PromOps;
8183 SmallPtrSet<SDNode *, 16> Visited;
8185 for (unsigned i = 0; i < 2; ++i) {
8186 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8187 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8188 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8189 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8190 isa<ConstantSDNode>(N->getOperand(i)))
8191 Inputs.push_back(N->getOperand(i));
8193 BinOps.push_back(N->getOperand(i));
8195 if (N->getOpcode() == ISD::TRUNCATE)
8199 // Visit all inputs, collect all binary operations (and, or, xor and
8200 // select) that are all fed by extensions.
8201 while (!BinOps.empty()) {
8202 SDValue BinOp = BinOps.back();
8205 if (!Visited.insert(BinOp.getNode()).second)
8208 PromOps.push_back(BinOp);
8210 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8211 // The condition of the select is not promoted.
8212 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8214 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8217 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8218 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8219 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8220 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8221 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8222 Inputs.push_back(BinOp.getOperand(i));
8223 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8224 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8225 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8226 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8227 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8228 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8229 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8230 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8231 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8232 BinOps.push_back(BinOp.getOperand(i));
8234 // We have an input that is not an extension or another binary
8235 // operation; we'll abort this transformation.
8241 // Make sure that this is a self-contained cluster of operations (which
8242 // is not quite the same thing as saying that everything has only one
8244 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8245 if (isa<ConstantSDNode>(Inputs[i]))
8248 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8249 UE = Inputs[i].getNode()->use_end();
8252 if (User != N && !Visited.count(User))
8255 // Make sure that we're not going to promote the non-output-value
8256 // operand(s) or SELECT or SELECT_CC.
8257 // FIXME: Although we could sometimes handle this, and it does occur in
8258 // practice that one of the condition inputs to the select is also one of
8259 // the outputs, we currently can't deal with this.
8260 if (User->getOpcode() == ISD::SELECT) {
8261 if (User->getOperand(0) == Inputs[i])
8263 } else if (User->getOpcode() == ISD::SELECT_CC) {
8264 if (User->getOperand(0) == Inputs[i] ||
8265 User->getOperand(1) == Inputs[i])
8271 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8272 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8273 UE = PromOps[i].getNode()->use_end();
8276 if (User != N && !Visited.count(User))
8279 // Make sure that we're not going to promote the non-output-value
8280 // operand(s) or SELECT or SELECT_CC.
8281 // FIXME: Although we could sometimes handle this, and it does occur in
8282 // practice that one of the condition inputs to the select is also one of
8283 // the outputs, we currently can't deal with this.
8284 if (User->getOpcode() == ISD::SELECT) {
8285 if (User->getOperand(0) == PromOps[i])
8287 } else if (User->getOpcode() == ISD::SELECT_CC) {
8288 if (User->getOperand(0) == PromOps[i] ||
8289 User->getOperand(1) == PromOps[i])
8295 // Replace all inputs with the extension operand.
8296 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8297 // Constants may have users outside the cluster of to-be-promoted nodes,
8298 // and so we need to replace those as we do the promotions.
8299 if (isa<ConstantSDNode>(Inputs[i]))
8302 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
8305 // Replace all operations (these are all the same, but have a different
8306 // (i1) return type). DAG.getNode will validate that the types of
8307 // a binary operator match, so go through the list in reverse so that
8308 // we've likely promoted both operands first. Any intermediate truncations or
8309 // extensions disappear.
8310 while (!PromOps.empty()) {
8311 SDValue PromOp = PromOps.back();
8314 if (PromOp.getOpcode() == ISD::TRUNCATE ||
8315 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8316 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8317 PromOp.getOpcode() == ISD::ANY_EXTEND) {
8318 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8319 PromOp.getOperand(0).getValueType() != MVT::i1) {
8320 // The operand is not yet ready (see comment below).
8321 PromOps.insert(PromOps.begin(), PromOp);
8325 SDValue RepValue = PromOp.getOperand(0);
8326 if (isa<ConstantSDNode>(RepValue))
8327 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8329 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8334 switch (PromOp.getOpcode()) {
8335 default: C = 0; break;
8336 case ISD::SELECT: C = 1; break;
8337 case ISD::SELECT_CC: C = 2; break;
8340 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8341 PromOp.getOperand(C).getValueType() != MVT::i1) ||
8342 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8343 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8344 // The to-be-promoted operands of this node have not yet been
8345 // promoted (this should be rare because we're going through the
8346 // list backward, but if one of the operands has several users in
8347 // this cluster of to-be-promoted nodes, it is possible).
8348 PromOps.insert(PromOps.begin(), PromOp);
8352 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8353 PromOp.getNode()->op_end());
8355 // If there are any constant inputs, make sure they're replaced now.
8356 for (unsigned i = 0; i < 2; ++i)
8357 if (isa<ConstantSDNode>(Ops[C+i]))
8358 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8360 DAG.ReplaceAllUsesOfValueWith(PromOp,
8361 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8364 // Now we're left with the initial truncation itself.
8365 if (N->getOpcode() == ISD::TRUNCATE)
8366 return N->getOperand(0);
8368 // Otherwise, this is a comparison. The operands to be compared have just
8369 // changed type (to i1), but everything else is the same.
8370 return SDValue(N, 0);
8373 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8374 DAGCombinerInfo &DCI) const {
8375 SelectionDAG &DAG = DCI.DAG;
8378 // If we're tracking CR bits, we need to be careful that we don't have:
8379 // zext(binary-ops(trunc(x), trunc(y)))
8381 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8382 // such that we're unnecessarily moving things into CR bits that can more
8383 // efficiently stay in GPRs. Note that if we're not certain that the high
8384 // bits are set as required by the final extension, we still may need to do
8385 // some masking to get the proper behavior.
8387 // This same functionality is important on PPC64 when dealing with
8388 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8389 // the return values of functions. Because it is so similar, it is handled
8392 if (N->getValueType(0) != MVT::i32 &&
8393 N->getValueType(0) != MVT::i64)
8396 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
8397 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
8400 if (N->getOperand(0).getOpcode() != ISD::AND &&
8401 N->getOperand(0).getOpcode() != ISD::OR &&
8402 N->getOperand(0).getOpcode() != ISD::XOR &&
8403 N->getOperand(0).getOpcode() != ISD::SELECT &&
8404 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8407 SmallVector<SDValue, 4> Inputs;
8408 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8409 SmallPtrSet<SDNode *, 16> Visited;
8411 // Visit all inputs, collect all binary operations (and, or, xor and
8412 // select) that are all fed by truncations.
8413 while (!BinOps.empty()) {
8414 SDValue BinOp = BinOps.back();
8417 if (!Visited.insert(BinOp.getNode()).second)
8420 PromOps.push_back(BinOp);
8422 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8423 // The condition of the select is not promoted.
8424 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8426 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8429 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8430 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8431 Inputs.push_back(BinOp.getOperand(i));
8432 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8433 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8434 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8435 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8436 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8437 BinOps.push_back(BinOp.getOperand(i));
8439 // We have an input that is not a truncation or another binary
8440 // operation; we'll abort this transformation.
8446 // The operands of a select that must be truncated when the select is
8447 // promoted because the operand is actually part of the to-be-promoted set.
8448 DenseMap<SDNode *, EVT> SelectTruncOp[2];
8450 // Make sure that this is a self-contained cluster of operations (which
8451 // is not quite the same thing as saying that everything has only one
8453 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8454 if (isa<ConstantSDNode>(Inputs[i]))
8457 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8458 UE = Inputs[i].getNode()->use_end();
8461 if (User != N && !Visited.count(User))
8464 // If we're going to promote the non-output-value operand(s) or SELECT or
8465 // SELECT_CC, record them for truncation.
8466 if (User->getOpcode() == ISD::SELECT) {
8467 if (User->getOperand(0) == Inputs[i])
8468 SelectTruncOp[0].insert(std::make_pair(User,
8469 User->getOperand(0).getValueType()));
8470 } else if (User->getOpcode() == ISD::SELECT_CC) {
8471 if (User->getOperand(0) == Inputs[i])
8472 SelectTruncOp[0].insert(std::make_pair(User,
8473 User->getOperand(0).getValueType()));
8474 if (User->getOperand(1) == Inputs[i])
8475 SelectTruncOp[1].insert(std::make_pair(User,
8476 User->getOperand(1).getValueType()));
8481 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8482 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8483 UE = PromOps[i].getNode()->use_end();
8486 if (User != N && !Visited.count(User))
8489 // If we're going to promote the non-output-value operand(s) or SELECT or
8490 // SELECT_CC, record them for truncation.
8491 if (User->getOpcode() == ISD::SELECT) {
8492 if (User->getOperand(0) == PromOps[i])
8493 SelectTruncOp[0].insert(std::make_pair(User,
8494 User->getOperand(0).getValueType()));
8495 } else if (User->getOpcode() == ISD::SELECT_CC) {
8496 if (User->getOperand(0) == PromOps[i])
8497 SelectTruncOp[0].insert(std::make_pair(User,
8498 User->getOperand(0).getValueType()));
8499 if (User->getOperand(1) == PromOps[i])
8500 SelectTruncOp[1].insert(std::make_pair(User,
8501 User->getOperand(1).getValueType()));
8506 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8507 bool ReallyNeedsExt = false;
8508 if (N->getOpcode() != ISD::ANY_EXTEND) {
8509 // If all of the inputs are not already sign/zero extended, then
8510 // we'll still need to do that at the end.
8511 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8512 if (isa<ConstantSDNode>(Inputs[i]))
8516 Inputs[i].getOperand(0).getValueSizeInBits();
8517 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8519 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8520 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8521 APInt::getHighBitsSet(OpBits,
8522 OpBits-PromBits))) ||
8523 (N->getOpcode() == ISD::SIGN_EXTEND &&
8524 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8525 (OpBits-(PromBits-1)))) {
8526 ReallyNeedsExt = true;
8532 // Replace all inputs, either with the truncation operand, or a
8533 // truncation or extension to the final output type.
8534 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8535 // Constant inputs need to be replaced with the to-be-promoted nodes that
8536 // use them because they might have users outside of the cluster of
8538 if (isa<ConstantSDNode>(Inputs[i]))
8541 SDValue InSrc = Inputs[i].getOperand(0);
8542 if (Inputs[i].getValueType() == N->getValueType(0))
8543 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8544 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8545 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8546 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8547 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8548 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8549 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8551 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8552 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8555 // Replace all operations (these are all the same, but have a different
8556 // (promoted) return type). DAG.getNode will validate that the types of
8557 // a binary operator match, so go through the list in reverse so that
8558 // we've likely promoted both operands first.
8559 while (!PromOps.empty()) {
8560 SDValue PromOp = PromOps.back();
8564 switch (PromOp.getOpcode()) {
8565 default: C = 0; break;
8566 case ISD::SELECT: C = 1; break;
8567 case ISD::SELECT_CC: C = 2; break;
8570 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8571 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8572 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8573 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8574 // The to-be-promoted operands of this node have not yet been
8575 // promoted (this should be rare because we're going through the
8576 // list backward, but if one of the operands has several users in
8577 // this cluster of to-be-promoted nodes, it is possible).
8578 PromOps.insert(PromOps.begin(), PromOp);
8582 // For SELECT and SELECT_CC nodes, we do a similar check for any
8583 // to-be-promoted comparison inputs.
8584 if (PromOp.getOpcode() == ISD::SELECT ||
8585 PromOp.getOpcode() == ISD::SELECT_CC) {
8586 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8587 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8588 (SelectTruncOp[1].count(PromOp.getNode()) &&
8589 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8590 PromOps.insert(PromOps.begin(), PromOp);
8595 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8596 PromOp.getNode()->op_end());
8598 // If this node has constant inputs, then they'll need to be promoted here.
8599 for (unsigned i = 0; i < 2; ++i) {
8600 if (!isa<ConstantSDNode>(Ops[C+i]))
8602 if (Ops[C+i].getValueType() == N->getValueType(0))
8605 if (N->getOpcode() == ISD::SIGN_EXTEND)
8606 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8607 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8608 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8610 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8613 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8614 // truncate them again to the original value type.
8615 if (PromOp.getOpcode() == ISD::SELECT ||
8616 PromOp.getOpcode() == ISD::SELECT_CC) {
8617 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8618 if (SI0 != SelectTruncOp[0].end())
8619 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8620 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8621 if (SI1 != SelectTruncOp[1].end())
8622 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8625 DAG.ReplaceAllUsesOfValueWith(PromOp,
8626 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8629 // Now we're left with the initial extension itself.
8630 if (!ReallyNeedsExt)
8631 return N->getOperand(0);
8633 // To zero extend, just mask off everything except for the first bit (in the
8635 if (N->getOpcode() == ISD::ZERO_EXTEND)
8636 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8637 DAG.getConstant(APInt::getLowBitsSet(
8638 N->getValueSizeInBits(0), PromBits),
8639 N->getValueType(0)));
8641 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8642 "Invalid extension type");
8643 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8645 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8646 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8647 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8648 N->getOperand(0), ShiftCst), ShiftCst);
8651 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8652 DAGCombinerInfo &DCI) const {
8653 assert((N->getOpcode() == ISD::SINT_TO_FP ||
8654 N->getOpcode() == ISD::UINT_TO_FP) &&
8655 "Need an int -> FP conversion node here");
8657 if (!Subtarget.has64BitSupport())
8660 SelectionDAG &DAG = DCI.DAG;
8664 // Don't handle ppc_fp128 here or i1 conversions.
8665 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8667 if (Op.getOperand(0).getValueType() == MVT::i1)
8670 // For i32 intermediate values, unfortunately, the conversion functions
8671 // leave the upper 32 bits of the value are undefined. Within the set of
8672 // scalar instructions, we have no method for zero- or sign-extending the
8673 // value. Thus, we cannot handle i32 intermediate values here.
8674 if (Op.getOperand(0).getValueType() == MVT::i32)
8677 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8678 "UINT_TO_FP is supported only with FPCVT");
8680 // If we have FCFIDS, then use it when converting to single-precision.
8681 // Otherwise, convert to double-precision and then round.
8682 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8683 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8685 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8687 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8691 // If we're converting from a float, to an int, and back to a float again,
8692 // then we don't need the store/load pair at all.
8693 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8694 Subtarget.hasFPCVT()) ||
8695 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8696 SDValue Src = Op.getOperand(0).getOperand(0);
8697 if (Src.getValueType() == MVT::f32) {
8698 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8699 DCI.AddToWorklist(Src.getNode());
8703 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8706 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8707 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8709 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8710 FP = DAG.getNode(ISD::FP_ROUND, dl,
8711 MVT::f32, FP, DAG.getIntPtrConstant(0));
8712 DCI.AddToWorklist(FP.getNode());
8721 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8722 // builtins) into loads with swaps.
8723 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8724 DAGCombinerInfo &DCI) const {
8725 SelectionDAG &DAG = DCI.DAG;
8729 MachineMemOperand *MMO;
8731 switch (N->getOpcode()) {
8733 llvm_unreachable("Unexpected opcode for little endian VSX load");
8735 LoadSDNode *LD = cast<LoadSDNode>(N);
8736 Chain = LD->getChain();
8737 Base = LD->getBasePtr();
8738 MMO = LD->getMemOperand();
8739 // If the MMO suggests this isn't a load of a full vector, leave
8740 // things alone. For a built-in, we have to make the change for
8741 // correctness, so if there is a size problem that will be a bug.
8742 if (MMO->getSize() < 16)
8746 case ISD::INTRINSIC_W_CHAIN: {
8747 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8748 Chain = Intrin->getChain();
8749 Base = Intrin->getBasePtr();
8750 MMO = Intrin->getMemOperand();
8755 MVT VecTy = N->getValueType(0).getSimpleVT();
8756 SDValue LoadOps[] = { Chain, Base };
8757 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8758 DAG.getVTList(VecTy, MVT::Other),
8759 LoadOps, VecTy, MMO);
8760 DCI.AddToWorklist(Load.getNode());
8761 Chain = Load.getValue(1);
8762 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8763 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8764 DCI.AddToWorklist(Swap.getNode());
8768 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8769 // builtins) into stores with swaps.
8770 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8771 DAGCombinerInfo &DCI) const {
8772 SelectionDAG &DAG = DCI.DAG;
8777 MachineMemOperand *MMO;
8779 switch (N->getOpcode()) {
8781 llvm_unreachable("Unexpected opcode for little endian VSX store");
8783 StoreSDNode *ST = cast<StoreSDNode>(N);
8784 Chain = ST->getChain();
8785 Base = ST->getBasePtr();
8786 MMO = ST->getMemOperand();
8788 // If the MMO suggests this isn't a store of a full vector, leave
8789 // things alone. For a built-in, we have to make the change for
8790 // correctness, so if there is a size problem that will be a bug.
8791 if (MMO->getSize() < 16)
8795 case ISD::INTRINSIC_VOID: {
8796 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8797 Chain = Intrin->getChain();
8798 // Intrin->getBasePtr() oddly does not get what we want.
8799 Base = Intrin->getOperand(3);
8800 MMO = Intrin->getMemOperand();
8806 SDValue Src = N->getOperand(SrcOpnd);
8807 MVT VecTy = Src.getValueType().getSimpleVT();
8808 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8809 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8810 DCI.AddToWorklist(Swap.getNode());
8811 Chain = Swap.getValue(1);
8812 SDValue StoreOps[] = { Chain, Swap, Base };
8813 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8814 DAG.getVTList(MVT::Other),
8815 StoreOps, VecTy, MMO);
8816 DCI.AddToWorklist(Store.getNode());
8820 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8821 DAGCombinerInfo &DCI) const {
8822 SelectionDAG &DAG = DCI.DAG;
8824 switch (N->getOpcode()) {
8827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8828 if (C->isNullValue()) // 0 << V -> 0.
8829 return N->getOperand(0);
8833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8834 if (C->isNullValue()) // 0 >>u V -> 0.
8835 return N->getOperand(0);
8839 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8840 if (C->isNullValue() || // 0 >>s V -> 0.
8841 C->isAllOnesValue()) // -1 >>s V -> -1.
8842 return N->getOperand(0);
8845 case ISD::SIGN_EXTEND:
8846 case ISD::ZERO_EXTEND:
8847 case ISD::ANY_EXTEND:
8848 return DAGCombineExtBoolTrunc(N, DCI);
8851 case ISD::SELECT_CC:
8852 return DAGCombineTruncBoolExt(N, DCI);
8853 case ISD::SINT_TO_FP:
8854 case ISD::UINT_TO_FP:
8855 return combineFPToIntToFP(N, DCI);
8857 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8858 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
8859 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8860 N->getOperand(1).getValueType() == MVT::i32 &&
8861 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8862 SDValue Val = N->getOperand(1).getOperand(0);
8863 if (Val.getValueType() == MVT::f32) {
8864 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8865 DCI.AddToWorklist(Val.getNode());
8867 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8868 DCI.AddToWorklist(Val.getNode());
8871 N->getOperand(0), Val, N->getOperand(2),
8872 DAG.getValueType(N->getOperand(1).getValueType())
8875 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8876 DAG.getVTList(MVT::Other), Ops,
8877 cast<StoreSDNode>(N)->getMemoryVT(),
8878 cast<StoreSDNode>(N)->getMemOperand());
8879 DCI.AddToWorklist(Val.getNode());
8883 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8884 if (cast<StoreSDNode>(N)->isUnindexed() &&
8885 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8886 N->getOperand(1).getNode()->hasOneUse() &&
8887 (N->getOperand(1).getValueType() == MVT::i32 ||
8888 N->getOperand(1).getValueType() == MVT::i16 ||
8889 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
8890 N->getOperand(1).getValueType() == MVT::i64))) {
8891 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8892 // Do an any-extend to 32-bits if this is a half-word input.
8893 if (BSwapOp.getValueType() == MVT::i16)
8894 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8897 N->getOperand(0), BSwapOp, N->getOperand(2),
8898 DAG.getValueType(N->getOperand(1).getValueType())
8901 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8902 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8903 cast<StoreSDNode>(N)->getMemOperand());
8906 // For little endian, VSX stores require generating xxswapd/lxvd2x.
8907 EVT VT = N->getOperand(1).getValueType();
8908 if (VT.isSimple()) {
8909 MVT StoreVT = VT.getSimpleVT();
8910 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8911 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8912 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8913 return expandVSXStoreForLE(N, DCI);
8918 LoadSDNode *LD = cast<LoadSDNode>(N);
8919 EVT VT = LD->getValueType(0);
8921 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8922 if (VT.isSimple()) {
8923 MVT LoadVT = VT.getSimpleVT();
8924 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8925 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8926 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8927 return expandVSXLoadForLE(N, DCI);
8930 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8931 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8932 if (ISD::isNON_EXTLoad(N) && VT.isVector() && Subtarget.hasAltivec() &&
8933 // P8 and later hardware should just use LOAD.
8934 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8935 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8936 LD->getAlignment() < ABIAlignment) {
8937 // This is a type-legal unaligned Altivec load.
8938 SDValue Chain = LD->getChain();
8939 SDValue Ptr = LD->getBasePtr();
8940 bool isLittleEndian = Subtarget.isLittleEndian();
8942 // This implements the loading of unaligned vectors as described in
8943 // the venerable Apple Velocity Engine overview. Specifically:
8944 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8945 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8947 // The general idea is to expand a sequence of one or more unaligned
8948 // loads into an alignment-based permutation-control instruction (lvsl
8949 // or lvsr), a series of regular vector loads (which always truncate
8950 // their input address to an aligned address), and a series of
8951 // permutations. The results of these permutations are the requested
8952 // loaded values. The trick is that the last "extra" load is not taken
8953 // from the address you might suspect (sizeof(vector) bytes after the
8954 // last requested load), but rather sizeof(vector) - 1 bytes after the
8955 // last requested vector. The point of this is to avoid a page fault if
8956 // the base address happened to be aligned. This works because if the
8957 // base address is aligned, then adding less than a full vector length
8958 // will cause the last vector in the sequence to be (re)loaded.
8959 // Otherwise, the next vector will be fetched as you might suspect was
8962 // We might be able to reuse the permutation generation from
8963 // a different base address offset from this one by an aligned amount.
8964 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8965 // optimization later.
8966 Intrinsic::ID Intr = (isLittleEndian ?
8967 Intrinsic::ppc_altivec_lvsr :
8968 Intrinsic::ppc_altivec_lvsl);
8969 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8971 // Create the new MMO for the new base load. It is like the original MMO,
8972 // but represents an area in memory almost twice the vector size centered
8973 // on the original address. If the address is unaligned, we might start
8974 // reading up to (sizeof(vector)-1) bytes below the address of the
8975 // original unaligned load.
8976 MachineFunction &MF = DAG.getMachineFunction();
8977 MachineMemOperand *BaseMMO =
8978 MF.getMachineMemOperand(LD->getMemOperand(),
8979 -LD->getMemoryVT().getStoreSize()+1,
8980 2*LD->getMemoryVT().getStoreSize()-1);
8982 // Create the new base load.
8983 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8985 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8987 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8988 DAG.getVTList(MVT::v4i32, MVT::Other),
8989 BaseLoadOps, MVT::v4i32, BaseMMO);
8991 // Note that the value of IncOffset (which is provided to the next
8992 // load's pointer info offset value, and thus used to calculate the
8993 // alignment), and the value of IncValue (which is actually used to
8994 // increment the pointer value) are different! This is because we
8995 // require the next load to appear to be aligned, even though it
8996 // is actually offset from the base pointer by a lesser amount.
8997 int IncOffset = VT.getSizeInBits() / 8;
8998 int IncValue = IncOffset;
9000 // Walk (both up and down) the chain looking for another load at the real
9001 // (aligned) offset (the alignment of the other load does not matter in
9002 // this case). If found, then do not use the offset reduction trick, as
9003 // that will prevent the loads from being later combined (as they would
9004 // otherwise be duplicates).
9005 if (!findConsecutiveLoad(LD, DAG))
9008 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9009 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9011 MachineMemOperand *ExtraMMO =
9012 MF.getMachineMemOperand(LD->getMemOperand(),
9013 1, 2*LD->getMemoryVT().getStoreSize()-1);
9014 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9016 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9017 DAG.getVTList(MVT::v4i32, MVT::Other),
9018 ExtraLoadOps, MVT::v4i32, ExtraMMO);
9020 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9021 BaseLoad.getValue(1), ExtraLoad.getValue(1));
9023 // Because vperm has a big-endian bias, we must reverse the order
9024 // of the input vectors and complement the permute control vector
9025 // when generating little endian code. We have already handled the
9026 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9027 // and ExtraLoad here.
9030 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9031 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9033 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9034 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9036 if (VT != MVT::v4i32)
9037 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
9039 // The output of the permutation is our loaded result, the TokenFactor is
9041 DCI.CombineTo(N, Perm, TF);
9042 return SDValue(N, 0);
9046 case ISD::INTRINSIC_WO_CHAIN: {
9047 bool isLittleEndian = Subtarget.isLittleEndian();
9048 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9049 : Intrinsic::ppc_altivec_lvsl);
9050 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
9051 N->getOperand(1)->getOpcode() == ISD::ADD) {
9052 SDValue Add = N->getOperand(1);
9054 if (DAG.MaskedValueIsZero(
9056 APInt::getAllOnesValue(4 /* 16 byte alignment */)
9058 Add.getValueType().getScalarType().getSizeInBits()))) {
9059 SDNode *BasePtr = Add->getOperand(0).getNode();
9060 for (SDNode::use_iterator UI = BasePtr->use_begin(),
9061 UE = BasePtr->use_end();
9063 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9064 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
9066 // We've found another LVSL/LVSR, and this address is an aligned
9067 // multiple of that one. The results will be the same, so use the
9068 // one we've just found instead.
9070 return SDValue(*UI, 0);
9078 case ISD::INTRINSIC_W_CHAIN: {
9079 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9080 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9081 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9084 case Intrinsic::ppc_vsx_lxvw4x:
9085 case Intrinsic::ppc_vsx_lxvd2x:
9086 return expandVSXLoadForLE(N, DCI);
9091 case ISD::INTRINSIC_VOID: {
9092 // For little endian, VSX stores require generating xxswapd/stxvd2x.
9093 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9094 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9097 case Intrinsic::ppc_vsx_stxvw4x:
9098 case Intrinsic::ppc_vsx_stxvd2x:
9099 return expandVSXStoreForLE(N, DCI);
9105 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
9106 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
9107 N->getOperand(0).hasOneUse() &&
9108 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
9109 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9110 N->getValueType(0) == MVT::i64))) {
9111 SDValue Load = N->getOperand(0);
9112 LoadSDNode *LD = cast<LoadSDNode>(Load);
9113 // Create the byte-swapping load.
9115 LD->getChain(), // Chain
9116 LD->getBasePtr(), // Ptr
9117 DAG.getValueType(N->getValueType(0)) // VT
9120 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
9121 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
9122 MVT::i64 : MVT::i32, MVT::Other),
9123 Ops, LD->getMemoryVT(), LD->getMemOperand());
9125 // If this is an i16 load, insert the truncate.
9126 SDValue ResVal = BSLoad;
9127 if (N->getValueType(0) == MVT::i16)
9128 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
9130 // First, combine the bswap away. This makes the value produced by the
9132 DCI.CombineTo(N, ResVal);
9134 // Next, combine the load away, we give it a bogus result value but a real
9135 // chain result. The result value is dead because the bswap is dead.
9136 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9138 // Return N so it doesn't get rechecked!
9139 return SDValue(N, 0);
9143 case PPCISD::VCMP: {
9144 // If a VCMPo node already exists with exactly the same operands as this
9145 // node, use its result instead of this node (VCMPo computes both a CR6 and
9146 // a normal output).
9148 if (!N->getOperand(0).hasOneUse() &&
9149 !N->getOperand(1).hasOneUse() &&
9150 !N->getOperand(2).hasOneUse()) {
9152 // Scan all of the users of the LHS, looking for VCMPo's that match.
9153 SDNode *VCMPoNode = nullptr;
9155 SDNode *LHSN = N->getOperand(0).getNode();
9156 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9158 if (UI->getOpcode() == PPCISD::VCMPo &&
9159 UI->getOperand(1) == N->getOperand(1) &&
9160 UI->getOperand(2) == N->getOperand(2) &&
9161 UI->getOperand(0) == N->getOperand(0)) {
9166 // If there is no VCMPo node, or if the flag value has a single use, don't
9168 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9171 // Look at the (necessarily single) use of the flag value. If it has a
9172 // chain, this transformation is more complex. Note that multiple things
9173 // could use the value result, which we should ignore.
9174 SDNode *FlagUser = nullptr;
9175 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9176 FlagUser == nullptr; ++UI) {
9177 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9179 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9180 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9187 // If the user is a MFOCRF instruction, we know this is safe.
9188 // Otherwise we give up for right now.
9189 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9190 return SDValue(VCMPoNode, 0);
9195 SDValue Cond = N->getOperand(1);
9196 SDValue Target = N->getOperand(2);
9198 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9199 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9200 Intrinsic::ppc_is_decremented_ctr_nonzero) {
9202 // We now need to make the intrinsic dead (it cannot be instruction
9204 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9205 assert(Cond.getNode()->hasOneUse() &&
9206 "Counter decrement has more than one use");
9208 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9209 N->getOperand(0), Target);
9214 // If this is a branch on an altivec predicate comparison, lower this so
9215 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
9216 // lowering is done pre-legalize, because the legalizer lowers the predicate
9217 // compare down to code that is difficult to reassemble.
9218 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9219 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9221 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9222 // value. If so, pass-through the AND to get to the intrinsic.
9223 if (LHS.getOpcode() == ISD::AND &&
9224 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9225 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9226 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9227 isa<ConstantSDNode>(LHS.getOperand(1)) &&
9228 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9230 LHS = LHS.getOperand(0);
9232 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9233 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9234 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9235 isa<ConstantSDNode>(RHS)) {
9236 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9237 "Counter decrement comparison is not EQ or NE");
9239 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9240 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9241 (CC == ISD::SETNE && !Val);
9243 // We now need to make the intrinsic dead (it cannot be instruction
9245 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9246 assert(LHS.getNode()->hasOneUse() &&
9247 "Counter decrement has more than one use");
9249 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9250 N->getOperand(0), N->getOperand(4));
9256 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9257 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9258 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9259 assert(isDot && "Can't compare against a vector result!");
9261 // If this is a comparison against something other than 0/1, then we know
9262 // that the condition is never/always true.
9263 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9264 if (Val != 0 && Val != 1) {
9265 if (CC == ISD::SETEQ) // Cond never true, remove branch.
9266 return N->getOperand(0);
9267 // Always !=, turn it into an unconditional branch.
9268 return DAG.getNode(ISD::BR, dl, MVT::Other,
9269 N->getOperand(0), N->getOperand(4));
9272 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9274 // Create the PPCISD altivec 'dot' comparison node.
9276 LHS.getOperand(2), // LHS of compare
9277 LHS.getOperand(3), // RHS of compare
9278 DAG.getConstant(CompareOpc, MVT::i32)
9280 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9281 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9283 // Unpack the result based on how the target uses it.
9284 PPC::Predicate CompOpc;
9285 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9286 default: // Can't happen, don't crash on invalid number though.
9287 case 0: // Branch on the value of the EQ bit of CR6.
9288 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9290 case 1: // Branch on the inverted value of the EQ bit of CR6.
9291 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9293 case 2: // Branch on the value of the LT bit of CR6.
9294 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9296 case 3: // Branch on the inverted value of the LT bit of CR6.
9297 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9301 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9302 DAG.getConstant(CompOpc, MVT::i32),
9303 DAG.getRegister(PPC::CR6, MVT::i32),
9304 N->getOperand(4), CompNode.getValue(1));
9314 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9316 std::vector<SDNode *> *Created) const {
9317 // fold (sdiv X, pow2)
9318 EVT VT = N->getValueType(0);
9319 if (VT == MVT::i64 && !Subtarget.isPPC64())
9321 if ((VT != MVT::i32 && VT != MVT::i64) ||
9322 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9326 SDValue N0 = N->getOperand(0);
9328 bool IsNegPow2 = (-Divisor).isPowerOf2();
9329 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9330 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9332 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9334 Created->push_back(Op.getNode());
9337 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9339 Created->push_back(Op.getNode());
9345 //===----------------------------------------------------------------------===//
9346 // Inline Assembly Support
9347 //===----------------------------------------------------------------------===//
9349 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9352 const SelectionDAG &DAG,
9353 unsigned Depth) const {
9354 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9355 switch (Op.getOpcode()) {
9357 case PPCISD::LBRX: {
9358 // lhbrx is known to have the top bits cleared out.
9359 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9360 KnownZero = 0xFFFF0000;
9363 case ISD::INTRINSIC_WO_CHAIN: {
9364 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9366 case Intrinsic::ppc_altivec_vcmpbfp_p:
9367 case Intrinsic::ppc_altivec_vcmpeqfp_p:
9368 case Intrinsic::ppc_altivec_vcmpequb_p:
9369 case Intrinsic::ppc_altivec_vcmpequh_p:
9370 case Intrinsic::ppc_altivec_vcmpequw_p:
9371 case Intrinsic::ppc_altivec_vcmpgefp_p:
9372 case Intrinsic::ppc_altivec_vcmpgtfp_p:
9373 case Intrinsic::ppc_altivec_vcmpgtsb_p:
9374 case Intrinsic::ppc_altivec_vcmpgtsh_p:
9375 case Intrinsic::ppc_altivec_vcmpgtsw_p:
9376 case Intrinsic::ppc_altivec_vcmpgtub_p:
9377 case Intrinsic::ppc_altivec_vcmpgtuh_p:
9378 case Intrinsic::ppc_altivec_vcmpgtuw_p:
9379 KnownZero = ~1U; // All bits but the low one are known to be zero.
9386 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9387 switch (Subtarget.getDarwinDirective()) {
9392 case PPC::DIR_PWR5X:
9394 case PPC::DIR_PWR6X:
9396 case PPC::DIR_PWR8: {
9400 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
9402 // For small loops (between 5 and 8 instructions), align to a 32-byte
9403 // boundary so that the entire loop fits in one instruction-cache line.
9404 uint64_t LoopSize = 0;
9405 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9406 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9407 LoopSize += TII->GetInstSizeInBytes(J);
9409 if (LoopSize > 16 && LoopSize <= 32)
9416 return TargetLowering::getPrefLoopAlignment(ML);
9419 /// getConstraintType - Given a constraint, return the type of
9420 /// constraint it is for this target.
9421 PPCTargetLowering::ConstraintType
9422 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9423 if (Constraint.size() == 1) {
9424 switch (Constraint[0]) {
9431 return C_RegisterClass;
9433 // FIXME: While Z does indicate a memory constraint, it specifically
9434 // indicates an r+r address (used in conjunction with the 'y' modifier
9435 // in the replacement string). Currently, we're forcing the base
9436 // register to be r0 in the asm printer (which is interpreted as zero)
9437 // and forming the complete address in the second register. This is
9441 } else if (Constraint == "wc") { // individual CR bits.
9442 return C_RegisterClass;
9443 } else if (Constraint == "wa" || Constraint == "wd" ||
9444 Constraint == "wf" || Constraint == "ws") {
9445 return C_RegisterClass; // VSX registers.
9447 return TargetLowering::getConstraintType(Constraint);
9450 /// Examine constraint type and operand type and determine a weight value.
9451 /// This object must already have been set up with the operand type
9452 /// and the current alternative constraint selected.
9453 TargetLowering::ConstraintWeight
9454 PPCTargetLowering::getSingleConstraintMatchWeight(
9455 AsmOperandInfo &info, const char *constraint) const {
9456 ConstraintWeight weight = CW_Invalid;
9457 Value *CallOperandVal = info.CallOperandVal;
9458 // If we don't have a value, we can't do a match,
9459 // but allow it at the lowest weight.
9460 if (!CallOperandVal)
9462 Type *type = CallOperandVal->getType();
9464 // Look at the constraint type.
9465 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9466 return CW_Register; // an individual CR bit.
9467 else if ((StringRef(constraint) == "wa" ||
9468 StringRef(constraint) == "wd" ||
9469 StringRef(constraint) == "wf") &&
9472 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9475 switch (*constraint) {
9477 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9480 if (type->isIntegerTy())
9481 weight = CW_Register;
9484 if (type->isFloatTy())
9485 weight = CW_Register;
9488 if (type->isDoubleTy())
9489 weight = CW_Register;
9492 if (type->isVectorTy())
9493 weight = CW_Register;
9496 weight = CW_Register;
9505 std::pair<unsigned, const TargetRegisterClass*>
9506 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9508 if (Constraint.size() == 1) {
9509 // GCC RS6000 Constraint Letters
9510 switch (Constraint[0]) {
9512 if (VT == MVT::i64 && Subtarget.isPPC64())
9513 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9514 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9516 if (VT == MVT::i64 && Subtarget.isPPC64())
9517 return std::make_pair(0U, &PPC::G8RCRegClass);
9518 return std::make_pair(0U, &PPC::GPRCRegClass);
9520 if (VT == MVT::f32 || VT == MVT::i32)
9521 return std::make_pair(0U, &PPC::F4RCRegClass);
9522 if (VT == MVT::f64 || VT == MVT::i64)
9523 return std::make_pair(0U, &PPC::F8RCRegClass);
9526 return std::make_pair(0U, &PPC::VRRCRegClass);
9528 return std::make_pair(0U, &PPC::CRRCRegClass);
9530 } else if (Constraint == "wc") { // an individual CR bit.
9531 return std::make_pair(0U, &PPC::CRBITRCRegClass);
9532 } else if (Constraint == "wa" || Constraint == "wd" ||
9533 Constraint == "wf") {
9534 return std::make_pair(0U, &PPC::VSRCRegClass);
9535 } else if (Constraint == "ws") {
9536 return std::make_pair(0U, &PPC::VSFRCRegClass);
9539 std::pair<unsigned, const TargetRegisterClass*> R =
9540 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9542 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9543 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9544 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9546 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9547 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9548 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9549 PPC::GPRCRegClass.contains(R.first)) {
9550 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9551 return std::make_pair(TRI->getMatchingSuperReg(R.first,
9552 PPC::sub_32, &PPC::G8RCRegClass),
9553 &PPC::G8RCRegClass);
9556 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9557 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9559 R.second = &PPC::CRRCRegClass;
9566 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9567 /// vector. If it is invalid, don't add anything to Ops.
9568 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9569 std::string &Constraint,
9570 std::vector<SDValue>&Ops,
9571 SelectionDAG &DAG) const {
9574 // Only support length 1 constraints.
9575 if (Constraint.length() > 1) return;
9577 char Letter = Constraint[0];
9588 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9589 if (!CST) return; // Must be an immediate to match.
9590 int64_t Value = CST->getSExtValue();
9591 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9592 // numbers are printed as such.
9594 default: llvm_unreachable("Unknown constraint letter!");
9595 case 'I': // "I" is a signed 16-bit constant.
9596 if (isInt<16>(Value))
9597 Result = DAG.getTargetConstant(Value, TCVT);
9599 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9600 if (isShiftedUInt<16, 16>(Value))
9601 Result = DAG.getTargetConstant(Value, TCVT);
9603 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9604 if (isShiftedInt<16, 16>(Value))
9605 Result = DAG.getTargetConstant(Value, TCVT);
9607 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9608 if (isUInt<16>(Value))
9609 Result = DAG.getTargetConstant(Value, TCVT);
9611 case 'M': // "M" is a constant that is greater than 31.
9613 Result = DAG.getTargetConstant(Value, TCVT);
9615 case 'N': // "N" is a positive constant that is an exact power of two.
9616 if (Value > 0 && isPowerOf2_64(Value))
9617 Result = DAG.getTargetConstant(Value, TCVT);
9619 case 'O': // "O" is the constant zero.
9621 Result = DAG.getTargetConstant(Value, TCVT);
9623 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9624 if (isInt<16>(-Value))
9625 Result = DAG.getTargetConstant(Value, TCVT);
9632 if (Result.getNode()) {
9633 Ops.push_back(Result);
9637 // Handle standard constraint letters.
9638 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9641 // isLegalAddressingMode - Return true if the addressing mode represented
9642 // by AM is legal for this target, for a load/store of the specified type.
9643 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9645 // FIXME: PPC does not allow r+i addressing modes for vectors!
9647 // PPC allows a sign-extended 16-bit immediate field.
9648 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9651 // No global is ever allowed as a base.
9655 // PPC only support r+r,
9657 case 0: // "r+i" or just "i", depending on HasBaseReg.
9660 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9662 // Otherwise we have r+r or r+i.
9665 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9667 // Allow 2*r as r+r.
9670 // No other scales are supported.
9677 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9678 SelectionDAG &DAG) const {
9679 MachineFunction &MF = DAG.getMachineFunction();
9680 MachineFrameInfo *MFI = MF.getFrameInfo();
9681 MFI->setReturnAddressIsTaken(true);
9683 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9687 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9689 // Make sure the function does not optimize away the store of the RA to
9691 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9692 FuncInfo->setLRStoreRequired();
9693 bool isPPC64 = Subtarget.isPPC64();
9694 bool isDarwinABI = Subtarget.isDarwinABI();
9697 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9700 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9701 isPPC64? MVT::i64 : MVT::i32);
9702 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9703 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9705 MachinePointerInfo(), false, false, false, 0);
9708 // Just load the return address off the stack.
9709 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9710 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9711 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9714 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9715 SelectionDAG &DAG) const {
9717 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9719 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9720 bool isPPC64 = PtrVT == MVT::i64;
9722 MachineFunction &MF = DAG.getMachineFunction();
9723 MachineFrameInfo *MFI = MF.getFrameInfo();
9724 MFI->setFrameAddressIsTaken(true);
9726 // Naked functions never have a frame pointer, and so we use r1. For all
9727 // other functions, this decision must be delayed until during PEI.
9729 if (MF.getFunction()->getAttributes().hasAttribute(
9730 AttributeSet::FunctionIndex, Attribute::Naked))
9731 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9733 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9735 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9738 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9739 FrameAddr, MachinePointerInfo(), false, false,
9744 // FIXME? Maybe this could be a TableGen attribute on some registers and
9745 // this table could be generated automatically from RegInfo.
9746 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9748 bool isPPC64 = Subtarget.isPPC64();
9749 bool isDarwinABI = Subtarget.isDarwinABI();
9751 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9752 (!isPPC64 && VT != MVT::i32))
9753 report_fatal_error("Invalid register global variable type");
9755 bool is64Bit = isPPC64 && VT == MVT::i64;
9756 unsigned Reg = StringSwitch<unsigned>(RegName)
9757 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9758 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
9759 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9760 (is64Bit ? PPC::X13 : PPC::R13))
9765 report_fatal_error("Invalid register name global variable");
9769 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9770 // The PowerPC target isn't yet aware of offsets.
9774 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9776 unsigned Intrinsic) const {
9778 switch (Intrinsic) {
9779 case Intrinsic::ppc_altivec_lvx:
9780 case Intrinsic::ppc_altivec_lvxl:
9781 case Intrinsic::ppc_altivec_lvebx:
9782 case Intrinsic::ppc_altivec_lvehx:
9783 case Intrinsic::ppc_altivec_lvewx:
9784 case Intrinsic::ppc_vsx_lxvd2x:
9785 case Intrinsic::ppc_vsx_lxvw4x: {
9787 switch (Intrinsic) {
9788 case Intrinsic::ppc_altivec_lvebx:
9791 case Intrinsic::ppc_altivec_lvehx:
9794 case Intrinsic::ppc_altivec_lvewx:
9797 case Intrinsic::ppc_vsx_lxvd2x:
9805 Info.opc = ISD::INTRINSIC_W_CHAIN;
9807 Info.ptrVal = I.getArgOperand(0);
9808 Info.offset = -VT.getStoreSize()+1;
9809 Info.size = 2*VT.getStoreSize()-1;
9812 Info.readMem = true;
9813 Info.writeMem = false;
9816 case Intrinsic::ppc_altivec_stvx:
9817 case Intrinsic::ppc_altivec_stvxl:
9818 case Intrinsic::ppc_altivec_stvebx:
9819 case Intrinsic::ppc_altivec_stvehx:
9820 case Intrinsic::ppc_altivec_stvewx:
9821 case Intrinsic::ppc_vsx_stxvd2x:
9822 case Intrinsic::ppc_vsx_stxvw4x: {
9824 switch (Intrinsic) {
9825 case Intrinsic::ppc_altivec_stvebx:
9828 case Intrinsic::ppc_altivec_stvehx:
9831 case Intrinsic::ppc_altivec_stvewx:
9834 case Intrinsic::ppc_vsx_stxvd2x:
9842 Info.opc = ISD::INTRINSIC_VOID;
9844 Info.ptrVal = I.getArgOperand(1);
9845 Info.offset = -VT.getStoreSize()+1;
9846 Info.size = 2*VT.getStoreSize()-1;
9849 Info.readMem = false;
9850 Info.writeMem = true;
9860 /// getOptimalMemOpType - Returns the target specific optimal type for load
9861 /// and store operations as a result of memset, memcpy, and memmove
9862 /// lowering. If DstAlign is zero that means it's safe to destination
9863 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9864 /// means there isn't a need to check it against alignment requirement,
9865 /// probably because the source does not need to be loaded. If 'IsMemset' is
9866 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9867 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9868 /// source is constant so it does not need to be loaded.
9869 /// It returns EVT::Other if the type should be determined using generic
9870 /// target-independent logic.
9871 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9872 unsigned DstAlign, unsigned SrcAlign,
9873 bool IsMemset, bool ZeroMemset,
9875 MachineFunction &MF) const {
9876 if (Subtarget.isPPC64()) {
9883 /// \brief Returns true if it is beneficial to convert a load of a constant
9884 /// to just the constant itself.
9885 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9887 assert(Ty->isIntegerTy());
9889 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9890 if (BitSize == 0 || BitSize > 64)
9895 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9896 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9898 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9899 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9900 return NumBits1 == 64 && NumBits2 == 32;
9903 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9904 if (!VT1.isInteger() || !VT2.isInteger())
9906 unsigned NumBits1 = VT1.getSizeInBits();
9907 unsigned NumBits2 = VT2.getSizeInBits();
9908 return NumBits1 == 64 && NumBits2 == 32;
9911 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9912 // Generally speaking, zexts are not free, but they are free when they can be
9913 // folded with other operations.
9914 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
9915 EVT MemVT = LD->getMemoryVT();
9916 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
9917 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
9918 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
9919 LD->getExtensionType() == ISD::ZEXTLOAD))
9923 // FIXME: Add other cases...
9924 // - 32-bit shifts with a zext to i64
9925 // - zext after ctlz, bswap, etc.
9926 // - zext after and by a constant mask
9928 return TargetLowering::isZExtFree(Val, VT2);
9931 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
9932 assert(VT.isFloatingPoint());
9936 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9937 return isInt<16>(Imm) || isUInt<16>(Imm);
9940 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9941 return isInt<16>(Imm) || isUInt<16>(Imm);
9944 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9948 if (DisablePPCUnaligned)
9951 // PowerPC supports unaligned memory access for simple non-vector types.
9952 // Although accessing unaligned addresses is not as efficient as accessing
9953 // aligned addresses, it is generally more efficient than manual expansion,
9954 // and generally only traps for software emulation when crossing page
9960 if (VT.getSimpleVT().isVector()) {
9961 if (Subtarget.hasVSX()) {
9962 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9963 VT != MVT::v4f32 && VT != MVT::v4i32)
9970 if (VT == MVT::ppcf128)
9979 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9980 VT = VT.getScalarType();
9985 switch (VT.getSimpleVT().SimpleTy) {
9997 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
9998 // LR is a callee-save register, but we must treat it as clobbered by any call
9999 // site. Hence we include LR in the scratch registers, which are in turn added
10000 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
10001 // to CTR, which is used by any indirect call.
10002 static const MCPhysReg ScratchRegs[] = {
10003 PPC::X12, PPC::LR8, PPC::CTR8, 0
10006 return ScratchRegs;
10010 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
10011 EVT VT , unsigned DefinedValues) const {
10012 if (VT == MVT::v2i64)
10015 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
10018 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
10019 if (DisableILPPref || Subtarget.enableMachineScheduler())
10020 return TargetLowering::getSchedulingPreference(N);
10025 // Create a fast isel object.
10027 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
10028 const TargetLibraryInfo *LibInfo) const {
10029 return PPC::createFastISel(FuncInfo, LibInfo);