1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61 const PPCSubtarget &STI)
62 : TargetLowering(TM), Subtarget(STI) {
63 // Use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(true);
65 setUseUnderscoreLongJmp(true);
67 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68 // arguments are at least 4/8 bytes aligned.
69 bool isPPC64 = Subtarget.isPPC64();
70 setMinStackArgumentAlignment(isPPC64 ? 8:4);
72 // Set up the register classes.
73 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78 for (MVT VT : MVT::integer_valuetypes()) {
79 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
83 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
85 // PowerPC has pre-inc load and store's.
86 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
101 if (Subtarget.useCRBits()) {
102 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
104 if (isPPC64 || Subtarget.hasFPCVT()) {
105 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107 isPPC64 ? MVT::i64 : MVT::i32);
108 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
110 isPPC64 ? MVT::i64 : MVT::i32);
112 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
116 // PowerPC does not support direct load / store of condition registers
117 setOperationAction(ISD::LOAD, MVT::i1, Custom);
118 setOperationAction(ISD::STORE, MVT::i1, Custom);
120 // FIXME: Remove this once the ANDI glue bug is fixed:
122 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
124 for (MVT VT : MVT::integer_valuetypes()) {
125 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127 setTruncStoreAction(VT, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget.hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget.hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185 Subtarget.hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget.hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget.hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget.hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget.useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget.useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget.useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget.isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget.isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget.has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (Subtarget.hasFPCVT()) {
371 if (Subtarget.has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget.use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget.hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (MVT VT : MVT::vector_valuetypes()) {
404 // add/sub are legal for all supported vector VT's.
405 setOperationAction(ISD::ADD , VT, Legal);
406 setOperationAction(ISD::SUB , VT, Legal);
408 // Vector instructions introduced in P8
409 if (Subtarget.hasP8Altivec()) {
410 setOperationAction(ISD::CTPOP, VT, Legal);
411 setOperationAction(ISD::CTLZ, VT, Legal);
414 setOperationAction(ISD::CTPOP, VT, Expand);
415 setOperationAction(ISD::CTLZ, VT, Expand);
418 // We promote all shuffles to v16i8.
419 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
422 // We promote all non-typed operations to v4i32.
423 setOperationAction(ISD::AND , VT, Promote);
424 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
425 setOperationAction(ISD::OR , VT, Promote);
426 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
427 setOperationAction(ISD::XOR , VT, Promote);
428 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
429 setOperationAction(ISD::LOAD , VT, Promote);
430 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
431 setOperationAction(ISD::SELECT, VT, Promote);
432 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433 setOperationAction(ISD::STORE, VT, Promote);
434 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
436 // No other operations are legal.
437 setOperationAction(ISD::MUL , VT, Expand);
438 setOperationAction(ISD::SDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UDIV, VT, Expand);
441 setOperationAction(ISD::UREM, VT, Expand);
442 setOperationAction(ISD::FDIV, VT, Expand);
443 setOperationAction(ISD::FREM, VT, Expand);
444 setOperationAction(ISD::FNEG, VT, Expand);
445 setOperationAction(ISD::FSQRT, VT, Expand);
446 setOperationAction(ISD::FLOG, VT, Expand);
447 setOperationAction(ISD::FLOG10, VT, Expand);
448 setOperationAction(ISD::FLOG2, VT, Expand);
449 setOperationAction(ISD::FEXP, VT, Expand);
450 setOperationAction(ISD::FEXP2, VT, Expand);
451 setOperationAction(ISD::FSIN, VT, Expand);
452 setOperationAction(ISD::FCOS, VT, Expand);
453 setOperationAction(ISD::FABS, VT, Expand);
454 setOperationAction(ISD::FPOWI, VT, Expand);
455 setOperationAction(ISD::FFLOOR, VT, Expand);
456 setOperationAction(ISD::FCEIL, VT, Expand);
457 setOperationAction(ISD::FTRUNC, VT, Expand);
458 setOperationAction(ISD::FRINT, VT, Expand);
459 setOperationAction(ISD::FNEARBYINT, VT, Expand);
460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463 setOperationAction(ISD::MULHU, VT, Expand);
464 setOperationAction(ISD::MULHS, VT, Expand);
465 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467 setOperationAction(ISD::UDIVREM, VT, Expand);
468 setOperationAction(ISD::SDIVREM, VT, Expand);
469 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470 setOperationAction(ISD::FPOW, VT, Expand);
471 setOperationAction(ISD::BSWAP, VT, Expand);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473 setOperationAction(ISD::CTTZ, VT, Expand);
474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475 setOperationAction(ISD::VSELECT, VT, Expand);
476 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
478 for (MVT InnerVT : MVT::vector_valuetypes()) {
479 setTruncStoreAction(VT, InnerVT, Expand);
480 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
486 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487 // with merges, splats, etc.
488 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
490 setOperationAction(ISD::AND , MVT::v4i32, Legal);
491 setOperationAction(ISD::OR , MVT::v4i32, Legal);
492 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
493 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
494 setOperationAction(ISD::SELECT, MVT::v4i32,
495 Subtarget.useCRBits() ? Legal : Expand);
496 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
506 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
511 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
514 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
519 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
523 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
524 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
526 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
527 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
528 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
529 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
531 // Altivec does not contain unordered floating-point compare instructions
532 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
535 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
537 if (Subtarget.hasVSX()) {
538 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
541 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
547 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
549 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
552 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
561 // Share the Altivec comparison restrictions.
562 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
567 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
568 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
570 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
572 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
574 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
575 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
577 // VSX v2i64 only supports non-arithmetic operations.
578 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
579 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
581 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
582 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
583 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
585 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
587 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
588 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
589 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
590 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
592 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
594 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
595 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
596 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
597 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
599 // Vector operation legalization checks the result type of
600 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
601 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
602 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
603 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
604 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
606 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
609 if (Subtarget.hasP8Altivec())
610 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
613 if (Subtarget.has64BitSupport())
614 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
616 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
619 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
620 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
623 setBooleanContents(ZeroOrOneBooleanContent);
624 // Altivec instructions set fields to all zeros or all ones.
625 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
628 // These libcalls are not available in 32-bit.
629 setLibcallName(RTLIB::SHL_I128, nullptr);
630 setLibcallName(RTLIB::SRL_I128, nullptr);
631 setLibcallName(RTLIB::SRA_I128, nullptr);
635 setStackPointerRegisterToSaveRestore(PPC::X1);
636 setExceptionPointerRegister(PPC::X3);
637 setExceptionSelectorRegister(PPC::X4);
639 setStackPointerRegisterToSaveRestore(PPC::R1);
640 setExceptionPointerRegister(PPC::R3);
641 setExceptionSelectorRegister(PPC::R4);
644 // We have target-specific dag combine patterns for the following nodes:
645 setTargetDAGCombine(ISD::SINT_TO_FP);
646 if (Subtarget.hasFPCVT())
647 setTargetDAGCombine(ISD::UINT_TO_FP);
648 setTargetDAGCombine(ISD::LOAD);
649 setTargetDAGCombine(ISD::STORE);
650 setTargetDAGCombine(ISD::BR_CC);
651 if (Subtarget.useCRBits())
652 setTargetDAGCombine(ISD::BRCOND);
653 setTargetDAGCombine(ISD::BSWAP);
654 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
655 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
656 setTargetDAGCombine(ISD::INTRINSIC_VOID);
658 setTargetDAGCombine(ISD::SIGN_EXTEND);
659 setTargetDAGCombine(ISD::ZERO_EXTEND);
660 setTargetDAGCombine(ISD::ANY_EXTEND);
662 if (Subtarget.useCRBits()) {
663 setTargetDAGCombine(ISD::TRUNCATE);
664 setTargetDAGCombine(ISD::SETCC);
665 setTargetDAGCombine(ISD::SELECT_CC);
668 // Use reciprocal estimates.
669 if (TM.Options.UnsafeFPMath) {
670 setTargetDAGCombine(ISD::FDIV);
671 setTargetDAGCombine(ISD::FSQRT);
674 // Darwin long double math library functions have $LDBL128 appended.
675 if (Subtarget.isDarwin()) {
676 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
677 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
678 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
679 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
680 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
681 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
682 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
683 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
684 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
685 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
688 // With 32 condition bits, we don't need to sink (and duplicate) compares
689 // aggressively in CodeGenPrep.
690 if (Subtarget.useCRBits())
691 setHasMultipleConditionRegisters();
693 setMinFunctionAlignment(2);
694 if (Subtarget.isDarwin())
695 setPrefFunctionAlignment(4);
697 switch (Subtarget.getDarwinDirective()) {
701 case PPC::DIR_E500mc:
710 setPrefFunctionAlignment(4);
711 setPrefLoopAlignment(4);
715 setInsertFencesForAtomic(true);
717 if (Subtarget.enableMachineScheduler())
718 setSchedulingPreference(Sched::Source);
720 setSchedulingPreference(Sched::Hybrid);
722 computeRegisterProperties();
724 // The Freescale cores do better with aggressive inlining of memcpy and
725 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
726 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
727 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
728 MaxStoresPerMemset = 32;
729 MaxStoresPerMemsetOptSize = 16;
730 MaxStoresPerMemcpy = 32;
731 MaxStoresPerMemcpyOptSize = 8;
732 MaxStoresPerMemmove = 32;
733 MaxStoresPerMemmoveOptSize = 8;
737 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
738 /// the desired ByVal argument alignment.
739 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
740 unsigned MaxMaxAlign) {
741 if (MaxAlign == MaxMaxAlign)
743 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
744 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
746 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
748 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
749 unsigned EltAlign = 0;
750 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
751 if (EltAlign > MaxAlign)
753 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
754 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
755 unsigned EltAlign = 0;
756 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
757 if (EltAlign > MaxAlign)
759 if (MaxAlign == MaxMaxAlign)
765 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
766 /// function arguments in the caller parameter area.
767 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
768 // Darwin passes everything on 4 byte boundary.
769 if (Subtarget.isDarwin())
772 // 16byte and wider vectors are passed on 16byte boundary.
773 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
774 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
775 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
776 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
780 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
782 default: return nullptr;
783 case PPCISD::FSEL: return "PPCISD::FSEL";
784 case PPCISD::FCFID: return "PPCISD::FCFID";
785 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
786 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
787 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
788 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
789 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
790 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
791 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
792 case PPCISD::FRE: return "PPCISD::FRE";
793 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
794 case PPCISD::STFIWX: return "PPCISD::STFIWX";
795 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
796 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
797 case PPCISD::VPERM: return "PPCISD::VPERM";
798 case PPCISD::CMPB: return "PPCISD::CMPB";
799 case PPCISD::Hi: return "PPCISD::Hi";
800 case PPCISD::Lo: return "PPCISD::Lo";
801 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
802 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
803 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
804 case PPCISD::SRL: return "PPCISD::SRL";
805 case PPCISD::SRA: return "PPCISD::SRA";
806 case PPCISD::SHL: return "PPCISD::SHL";
807 case PPCISD::CALL: return "PPCISD::CALL";
808 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
809 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS";
810 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS";
811 case PPCISD::MTCTR: return "PPCISD::MTCTR";
812 case PPCISD::BCTRL: return "PPCISD::BCTRL";
813 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
814 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
815 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
816 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
817 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
818 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
819 case PPCISD::VCMP: return "PPCISD::VCMP";
820 case PPCISD::VCMPo: return "PPCISD::VCMPo";
821 case PPCISD::LBRX: return "PPCISD::LBRX";
822 case PPCISD::STBRX: return "PPCISD::STBRX";
823 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
824 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
825 case PPCISD::LARX: return "PPCISD::LARX";
826 case PPCISD::STCX: return "PPCISD::STCX";
827 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
828 case PPCISD::BDNZ: return "PPCISD::BDNZ";
829 case PPCISD::BDZ: return "PPCISD::BDZ";
830 case PPCISD::MFFS: return "PPCISD::MFFS";
831 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
832 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
833 case PPCISD::CR6SET: return "PPCISD::CR6SET";
834 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
835 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
836 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
837 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
838 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
839 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
840 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
841 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
842 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
843 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
844 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
845 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
846 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
847 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
848 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
849 case PPCISD::SC: return "PPCISD::SC";
853 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
855 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
856 return VT.changeVectorElementTypeToInteger();
859 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
860 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
864 //===----------------------------------------------------------------------===//
865 // Node matching predicates, for use by the tblgen matching code.
866 //===----------------------------------------------------------------------===//
868 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
869 static bool isFloatingPointZero(SDValue Op) {
870 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
871 return CFP->getValueAPF().isZero();
872 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
873 // Maybe this has already been legalized into the constant pool?
874 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
875 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
876 return CFP->getValueAPF().isZero();
881 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
882 /// true if Op is undef or if it matches the specified value.
883 static bool isConstantOrUndef(int Op, int Val) {
884 return Op < 0 || Op == Val;
887 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
888 /// VPKUHUM instruction.
889 /// The ShuffleKind distinguishes between big-endian operations with
890 /// two different inputs (0), either-endian operations with two identical
891 /// inputs (1), and little-endian operantion with two different inputs (2).
892 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
893 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
895 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
896 if (ShuffleKind == 0) {
899 for (unsigned i = 0; i != 16; ++i)
900 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
902 } else if (ShuffleKind == 2) {
905 for (unsigned i = 0; i != 16; ++i)
906 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
908 } else if (ShuffleKind == 1) {
909 unsigned j = IsLE ? 0 : 1;
910 for (unsigned i = 0; i != 8; ++i)
911 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
912 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
918 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
919 /// VPKUWUM instruction.
920 /// The ShuffleKind distinguishes between big-endian operations with
921 /// two different inputs (0), either-endian operations with two identical
922 /// inputs (1), and little-endian operantion with two different inputs (2).
923 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
924 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
926 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
927 if (ShuffleKind == 0) {
930 for (unsigned i = 0; i != 16; i += 2)
931 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
932 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
934 } else if (ShuffleKind == 2) {
937 for (unsigned i = 0; i != 16; i += 2)
938 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
939 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
941 } else if (ShuffleKind == 1) {
942 unsigned j = IsLE ? 0 : 2;
943 for (unsigned i = 0; i != 8; i += 2)
944 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
945 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
946 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
947 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
953 /// isVMerge - Common function, used to match vmrg* shuffles.
955 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
956 unsigned LHSStart, unsigned RHSStart) {
957 if (N->getValueType(0) != MVT::v16i8)
959 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
960 "Unsupported merge size!");
962 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
963 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
964 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
965 LHSStart+j+i*UnitSize) ||
966 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
967 RHSStart+j+i*UnitSize))
973 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
974 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
975 /// The ShuffleKind distinguishes between big-endian merges with two
976 /// different inputs (0), either-endian merges with two identical inputs (1),
977 /// and little-endian merges with two different inputs (2). For the latter,
978 /// the input operands are swapped (see PPCInstrAltivec.td).
979 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
980 unsigned ShuffleKind, SelectionDAG &DAG) {
981 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
982 if (ShuffleKind == 1) // unary
983 return isVMerge(N, UnitSize, 0, 0);
984 else if (ShuffleKind == 2) // swapped
985 return isVMerge(N, UnitSize, 0, 16);
989 if (ShuffleKind == 1) // unary
990 return isVMerge(N, UnitSize, 8, 8);
991 else if (ShuffleKind == 0) // normal
992 return isVMerge(N, UnitSize, 8, 24);
998 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
999 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1000 /// The ShuffleKind distinguishes between big-endian merges with two
1001 /// different inputs (0), either-endian merges with two identical inputs (1),
1002 /// and little-endian merges with two different inputs (2). For the latter,
1003 /// the input operands are swapped (see PPCInstrAltivec.td).
1004 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1005 unsigned ShuffleKind, SelectionDAG &DAG) {
1006 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1007 if (ShuffleKind == 1) // unary
1008 return isVMerge(N, UnitSize, 8, 8);
1009 else if (ShuffleKind == 2) // swapped
1010 return isVMerge(N, UnitSize, 8, 24);
1014 if (ShuffleKind == 1) // unary
1015 return isVMerge(N, UnitSize, 0, 0);
1016 else if (ShuffleKind == 0) // normal
1017 return isVMerge(N, UnitSize, 0, 16);
1024 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1025 /// amount, otherwise return -1.
1026 /// The ShuffleKind distinguishes between big-endian operations with two
1027 /// different inputs (0), either-endian operations with two identical inputs
1028 /// (1), and little-endian operations with two different inputs (2). For the
1029 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1030 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1031 SelectionDAG &DAG) {
1032 if (N->getValueType(0) != MVT::v16i8)
1035 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1037 // Find the first non-undef value in the shuffle mask.
1039 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1042 if (i == 16) return -1; // all undef.
1044 // Otherwise, check to see if the rest of the elements are consecutively
1045 // numbered from this value.
1046 unsigned ShiftAmt = SVOp->getMaskElt(i);
1047 if (ShiftAmt < i) return -1;
1050 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1052 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1053 // Check the rest of the elements to see if they are consecutive.
1054 for (++i; i != 16; ++i)
1055 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1057 } else if (ShuffleKind == 1) {
1058 // Check the rest of the elements to see if they are consecutive.
1059 for (++i; i != 16; ++i)
1060 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1065 if (ShuffleKind == 2 && isLE)
1066 ShiftAmt = 16 - ShiftAmt;
1071 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1072 /// specifies a splat of a single element that is suitable for input to
1073 /// VSPLTB/VSPLTH/VSPLTW.
1074 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1075 assert(N->getValueType(0) == MVT::v16i8 &&
1076 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1078 // This is a splat operation if each element of the permute is the same, and
1079 // if the value doesn't reference the second vector.
1080 unsigned ElementBase = N->getMaskElt(0);
1082 // FIXME: Handle UNDEF elements too!
1083 if (ElementBase >= 16)
1086 // Check that the indices are consecutive, in the case of a multi-byte element
1087 // splatted with a v16i8 mask.
1088 for (unsigned i = 1; i != EltSize; ++i)
1089 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1092 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1093 if (N->getMaskElt(i) < 0) continue;
1094 for (unsigned j = 0; j != EltSize; ++j)
1095 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1101 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1103 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1104 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1106 APInt APVal, APUndef;
1110 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1111 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1112 return CFP->getValueAPF().isNegZero();
1117 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1118 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1119 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1120 SelectionDAG &DAG) {
1121 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1122 assert(isSplatShuffleMask(SVOp, EltSize));
1123 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1124 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1126 return SVOp->getMaskElt(0) / EltSize;
1129 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1130 /// by using a vspltis[bhw] instruction of the specified element size, return
1131 /// the constant being splatted. The ByteSize field indicates the number of
1132 /// bytes of each element [124] -> [bhw].
1133 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1134 SDValue OpVal(nullptr, 0);
1136 // If ByteSize of the splat is bigger than the element size of the
1137 // build_vector, then we have a case where we are checking for a splat where
1138 // multiple elements of the buildvector are folded together into a single
1139 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1140 unsigned EltSize = 16/N->getNumOperands();
1141 if (EltSize < ByteSize) {
1142 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1143 SDValue UniquedVals[4];
1144 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1146 // See if all of the elements in the buildvector agree across.
1147 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1148 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1149 // If the element isn't a constant, bail fully out.
1150 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1153 if (!UniquedVals[i&(Multiple-1)].getNode())
1154 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1155 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1156 return SDValue(); // no match.
1159 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1160 // either constant or undef values that are identical for each chunk. See
1161 // if these chunks can form into a larger vspltis*.
1163 // Check to see if all of the leading entries are either 0 or -1. If
1164 // neither, then this won't fit into the immediate field.
1165 bool LeadingZero = true;
1166 bool LeadingOnes = true;
1167 for (unsigned i = 0; i != Multiple-1; ++i) {
1168 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1170 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1171 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1173 // Finally, check the least significant entry.
1175 if (!UniquedVals[Multiple-1].getNode())
1176 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1177 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1179 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1182 if (!UniquedVals[Multiple-1].getNode())
1183 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1184 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1185 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1186 return DAG.getTargetConstant(Val, MVT::i32);
1192 // Check to see if this buildvec has a single non-undef value in its elements.
1193 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1194 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1195 if (!OpVal.getNode())
1196 OpVal = N->getOperand(i);
1197 else if (OpVal != N->getOperand(i))
1201 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1203 unsigned ValSizeInBytes = EltSize;
1205 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1206 Value = CN->getZExtValue();
1207 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1208 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1209 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1212 // If the splat value is larger than the element value, then we can never do
1213 // this splat. The only case that we could fit the replicated bits into our
1214 // immediate field for would be zero, and we prefer to use vxor for it.
1215 if (ValSizeInBytes < ByteSize) return SDValue();
1217 // If the element value is larger than the splat value, cut it in half and
1218 // check to see if the two halves are equal. Continue doing this until we
1219 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1220 while (ValSizeInBytes > ByteSize) {
1221 ValSizeInBytes >>= 1;
1223 // If the top half equals the bottom half, we're still ok.
1224 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1225 (Value & ((1 << (8*ValSizeInBytes))-1)))
1229 // Properly sign extend the value.
1230 int MaskVal = SignExtend32(Value, ByteSize * 8);
1232 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1233 if (MaskVal == 0) return SDValue();
1235 // Finally, if this value fits in a 5 bit sext field, return it
1236 if (SignExtend32<5>(MaskVal) == MaskVal)
1237 return DAG.getTargetConstant(MaskVal, MVT::i32);
1241 //===----------------------------------------------------------------------===//
1242 // Addressing Mode Selection
1243 //===----------------------------------------------------------------------===//
1245 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1246 /// or 64-bit immediate, and if the value can be accurately represented as a
1247 /// sign extension from a 16-bit value. If so, this returns true and the
1249 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1250 if (!isa<ConstantSDNode>(N))
1253 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1254 if (N->getValueType(0) == MVT::i32)
1255 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1257 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1259 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1260 return isIntS16Immediate(Op.getNode(), Imm);
1264 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1265 /// can be represented as an indexed [r+r] operation. Returns false if it
1266 /// can be more efficiently represented with [r+imm].
1267 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1269 SelectionDAG &DAG) const {
1271 if (N.getOpcode() == ISD::ADD) {
1272 if (isIntS16Immediate(N.getOperand(1), imm))
1273 return false; // r+i
1274 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1275 return false; // r+i
1277 Base = N.getOperand(0);
1278 Index = N.getOperand(1);
1280 } else if (N.getOpcode() == ISD::OR) {
1281 if (isIntS16Immediate(N.getOperand(1), imm))
1282 return false; // r+i can fold it if we can.
1284 // If this is an or of disjoint bitfields, we can codegen this as an add
1285 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1287 APInt LHSKnownZero, LHSKnownOne;
1288 APInt RHSKnownZero, RHSKnownOne;
1289 DAG.computeKnownBits(N.getOperand(0),
1290 LHSKnownZero, LHSKnownOne);
1292 if (LHSKnownZero.getBoolValue()) {
1293 DAG.computeKnownBits(N.getOperand(1),
1294 RHSKnownZero, RHSKnownOne);
1295 // If all of the bits are known zero on the LHS or RHS, the add won't
1297 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1298 Base = N.getOperand(0);
1299 Index = N.getOperand(1);
1308 // If we happen to be doing an i64 load or store into a stack slot that has
1309 // less than a 4-byte alignment, then the frame-index elimination may need to
1310 // use an indexed load or store instruction (because the offset may not be a
1311 // multiple of 4). The extra register needed to hold the offset comes from the
1312 // register scavenger, and it is possible that the scavenger will need to use
1313 // an emergency spill slot. As a result, we need to make sure that a spill slot
1314 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1316 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1317 // FIXME: This does not handle the LWA case.
1321 // NOTE: We'll exclude negative FIs here, which come from argument
1322 // lowering, because there are no known test cases triggering this problem
1323 // using packed structures (or similar). We can remove this exclusion if
1324 // we find such a test case. The reason why this is so test-case driven is
1325 // because this entire 'fixup' is only to prevent crashes (from the
1326 // register scavenger) on not-really-valid inputs. For example, if we have:
1328 // %b = bitcast i1* %a to i64*
1329 // store i64* a, i64 b
1330 // then the store should really be marked as 'align 1', but is not. If it
1331 // were marked as 'align 1' then the indexed form would have been
1332 // instruction-selected initially, and the problem this 'fixup' is preventing
1333 // won't happen regardless.
1337 MachineFunction &MF = DAG.getMachineFunction();
1338 MachineFrameInfo *MFI = MF.getFrameInfo();
1340 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1344 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1345 FuncInfo->setHasNonRISpills();
1348 /// Returns true if the address N can be represented by a base register plus
1349 /// a signed 16-bit displacement [r+imm], and if it is not better
1350 /// represented as reg+reg. If Aligned is true, only accept displacements
1351 /// suitable for STD and friends, i.e. multiples of 4.
1352 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1355 bool Aligned) const {
1356 // FIXME dl should come from parent load or store, not from address
1358 // If this can be more profitably realized as r+r, fail.
1359 if (SelectAddressRegReg(N, Disp, Base, DAG))
1362 if (N.getOpcode() == ISD::ADD) {
1364 if (isIntS16Immediate(N.getOperand(1), imm) &&
1365 (!Aligned || (imm & 3) == 0)) {
1366 Disp = DAG.getTargetConstant(imm, N.getValueType());
1367 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1368 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1369 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1371 Base = N.getOperand(0);
1373 return true; // [r+i]
1374 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1375 // Match LOAD (ADD (X, Lo(G))).
1376 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1377 && "Cannot handle constant offsets yet!");
1378 Disp = N.getOperand(1).getOperand(0); // The global address.
1379 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1380 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1381 Disp.getOpcode() == ISD::TargetConstantPool ||
1382 Disp.getOpcode() == ISD::TargetJumpTable);
1383 Base = N.getOperand(0);
1384 return true; // [&g+r]
1386 } else if (N.getOpcode() == ISD::OR) {
1388 if (isIntS16Immediate(N.getOperand(1), imm) &&
1389 (!Aligned || (imm & 3) == 0)) {
1390 // If this is an or of disjoint bitfields, we can codegen this as an add
1391 // (for better address arithmetic) if the LHS and RHS of the OR are
1392 // provably disjoint.
1393 APInt LHSKnownZero, LHSKnownOne;
1394 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1396 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1397 // If all of the bits are known zero on the LHS or RHS, the add won't
1399 if (FrameIndexSDNode *FI =
1400 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1401 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1402 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1404 Base = N.getOperand(0);
1406 Disp = DAG.getTargetConstant(imm, N.getValueType());
1410 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1411 // Loading from a constant address.
1413 // If this address fits entirely in a 16-bit sext immediate field, codegen
1416 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1417 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1418 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1419 CN->getValueType(0));
1423 // Handle 32-bit sext immediates with LIS + addr mode.
1424 if ((CN->getValueType(0) == MVT::i32 ||
1425 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1426 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1427 int Addr = (int)CN->getZExtValue();
1429 // Otherwise, break this down into an LIS + disp.
1430 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1432 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1433 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1434 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1439 Disp = DAG.getTargetConstant(0, getPointerTy());
1440 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1441 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1442 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1445 return true; // [r+0]
1448 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1449 /// represented as an indexed [r+r] operation.
1450 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1452 SelectionDAG &DAG) const {
1453 // Check to see if we can easily represent this as an [r+r] address. This
1454 // will fail if it thinks that the address is more profitably represented as
1455 // reg+imm, e.g. where imm = 0.
1456 if (SelectAddressRegReg(N, Base, Index, DAG))
1459 // If the operand is an addition, always emit this as [r+r], since this is
1460 // better (for code size, and execution, as the memop does the add for free)
1461 // than emitting an explicit add.
1462 if (N.getOpcode() == ISD::ADD) {
1463 Base = N.getOperand(0);
1464 Index = N.getOperand(1);
1468 // Otherwise, do it the hard way, using R0 as the base register.
1469 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1475 /// getPreIndexedAddressParts - returns true by value, base pointer and
1476 /// offset pointer and addressing mode by reference if the node's address
1477 /// can be legally represented as pre-indexed load / store address.
1478 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1480 ISD::MemIndexedMode &AM,
1481 SelectionDAG &DAG) const {
1482 if (DisablePPCPreinc) return false;
1488 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1489 Ptr = LD->getBasePtr();
1490 VT = LD->getMemoryVT();
1491 Alignment = LD->getAlignment();
1492 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1493 Ptr = ST->getBasePtr();
1494 VT = ST->getMemoryVT();
1495 Alignment = ST->getAlignment();
1500 // PowerPC doesn't have preinc load/store instructions for vectors.
1504 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1506 // Common code will reject creating a pre-inc form if the base pointer
1507 // is a frame index, or if N is a store and the base pointer is either
1508 // the same as or a predecessor of the value being stored. Check for
1509 // those situations here, and try with swapped Base/Offset instead.
1512 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1515 SDValue Val = cast<StoreSDNode>(N)->getValue();
1516 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1521 std::swap(Base, Offset);
1527 // LDU/STU can only handle immediates that are a multiple of 4.
1528 if (VT != MVT::i64) {
1529 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1532 // LDU/STU need an address with at least 4-byte alignment.
1536 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1540 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1541 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1542 // sext i32 to i64 when addr mode is r+i.
1543 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1544 LD->getExtensionType() == ISD::SEXTLOAD &&
1545 isa<ConstantSDNode>(Offset))
1553 //===----------------------------------------------------------------------===//
1554 // LowerOperation implementation
1555 //===----------------------------------------------------------------------===//
1557 /// GetLabelAccessInfo - Return true if we should reference labels using a
1558 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1559 static bool GetLabelAccessInfo(const TargetMachine &TM,
1560 const PPCSubtarget &Subtarget,
1561 unsigned &HiOpFlags, unsigned &LoOpFlags,
1562 const GlobalValue *GV = nullptr) {
1563 HiOpFlags = PPCII::MO_HA;
1564 LoOpFlags = PPCII::MO_LO;
1566 // Don't use the pic base if not in PIC relocation model.
1567 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1570 HiOpFlags |= PPCII::MO_PIC_FLAG;
1571 LoOpFlags |= PPCII::MO_PIC_FLAG;
1574 // If this is a reference to a global value that requires a non-lazy-ptr, make
1575 // sure that instruction lowering adds it.
1576 if (GV && Subtarget.hasLazyResolverStub(GV, TM)) {
1577 HiOpFlags |= PPCII::MO_NLP_FLAG;
1578 LoOpFlags |= PPCII::MO_NLP_FLAG;
1580 if (GV->hasHiddenVisibility()) {
1581 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1582 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1589 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1590 SelectionDAG &DAG) {
1591 EVT PtrVT = HiPart.getValueType();
1592 SDValue Zero = DAG.getConstant(0, PtrVT);
1595 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1596 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1598 // With PIC, the first instruction is actually "GR+hi(&G)".
1600 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1601 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1603 // Generate non-pic code that has direct accesses to the constant pool.
1604 // The address of the global is just (hi(&g)+lo(&g)).
1605 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1608 static void setUsesTOCBasePtr(MachineFunction &MF) {
1609 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1610 FuncInfo->setUsesTOCBasePtr();
1613 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1614 setUsesTOCBasePtr(DAG.getMachineFunction());
1617 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1618 SelectionDAG &DAG) const {
1619 EVT PtrVT = Op.getValueType();
1620 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1621 const Constant *C = CP->getConstVal();
1623 // 64-bit SVR4 ABI code is always position-independent.
1624 // The actual address of the GlobalValue is stored in the TOC.
1625 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1626 setUsesTOCBasePtr(DAG);
1627 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1628 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1629 DAG.getRegister(PPC::X2, MVT::i64));
1632 unsigned MOHiFlag, MOLoFlag;
1634 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1636 if (isPIC && Subtarget.isSVR4ABI()) {
1637 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1638 PPCII::MO_PIC_FLAG);
1640 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1641 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1645 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1647 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1648 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1651 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1652 EVT PtrVT = Op.getValueType();
1653 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1655 // 64-bit SVR4 ABI code is always position-independent.
1656 // The actual address of the GlobalValue is stored in the TOC.
1657 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1658 setUsesTOCBasePtr(DAG);
1659 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1660 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1661 DAG.getRegister(PPC::X2, MVT::i64));
1664 unsigned MOHiFlag, MOLoFlag;
1666 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1668 if (isPIC && Subtarget.isSVR4ABI()) {
1669 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1670 PPCII::MO_PIC_FLAG);
1672 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1673 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1676 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1677 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1678 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1681 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1682 SelectionDAG &DAG) const {
1683 EVT PtrVT = Op.getValueType();
1684 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1685 const BlockAddress *BA = BASDN->getBlockAddress();
1687 // 64-bit SVR4 ABI code is always position-independent.
1688 // The actual BlockAddress is stored in the TOC.
1689 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1690 setUsesTOCBasePtr(DAG);
1691 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1692 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1693 DAG.getRegister(PPC::X2, MVT::i64));
1696 unsigned MOHiFlag, MOLoFlag;
1698 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1699 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1700 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1701 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1704 // Generate a call to __tls_get_addr for the given GOT entry Op.
1705 std::pair<SDValue,SDValue>
1706 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1707 SelectionDAG &DAG) const {
1709 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1710 TargetLowering::ArgListTy Args;
1711 TargetLowering::ArgListEntry Entry;
1713 Entry.Ty = IntPtrTy;
1714 Args.push_back(Entry);
1716 TargetLowering::CallLoweringInfo CLI(DAG);
1717 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1718 .setCallee(CallingConv::C, IntPtrTy,
1719 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1720 std::move(Args), 0);
1722 return LowerCallTo(CLI);
1725 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1726 SelectionDAG &DAG) const {
1728 // FIXME: TLS addresses currently use medium model code sequences,
1729 // which is the most useful form. Eventually support for small and
1730 // large models could be added if users need it, at the cost of
1731 // additional complexity.
1732 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1734 const GlobalValue *GV = GA->getGlobal();
1735 EVT PtrVT = getPointerTy();
1736 bool is64bit = Subtarget.isPPC64();
1737 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1738 PICLevel::Level picLevel = M->getPICLevel();
1740 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1742 if (Model == TLSModel::LocalExec) {
1743 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1744 PPCII::MO_TPREL_HA);
1745 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1746 PPCII::MO_TPREL_LO);
1747 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1748 is64bit ? MVT::i64 : MVT::i32);
1749 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1750 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1753 if (Model == TLSModel::InitialExec) {
1754 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1755 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1759 setUsesTOCBasePtr(DAG);
1760 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1761 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1762 PtrVT, GOTReg, TGA);
1764 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1765 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1766 PtrVT, TGA, GOTPtr);
1767 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1770 if (Model == TLSModel::GeneralDynamic) {
1771 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1775 setUsesTOCBasePtr(DAG);
1776 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1777 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1780 if (picLevel == PICLevel::Small)
1781 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1783 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1785 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1787 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1788 return CallResult.first;
1791 if (Model == TLSModel::LocalDynamic) {
1792 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1796 setUsesTOCBasePtr(DAG);
1797 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1798 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1801 if (picLevel == PICLevel::Small)
1802 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1804 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1806 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1808 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1809 SDValue TLSAddr = CallResult.first;
1810 SDValue Chain = CallResult.second;
1811 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1812 Chain, TLSAddr, TGA);
1813 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1816 llvm_unreachable("Unknown TLS model!");
1819 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1820 SelectionDAG &DAG) const {
1821 EVT PtrVT = Op.getValueType();
1822 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1824 const GlobalValue *GV = GSDN->getGlobal();
1826 // 64-bit SVR4 ABI code is always position-independent.
1827 // The actual address of the GlobalValue is stored in the TOC.
1828 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1829 setUsesTOCBasePtr(DAG);
1830 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1831 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1832 DAG.getRegister(PPC::X2, MVT::i64));
1835 unsigned MOHiFlag, MOLoFlag;
1837 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
1839 if (isPIC && Subtarget.isSVR4ABI()) {
1840 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1842 PPCII::MO_PIC_FLAG);
1843 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1844 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1848 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1850 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1852 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1854 // If the global reference is actually to a non-lazy-pointer, we have to do an
1855 // extra load to get the address of the global.
1856 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1857 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1858 false, false, false, 0);
1862 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1863 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1866 if (Op.getValueType() == MVT::v2i64) {
1867 // When the operands themselves are v2i64 values, we need to do something
1868 // special because VSX has no underlying comparison operations for these.
1869 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1870 // Equality can be handled by casting to the legal type for Altivec
1871 // comparisons, everything else needs to be expanded.
1872 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1873 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1874 DAG.getSetCC(dl, MVT::v4i32,
1875 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1876 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1883 // We handle most of these in the usual way.
1887 // If we're comparing for equality to zero, expose the fact that this is
1888 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1889 // fold the new nodes.
1890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1891 if (C->isNullValue() && CC == ISD::SETEQ) {
1892 EVT VT = Op.getOperand(0).getValueType();
1893 SDValue Zext = Op.getOperand(0);
1894 if (VT.bitsLT(MVT::i32)) {
1896 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1898 unsigned Log2b = Log2_32(VT.getSizeInBits());
1899 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1900 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1901 DAG.getConstant(Log2b, MVT::i32));
1902 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1904 // Leave comparisons against 0 and -1 alone for now, since they're usually
1905 // optimized. FIXME: revisit this when we can custom lower all setcc
1907 if (C->isAllOnesValue() || C->isNullValue())
1911 // If we have an integer seteq/setne, turn it into a compare against zero
1912 // by xor'ing the rhs with the lhs, which is faster than setting a
1913 // condition register, reading it back out, and masking the correct bit. The
1914 // normal approach here uses sub to do this instead of xor. Using xor exposes
1915 // the result to other bit-twiddling opportunities.
1916 EVT LHSVT = Op.getOperand(0).getValueType();
1917 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1918 EVT VT = Op.getValueType();
1919 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1921 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1926 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1927 const PPCSubtarget &Subtarget) const {
1928 SDNode *Node = Op.getNode();
1929 EVT VT = Node->getValueType(0);
1930 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1931 SDValue InChain = Node->getOperand(0);
1932 SDValue VAListPtr = Node->getOperand(1);
1933 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1936 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1939 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1940 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1941 false, false, false, 0);
1942 InChain = GprIndex.getValue(1);
1944 if (VT == MVT::i64) {
1945 // Check if GprIndex is even
1946 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1947 DAG.getConstant(1, MVT::i32));
1948 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1949 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1950 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1951 DAG.getConstant(1, MVT::i32));
1952 // Align GprIndex to be even if it isn't
1953 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1957 // fpr index is 1 byte after gpr
1958 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1959 DAG.getConstant(1, MVT::i32));
1962 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1963 FprPtr, MachinePointerInfo(SV), MVT::i8,
1964 false, false, false, 0);
1965 InChain = FprIndex.getValue(1);
1967 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1968 DAG.getConstant(8, MVT::i32));
1970 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1971 DAG.getConstant(4, MVT::i32));
1974 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1975 MachinePointerInfo(), false, false,
1977 InChain = OverflowArea.getValue(1);
1979 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1980 MachinePointerInfo(), false, false,
1982 InChain = RegSaveArea.getValue(1);
1984 // select overflow_area if index > 8
1985 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1986 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1988 // adjustment constant gpr_index * 4/8
1989 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1990 VT.isInteger() ? GprIndex : FprIndex,
1991 DAG.getConstant(VT.isInteger() ? 4 : 8,
1994 // OurReg = RegSaveArea + RegConstant
1995 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1998 // Floating types are 32 bytes into RegSaveArea
1999 if (VT.isFloatingPoint())
2000 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2001 DAG.getConstant(32, MVT::i32));
2003 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2004 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2005 VT.isInteger() ? GprIndex : FprIndex,
2006 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2009 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2010 VT.isInteger() ? VAListPtr : FprPtr,
2011 MachinePointerInfo(SV),
2012 MVT::i8, false, false, 0);
2014 // determine if we should load from reg_save_area or overflow_area
2015 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2017 // increase overflow_area by 4/8 if gpr/fpr > 8
2018 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2019 DAG.getConstant(VT.isInteger() ? 4 : 8,
2022 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2025 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2027 MachinePointerInfo(),
2028 MVT::i32, false, false, 0);
2030 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2031 false, false, false, 0);
2034 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2035 const PPCSubtarget &Subtarget) const {
2036 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2038 // We have to copy the entire va_list struct:
2039 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2040 return DAG.getMemcpy(Op.getOperand(0), Op,
2041 Op.getOperand(1), Op.getOperand(2),
2042 DAG.getConstant(12, MVT::i32), 8, false, true,
2043 MachinePointerInfo(), MachinePointerInfo());
2046 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2047 SelectionDAG &DAG) const {
2048 return Op.getOperand(0);
2051 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2052 SelectionDAG &DAG) const {
2053 SDValue Chain = Op.getOperand(0);
2054 SDValue Trmp = Op.getOperand(1); // trampoline
2055 SDValue FPtr = Op.getOperand(2); // nested function
2056 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2059 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2060 bool isPPC64 = (PtrVT == MVT::i64);
2062 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2065 TargetLowering::ArgListTy Args;
2066 TargetLowering::ArgListEntry Entry;
2068 Entry.Ty = IntPtrTy;
2069 Entry.Node = Trmp; Args.push_back(Entry);
2071 // TrampSize == (isPPC64 ? 48 : 40);
2072 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2073 isPPC64 ? MVT::i64 : MVT::i32);
2074 Args.push_back(Entry);
2076 Entry.Node = FPtr; Args.push_back(Entry);
2077 Entry.Node = Nest; Args.push_back(Entry);
2079 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2080 TargetLowering::CallLoweringInfo CLI(DAG);
2081 CLI.setDebugLoc(dl).setChain(Chain)
2082 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2083 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2084 std::move(Args), 0);
2086 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2087 return CallResult.second;
2090 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2091 const PPCSubtarget &Subtarget) const {
2092 MachineFunction &MF = DAG.getMachineFunction();
2093 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2097 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2098 // vastart just stores the address of the VarArgsFrameIndex slot into the
2099 // memory location argument.
2100 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2101 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2102 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2103 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2104 MachinePointerInfo(SV),
2108 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2109 // We suppose the given va_list is already allocated.
2112 // char gpr; /* index into the array of 8 GPRs
2113 // * stored in the register save area
2114 // * gpr=0 corresponds to r3,
2115 // * gpr=1 to r4, etc.
2117 // char fpr; /* index into the array of 8 FPRs
2118 // * stored in the register save area
2119 // * fpr=0 corresponds to f1,
2120 // * fpr=1 to f2, etc.
2122 // char *overflow_arg_area;
2123 // /* location on stack that holds
2124 // * the next overflow argument
2126 // char *reg_save_area;
2127 // /* where r3:r10 and f1:f8 (if saved)
2133 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2134 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2137 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2139 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2141 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2144 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2145 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2147 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2148 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2150 uint64_t FPROffset = 1;
2151 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2153 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2155 // Store first byte : number of int regs
2156 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2158 MachinePointerInfo(SV),
2159 MVT::i8, false, false, 0);
2160 uint64_t nextOffset = FPROffset;
2161 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2164 // Store second byte : number of float regs
2165 SDValue secondStore =
2166 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2167 MachinePointerInfo(SV, nextOffset), MVT::i8,
2169 nextOffset += StackOffset;
2170 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2172 // Store second word : arguments given on stack
2173 SDValue thirdStore =
2174 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2175 MachinePointerInfo(SV, nextOffset),
2177 nextOffset += FrameOffset;
2178 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2180 // Store third word : arguments given in registers
2181 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2182 MachinePointerInfo(SV, nextOffset),
2187 #include "PPCGenCallingConv.inc"
2189 // Function whose sole purpose is to kill compiler warnings
2190 // stemming from unused functions included from PPCGenCallingConv.inc.
2191 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2192 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2195 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2196 CCValAssign::LocInfo &LocInfo,
2197 ISD::ArgFlagsTy &ArgFlags,
2202 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2204 CCValAssign::LocInfo &LocInfo,
2205 ISD::ArgFlagsTy &ArgFlags,
2207 static const MCPhysReg ArgRegs[] = {
2208 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2209 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2211 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2213 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2215 // Skip one register if the first unallocated register has an even register
2216 // number and there are still argument registers available which have not been
2217 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2218 // need to skip a register if RegNum is odd.
2219 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2220 State.AllocateReg(ArgRegs[RegNum]);
2223 // Always return false here, as this function only makes sure that the first
2224 // unallocated register has an odd register number and does not actually
2225 // allocate a register for the current argument.
2229 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2231 CCValAssign::LocInfo &LocInfo,
2232 ISD::ArgFlagsTy &ArgFlags,
2234 static const MCPhysReg ArgRegs[] = {
2235 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2239 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2241 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2243 // If there is only one Floating-point register left we need to put both f64
2244 // values of a split ppc_fp128 value on the stack.
2245 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2246 State.AllocateReg(ArgRegs[RegNum]);
2249 // Always return false here, as this function only makes sure that the two f64
2250 // values a ppc_fp128 value is split into are both passed in registers or both
2251 // passed on the stack and does not actually allocate a register for the
2252 // current argument.
2256 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2258 static const MCPhysReg *GetFPR() {
2259 static const MCPhysReg FPR[] = {
2260 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2261 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2267 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2269 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2270 unsigned PtrByteSize) {
2271 unsigned ArgSize = ArgVT.getStoreSize();
2272 if (Flags.isByVal())
2273 ArgSize = Flags.getByValSize();
2275 // Round up to multiples of the pointer size, except for array members,
2276 // which are always packed.
2277 if (!Flags.isInConsecutiveRegs())
2278 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2283 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2285 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2286 ISD::ArgFlagsTy Flags,
2287 unsigned PtrByteSize) {
2288 unsigned Align = PtrByteSize;
2290 // Altivec parameters are padded to a 16 byte boundary.
2291 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2292 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2293 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2296 // ByVal parameters are aligned as requested.
2297 if (Flags.isByVal()) {
2298 unsigned BVAlign = Flags.getByValAlign();
2299 if (BVAlign > PtrByteSize) {
2300 if (BVAlign % PtrByteSize != 0)
2302 "ByVal alignment is not a multiple of the pointer size");
2308 // Array members are always packed to their original alignment.
2309 if (Flags.isInConsecutiveRegs()) {
2310 // If the array member was split into multiple registers, the first
2311 // needs to be aligned to the size of the full type. (Except for
2312 // ppcf128, which is only aligned as its f64 components.)
2313 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2314 Align = OrigVT.getStoreSize();
2316 Align = ArgVT.getStoreSize();
2322 /// CalculateStackSlotUsed - Return whether this argument will use its
2323 /// stack slot (instead of being passed in registers). ArgOffset,
2324 /// AvailableFPRs, and AvailableVRs must hold the current argument
2325 /// position, and will be updated to account for this argument.
2326 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2327 ISD::ArgFlagsTy Flags,
2328 unsigned PtrByteSize,
2329 unsigned LinkageSize,
2330 unsigned ParamAreaSize,
2331 unsigned &ArgOffset,
2332 unsigned &AvailableFPRs,
2333 unsigned &AvailableVRs) {
2334 bool UseMemory = false;
2336 // Respect alignment of argument on the stack.
2338 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2339 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2340 // If there's no space left in the argument save area, we must
2341 // use memory (this check also catches zero-sized arguments).
2342 if (ArgOffset >= LinkageSize + ParamAreaSize)
2345 // Allocate argument on the stack.
2346 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2347 if (Flags.isInConsecutiveRegsLast())
2348 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2349 // If we overran the argument save area, we must use memory
2350 // (this check catches arguments passed partially in memory)
2351 if (ArgOffset > LinkageSize + ParamAreaSize)
2354 // However, if the argument is actually passed in an FPR or a VR,
2355 // we don't use memory after all.
2356 if (!Flags.isByVal()) {
2357 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2358 if (AvailableFPRs > 0) {
2362 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2363 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2364 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2365 if (AvailableVRs > 0) {
2374 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2375 /// ensure minimum alignment required for target.
2376 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2377 unsigned NumBytes) {
2378 unsigned TargetAlign = Lowering->getStackAlignment();
2379 unsigned AlignMask = TargetAlign - 1;
2380 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2385 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2386 CallingConv::ID CallConv, bool isVarArg,
2387 const SmallVectorImpl<ISD::InputArg>
2389 SDLoc dl, SelectionDAG &DAG,
2390 SmallVectorImpl<SDValue> &InVals)
2392 if (Subtarget.isSVR4ABI()) {
2393 if (Subtarget.isPPC64())
2394 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2397 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2400 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2406 PPCTargetLowering::LowerFormalArguments_32SVR4(
2408 CallingConv::ID CallConv, bool isVarArg,
2409 const SmallVectorImpl<ISD::InputArg>
2411 SDLoc dl, SelectionDAG &DAG,
2412 SmallVectorImpl<SDValue> &InVals) const {
2414 // 32-bit SVR4 ABI Stack Frame Layout:
2415 // +-----------------------------------+
2416 // +--> | Back chain |
2417 // | +-----------------------------------+
2418 // | | Floating-point register save area |
2419 // | +-----------------------------------+
2420 // | | General register save area |
2421 // | +-----------------------------------+
2422 // | | CR save word |
2423 // | +-----------------------------------+
2424 // | | VRSAVE save word |
2425 // | +-----------------------------------+
2426 // | | Alignment padding |
2427 // | +-----------------------------------+
2428 // | | Vector register save area |
2429 // | +-----------------------------------+
2430 // | | Local variable space |
2431 // | +-----------------------------------+
2432 // | | Parameter list area |
2433 // | +-----------------------------------+
2434 // | | LR save word |
2435 // | +-----------------------------------+
2436 // SP--> +--- | Back chain |
2437 // +-----------------------------------+
2440 // System V Application Binary Interface PowerPC Processor Supplement
2441 // AltiVec Technology Programming Interface Manual
2443 MachineFunction &MF = DAG.getMachineFunction();
2444 MachineFrameInfo *MFI = MF.getFrameInfo();
2445 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2447 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2448 // Potential tail calls could cause overwriting of argument stack slots.
2449 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2450 (CallConv == CallingConv::Fast));
2451 unsigned PtrByteSize = 4;
2453 // Assign locations to all of the incoming arguments.
2454 SmallVector<CCValAssign, 16> ArgLocs;
2455 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2458 // Reserve space for the linkage area on the stack.
2459 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2460 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2462 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2464 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2465 CCValAssign &VA = ArgLocs[i];
2467 // Arguments stored in registers.
2468 if (VA.isRegLoc()) {
2469 const TargetRegisterClass *RC;
2470 EVT ValVT = VA.getValVT();
2472 switch (ValVT.getSimpleVT().SimpleTy) {
2474 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2477 RC = &PPC::GPRCRegClass;
2480 RC = &PPC::F4RCRegClass;
2483 if (Subtarget.hasVSX())
2484 RC = &PPC::VSFRCRegClass;
2486 RC = &PPC::F8RCRegClass;
2492 RC = &PPC::VRRCRegClass;
2496 RC = &PPC::VSHRCRegClass;
2500 // Transform the arguments stored in physical registers into virtual ones.
2501 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2502 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2503 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2505 if (ValVT == MVT::i1)
2506 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2508 InVals.push_back(ArgValue);
2510 // Argument stored in memory.
2511 assert(VA.isMemLoc());
2513 unsigned ArgSize = VA.getLocVT().getStoreSize();
2514 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2517 // Create load nodes to retrieve arguments from the stack.
2518 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2519 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2520 MachinePointerInfo(),
2521 false, false, false, 0));
2525 // Assign locations to all of the incoming aggregate by value arguments.
2526 // Aggregates passed by value are stored in the local variable space of the
2527 // caller's stack frame, right above the parameter list area.
2528 SmallVector<CCValAssign, 16> ByValArgLocs;
2529 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2530 ByValArgLocs, *DAG.getContext());
2532 // Reserve stack space for the allocations in CCInfo.
2533 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2535 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2537 // Area that is at least reserved in the caller of this function.
2538 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2539 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2541 // Set the size that is at least reserved in caller of this function. Tail
2542 // call optimized function's reserved stack space needs to be aligned so that
2543 // taking the difference between two stack areas will result in an aligned
2546 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2547 FuncInfo->setMinReservedArea(MinReservedArea);
2549 SmallVector<SDValue, 8> MemOps;
2551 // If the function takes variable number of arguments, make a frame index for
2552 // the start of the first vararg value... for expansion of llvm.va_start.
2554 static const MCPhysReg GPArgRegs[] = {
2555 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2556 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2558 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2560 static const MCPhysReg FPArgRegs[] = {
2561 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2564 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2565 if (DisablePPCFloatInVariadic)
2568 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2570 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2573 // Make room for NumGPArgRegs and NumFPArgRegs.
2574 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2575 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2577 FuncInfo->setVarArgsStackOffset(
2578 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2579 CCInfo.getNextStackOffset(), true));
2581 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2582 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2584 // The fixed integer arguments of a variadic function are stored to the
2585 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2586 // the result of va_next.
2587 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2588 // Get an existing live-in vreg, or add a new one.
2589 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2591 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2593 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2594 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2595 MachinePointerInfo(), false, false, 0);
2596 MemOps.push_back(Store);
2597 // Increment the address by four for the next argument to store
2598 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2599 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2602 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2604 // The double arguments are stored to the VarArgsFrameIndex
2606 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2607 // Get an existing live-in vreg, or add a new one.
2608 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2610 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2612 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2613 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2614 MachinePointerInfo(), false, false, 0);
2615 MemOps.push_back(Store);
2616 // Increment the address by eight for the next argument to store
2617 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2619 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2623 if (!MemOps.empty())
2624 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2629 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2630 // value to MVT::i64 and then truncate to the correct register size.
2632 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2633 SelectionDAG &DAG, SDValue ArgVal,
2636 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2637 DAG.getValueType(ObjectVT));
2638 else if (Flags.isZExt())
2639 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2640 DAG.getValueType(ObjectVT));
2642 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2646 PPCTargetLowering::LowerFormalArguments_64SVR4(
2648 CallingConv::ID CallConv, bool isVarArg,
2649 const SmallVectorImpl<ISD::InputArg>
2651 SDLoc dl, SelectionDAG &DAG,
2652 SmallVectorImpl<SDValue> &InVals) const {
2653 // TODO: add description of PPC stack frame format, or at least some docs.
2655 bool isELFv2ABI = Subtarget.isELFv2ABI();
2656 bool isLittleEndian = Subtarget.isLittleEndian();
2657 MachineFunction &MF = DAG.getMachineFunction();
2658 MachineFrameInfo *MFI = MF.getFrameInfo();
2659 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2661 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2662 "fastcc not supported on varargs functions");
2664 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2665 // Potential tail calls could cause overwriting of argument stack slots.
2666 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2667 (CallConv == CallingConv::Fast));
2668 unsigned PtrByteSize = 8;
2670 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2673 static const MCPhysReg GPR[] = {
2674 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2675 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2678 static const MCPhysReg *FPR = GetFPR();
2680 static const MCPhysReg VR[] = {
2681 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2682 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2684 static const MCPhysReg VSRH[] = {
2685 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2686 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2689 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2690 const unsigned Num_FPR_Regs = 13;
2691 const unsigned Num_VR_Regs = array_lengthof(VR);
2693 // Do a first pass over the arguments to determine whether the ABI
2694 // guarantees that our caller has allocated the parameter save area
2695 // on its stack frame. In the ELFv1 ABI, this is always the case;
2696 // in the ELFv2 ABI, it is true if this is a vararg function or if
2697 // any parameter is located in a stack slot.
2699 bool HasParameterArea = !isELFv2ABI || isVarArg;
2700 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2701 unsigned NumBytes = LinkageSize;
2702 unsigned AvailableFPRs = Num_FPR_Regs;
2703 unsigned AvailableVRs = Num_VR_Regs;
2704 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2705 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2706 PtrByteSize, LinkageSize, ParamAreaSize,
2707 NumBytes, AvailableFPRs, AvailableVRs))
2708 HasParameterArea = true;
2710 // Add DAG nodes to load the arguments or copy them out of registers. On
2711 // entry to a function on PPC, the arguments start after the linkage area,
2712 // although the first ones are often in registers.
2714 unsigned ArgOffset = LinkageSize;
2715 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2716 SmallVector<SDValue, 8> MemOps;
2717 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2718 unsigned CurArgIdx = 0;
2719 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2721 bool needsLoad = false;
2722 EVT ObjectVT = Ins[ArgNo].VT;
2723 EVT OrigVT = Ins[ArgNo].ArgVT;
2724 unsigned ObjSize = ObjectVT.getStoreSize();
2725 unsigned ArgSize = ObjSize;
2726 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2727 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2728 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2730 // We re-align the argument offset for each argument, except when using the
2731 // fast calling convention, when we need to make sure we do that only when
2732 // we'll actually use a stack slot.
2733 unsigned CurArgOffset, Align;
2734 auto ComputeArgOffset = [&]() {
2735 /* Respect alignment of argument on the stack. */
2736 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2737 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2738 CurArgOffset = ArgOffset;
2741 if (CallConv != CallingConv::Fast) {
2744 /* Compute GPR index associated with argument offset. */
2745 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2746 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2749 // FIXME the codegen can be much improved in some cases.
2750 // We do not have to keep everything in memory.
2751 if (Flags.isByVal()) {
2752 if (CallConv == CallingConv::Fast)
2755 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2756 ObjSize = Flags.getByValSize();
2757 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2758 // Empty aggregate parameters do not take up registers. Examples:
2762 // etc. However, we have to provide a place-holder in InVals, so
2763 // pretend we have an 8-byte item at the current address for that
2766 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2767 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2768 InVals.push_back(FIN);
2772 // Create a stack object covering all stack doublewords occupied
2773 // by the argument. If the argument is (fully or partially) on
2774 // the stack, or if the argument is fully in registers but the
2775 // caller has allocated the parameter save anyway, we can refer
2776 // directly to the caller's stack frame. Otherwise, create a
2777 // local copy in our own frame.
2779 if (HasParameterArea ||
2780 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2781 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2783 FI = MFI->CreateStackObject(ArgSize, Align, false);
2784 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2786 // Handle aggregates smaller than 8 bytes.
2787 if (ObjSize < PtrByteSize) {
2788 // The value of the object is its address, which differs from the
2789 // address of the enclosing doubleword on big-endian systems.
2791 if (!isLittleEndian) {
2792 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2793 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2795 InVals.push_back(Arg);
2797 if (GPR_idx != Num_GPR_Regs) {
2798 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2799 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2802 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2803 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2804 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2805 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2806 MachinePointerInfo(FuncArg),
2807 ObjType, false, false, 0);
2809 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2810 // store the whole register as-is to the parameter save area
2812 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2813 MachinePointerInfo(FuncArg),
2817 MemOps.push_back(Store);
2819 // Whether we copied from a register or not, advance the offset
2820 // into the parameter save area by a full doubleword.
2821 ArgOffset += PtrByteSize;
2825 // The value of the object is its address, which is the address of
2826 // its first stack doubleword.
2827 InVals.push_back(FIN);
2829 // Store whatever pieces of the object are in registers to memory.
2830 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2831 if (GPR_idx == Num_GPR_Regs)
2834 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2835 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2838 SDValue Off = DAG.getConstant(j, PtrVT);
2839 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2841 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2842 MachinePointerInfo(FuncArg, j),
2844 MemOps.push_back(Store);
2847 ArgOffset += ArgSize;
2851 switch (ObjectVT.getSimpleVT().SimpleTy) {
2852 default: llvm_unreachable("Unhandled argument type!");
2856 // These can be scalar arguments or elements of an integer array type
2857 // passed directly. Clang may use those instead of "byval" aggregate
2858 // types to avoid forcing arguments to memory unnecessarily.
2859 if (GPR_idx != Num_GPR_Regs) {
2860 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2861 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2863 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2864 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2865 // value to MVT::i64 and then truncate to the correct register size.
2866 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2868 if (CallConv == CallingConv::Fast)
2872 ArgSize = PtrByteSize;
2874 if (CallConv != CallingConv::Fast || needsLoad)
2880 // These can be scalar arguments or elements of a float array type
2881 // passed directly. The latter are used to implement ELFv2 homogenous
2882 // float aggregates.
2883 if (FPR_idx != Num_FPR_Regs) {
2886 if (ObjectVT == MVT::f32)
2887 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2889 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
2890 ? &PPC::VSFRCRegClass
2891 : &PPC::F8RCRegClass);
2893 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2895 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
2896 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
2897 // once we support fp <-> gpr moves.
2899 // This can only ever happen in the presence of f32 array types,
2900 // since otherwise we never run out of FPRs before running out
2902 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2903 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2905 if (ObjectVT == MVT::f32) {
2906 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2907 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2908 DAG.getConstant(32, MVT::i32));
2909 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2912 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2914 if (CallConv == CallingConv::Fast)
2920 // When passing an array of floats, the array occupies consecutive
2921 // space in the argument area; only round up to the next doubleword
2922 // at the end of the array. Otherwise, each float takes 8 bytes.
2923 if (CallConv != CallingConv::Fast || needsLoad) {
2924 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2925 ArgOffset += ArgSize;
2926 if (Flags.isInConsecutiveRegsLast())
2927 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2936 // These can be scalar arguments or elements of a vector array type
2937 // passed directly. The latter are used to implement ELFv2 homogenous
2938 // vector aggregates.
2939 if (VR_idx != Num_VR_Regs) {
2940 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2941 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2942 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2943 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2946 if (CallConv == CallingConv::Fast)
2951 if (CallConv != CallingConv::Fast || needsLoad)
2956 // We need to load the argument to a virtual register if we determined
2957 // above that we ran out of physical registers of the appropriate type.
2959 if (ObjSize < ArgSize && !isLittleEndian)
2960 CurArgOffset += ArgSize - ObjSize;
2961 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2962 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2963 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2964 false, false, false, 0);
2967 InVals.push_back(ArgVal);
2970 // Area that is at least reserved in the caller of this function.
2971 unsigned MinReservedArea;
2972 if (HasParameterArea)
2973 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2975 MinReservedArea = LinkageSize;
2977 // Set the size that is at least reserved in caller of this function. Tail
2978 // call optimized functions' reserved stack space needs to be aligned so that
2979 // taking the difference between two stack areas will result in an aligned
2982 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2983 FuncInfo->setMinReservedArea(MinReservedArea);
2985 // If the function takes variable number of arguments, make a frame index for
2986 // the start of the first vararg value... for expansion of llvm.va_start.
2988 int Depth = ArgOffset;
2990 FuncInfo->setVarArgsFrameIndex(
2991 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2992 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2994 // If this function is vararg, store any remaining integer argument regs
2995 // to their spots on the stack so that they may be loaded by deferencing the
2996 // result of va_next.
2997 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2998 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2999 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3000 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3001 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3002 MachinePointerInfo(), false, false, 0);
3003 MemOps.push_back(Store);
3004 // Increment the address by four for the next argument to store
3005 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3006 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3010 if (!MemOps.empty())
3011 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3017 PPCTargetLowering::LowerFormalArguments_Darwin(
3019 CallingConv::ID CallConv, bool isVarArg,
3020 const SmallVectorImpl<ISD::InputArg>
3022 SDLoc dl, SelectionDAG &DAG,
3023 SmallVectorImpl<SDValue> &InVals) const {
3024 // TODO: add description of PPC stack frame format, or at least some docs.
3026 MachineFunction &MF = DAG.getMachineFunction();
3027 MachineFrameInfo *MFI = MF.getFrameInfo();
3028 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3030 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3031 bool isPPC64 = PtrVT == MVT::i64;
3032 // Potential tail calls could cause overwriting of argument stack slots.
3033 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3034 (CallConv == CallingConv::Fast));
3035 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3037 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
3039 unsigned ArgOffset = LinkageSize;
3040 // Area that is at least reserved in caller of this function.
3041 unsigned MinReservedArea = ArgOffset;
3043 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3044 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3045 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3047 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3048 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3049 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3052 static const MCPhysReg *FPR = GetFPR();
3054 static const MCPhysReg VR[] = {
3055 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3056 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3059 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3060 const unsigned Num_FPR_Regs = 13;
3061 const unsigned Num_VR_Regs = array_lengthof( VR);
3063 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3065 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3067 // In 32-bit non-varargs functions, the stack space for vectors is after the
3068 // stack space for non-vectors. We do not use this space unless we have
3069 // too many vectors to fit in registers, something that only occurs in
3070 // constructed examples:), but we have to walk the arglist to figure
3071 // that out...for the pathological case, compute VecArgOffset as the
3072 // start of the vector parameter area. Computing VecArgOffset is the
3073 // entire point of the following loop.
3074 unsigned VecArgOffset = ArgOffset;
3075 if (!isVarArg && !isPPC64) {
3076 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3078 EVT ObjectVT = Ins[ArgNo].VT;
3079 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3081 if (Flags.isByVal()) {
3082 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3083 unsigned ObjSize = Flags.getByValSize();
3085 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3086 VecArgOffset += ArgSize;
3090 switch(ObjectVT.getSimpleVT().SimpleTy) {
3091 default: llvm_unreachable("Unhandled argument type!");
3097 case MVT::i64: // PPC64
3099 // FIXME: We are guaranteed to be !isPPC64 at this point.
3100 // Does MVT::i64 apply?
3107 // Nothing to do, we're only looking at Nonvector args here.
3112 // We've found where the vector parameter area in memory is. Skip the
3113 // first 12 parameters; these don't use that memory.
3114 VecArgOffset = ((VecArgOffset+15)/16)*16;
3115 VecArgOffset += 12*16;
3117 // Add DAG nodes to load the arguments or copy them out of registers. On
3118 // entry to a function on PPC, the arguments start after the linkage area,
3119 // although the first ones are often in registers.
3121 SmallVector<SDValue, 8> MemOps;
3122 unsigned nAltivecParamsAtEnd = 0;
3123 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3124 unsigned CurArgIdx = 0;
3125 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3127 bool needsLoad = false;
3128 EVT ObjectVT = Ins[ArgNo].VT;
3129 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3130 unsigned ArgSize = ObjSize;
3131 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3132 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3133 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3135 unsigned CurArgOffset = ArgOffset;
3137 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3138 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3139 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3140 if (isVarArg || isPPC64) {
3141 MinReservedArea = ((MinReservedArea+15)/16)*16;
3142 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3145 } else nAltivecParamsAtEnd++;
3147 // Calculate min reserved area.
3148 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3152 // FIXME the codegen can be much improved in some cases.
3153 // We do not have to keep everything in memory.
3154 if (Flags.isByVal()) {
3155 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3156 ObjSize = Flags.getByValSize();
3157 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3158 // Objects of size 1 and 2 are right justified, everything else is
3159 // left justified. This means the memory address is adjusted forwards.
3160 if (ObjSize==1 || ObjSize==2) {
3161 CurArgOffset = CurArgOffset + (4 - ObjSize);
3163 // The value of the object is its address.
3164 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3165 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3166 InVals.push_back(FIN);
3167 if (ObjSize==1 || ObjSize==2) {
3168 if (GPR_idx != Num_GPR_Regs) {
3171 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3173 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3174 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3175 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3176 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3177 MachinePointerInfo(FuncArg),
3178 ObjType, false, false, 0);
3179 MemOps.push_back(Store);
3183 ArgOffset += PtrByteSize;
3187 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3188 // Store whatever pieces of the object are in registers
3189 // to memory. ArgOffset will be the address of the beginning
3191 if (GPR_idx != Num_GPR_Regs) {
3194 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3196 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3197 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3198 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3199 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3200 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3201 MachinePointerInfo(FuncArg, j),
3203 MemOps.push_back(Store);
3205 ArgOffset += PtrByteSize;
3207 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3214 switch (ObjectVT.getSimpleVT().SimpleTy) {
3215 default: llvm_unreachable("Unhandled argument type!");
3219 if (GPR_idx != Num_GPR_Regs) {
3220 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3221 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3223 if (ObjectVT == MVT::i1)
3224 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3229 ArgSize = PtrByteSize;
3231 // All int arguments reserve stack space in the Darwin ABI.
3232 ArgOffset += PtrByteSize;
3236 case MVT::i64: // PPC64
3237 if (GPR_idx != Num_GPR_Regs) {
3238 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3239 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3241 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3242 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3243 // value to MVT::i64 and then truncate to the correct register size.
3244 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3249 ArgSize = PtrByteSize;
3251 // All int arguments reserve stack space in the Darwin ABI.
3257 // Every 4 bytes of argument space consumes one of the GPRs available for
3258 // argument passing.
3259 if (GPR_idx != Num_GPR_Regs) {
3261 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3264 if (FPR_idx != Num_FPR_Regs) {
3267 if (ObjectVT == MVT::f32)
3268 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3270 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3272 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3278 // All FP arguments reserve stack space in the Darwin ABI.
3279 ArgOffset += isPPC64 ? 8 : ObjSize;
3285 // Note that vector arguments in registers don't reserve stack space,
3286 // except in varargs functions.
3287 if (VR_idx != Num_VR_Regs) {
3288 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3289 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3291 while ((ArgOffset % 16) != 0) {
3292 ArgOffset += PtrByteSize;
3293 if (GPR_idx != Num_GPR_Regs)
3297 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3301 if (!isVarArg && !isPPC64) {
3302 // Vectors go after all the nonvectors.
3303 CurArgOffset = VecArgOffset;
3306 // Vectors are aligned.
3307 ArgOffset = ((ArgOffset+15)/16)*16;
3308 CurArgOffset = ArgOffset;
3316 // We need to load the argument to a virtual register if we determined above
3317 // that we ran out of physical registers of the appropriate type.
3319 int FI = MFI->CreateFixedObject(ObjSize,
3320 CurArgOffset + (ArgSize - ObjSize),
3322 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3323 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3324 false, false, false, 0);
3327 InVals.push_back(ArgVal);
3330 // Allow for Altivec parameters at the end, if needed.
3331 if (nAltivecParamsAtEnd) {
3332 MinReservedArea = ((MinReservedArea+15)/16)*16;
3333 MinReservedArea += 16*nAltivecParamsAtEnd;
3336 // Area that is at least reserved in the caller of this function.
3337 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3339 // Set the size that is at least reserved in caller of this function. Tail
3340 // call optimized functions' reserved stack space needs to be aligned so that
3341 // taking the difference between two stack areas will result in an aligned
3344 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3345 FuncInfo->setMinReservedArea(MinReservedArea);
3347 // If the function takes variable number of arguments, make a frame index for
3348 // the start of the first vararg value... for expansion of llvm.va_start.
3350 int Depth = ArgOffset;
3352 FuncInfo->setVarArgsFrameIndex(
3353 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3355 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3357 // If this function is vararg, store any remaining integer argument regs
3358 // to their spots on the stack so that they may be loaded by deferencing the
3359 // result of va_next.
3360 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3364 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3366 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3368 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3369 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3370 MachinePointerInfo(), false, false, 0);
3371 MemOps.push_back(Store);
3372 // Increment the address by four for the next argument to store
3373 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3374 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3378 if (!MemOps.empty())
3379 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3384 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3385 /// adjusted to accommodate the arguments for the tailcall.
3386 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3387 unsigned ParamSize) {
3389 if (!isTailCall) return 0;
3391 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3392 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3393 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3394 // Remember only if the new adjustement is bigger.
3395 if (SPDiff < FI->getTailCallSPDelta())
3396 FI->setTailCallSPDelta(SPDiff);
3401 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3402 /// for tail call optimization. Targets which want to do tail call
3403 /// optimization should implement this function.
3405 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3406 CallingConv::ID CalleeCC,
3408 const SmallVectorImpl<ISD::InputArg> &Ins,
3409 SelectionDAG& DAG) const {
3410 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3413 // Variable argument functions are not supported.
3417 MachineFunction &MF = DAG.getMachineFunction();
3418 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3419 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3420 // Functions containing by val parameters are not supported.
3421 for (unsigned i = 0; i != Ins.size(); i++) {
3422 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3423 if (Flags.isByVal()) return false;
3426 // Non-PIC/GOT tail calls are supported.
3427 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3430 // At the moment we can only do local tail calls (in same module, hidden
3431 // or protected) if we are generating PIC.
3432 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3433 return G->getGlobal()->hasHiddenVisibility()
3434 || G->getGlobal()->hasProtectedVisibility();
3440 /// isCallCompatibleAddress - Return the immediate to use if the specified
3441 /// 32-bit value is representable in the immediate field of a BxA instruction.
3442 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3443 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3444 if (!C) return nullptr;
3446 int Addr = C->getZExtValue();
3447 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3448 SignExtend32<26>(Addr) != Addr)
3449 return nullptr; // Top 6 bits have to be sext of immediate.
3451 return DAG.getConstant((int)C->getZExtValue() >> 2,
3452 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3457 struct TailCallArgumentInfo {
3462 TailCallArgumentInfo() : FrameIdx(0) {}
3467 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3469 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3471 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3472 SmallVectorImpl<SDValue> &MemOpChains,
3474 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3475 SDValue Arg = TailCallArgs[i].Arg;
3476 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3477 int FI = TailCallArgs[i].FrameIdx;
3478 // Store relative to framepointer.
3479 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3480 MachinePointerInfo::getFixedStack(FI),
3485 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3486 /// the appropriate stack slot for the tail call optimized function call.
3487 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3488 MachineFunction &MF,
3497 // Calculate the new stack slot for the return address.
3498 int SlotSize = isPPC64 ? 8 : 4;
3499 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3501 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3502 NewRetAddrLoc, true);
3503 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3504 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3505 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3506 MachinePointerInfo::getFixedStack(NewRetAddr),
3509 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3510 // slot as the FP is never overwritten.
3513 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3514 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3516 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3517 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3518 MachinePointerInfo::getFixedStack(NewFPIdx),
3525 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3526 /// the position of the argument.
3528 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3529 SDValue Arg, int SPDiff, unsigned ArgOffset,
3530 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3531 int Offset = ArgOffset + SPDiff;
3532 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3533 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3534 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3535 SDValue FIN = DAG.getFrameIndex(FI, VT);
3536 TailCallArgumentInfo Info;
3538 Info.FrameIdxOp = FIN;
3540 TailCallArguments.push_back(Info);
3543 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3544 /// stack slot. Returns the chain as result and the loaded frame pointers in
3545 /// LROpOut/FPOpout. Used when tail calling.
3546 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3554 // Load the LR and FP stack slot for later adjusting.
3555 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3556 LROpOut = getReturnAddrFrameIndex(DAG);
3557 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3558 false, false, false, 0);
3559 Chain = SDValue(LROpOut.getNode(), 1);
3561 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3562 // slot as the FP is never overwritten.
3564 FPOpOut = getFramePointerFrameIndex(DAG);
3565 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3566 false, false, false, 0);
3567 Chain = SDValue(FPOpOut.getNode(), 1);
3573 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3574 /// by "Src" to address "Dst" of size "Size". Alignment information is
3575 /// specified by the specific parameter attribute. The copy will be passed as
3576 /// a byval function parameter.
3577 /// Sometimes what we are copying is the end of a larger object, the part that
3578 /// does not fit in registers.
3580 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3581 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3583 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3584 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3585 false, false, MachinePointerInfo(),
3586 MachinePointerInfo());
3589 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3592 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3593 SDValue Arg, SDValue PtrOff, int SPDiff,
3594 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3595 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3596 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3598 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3603 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3605 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3606 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3607 DAG.getConstant(ArgOffset, PtrVT));
3609 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3610 MachinePointerInfo(), false, false, 0));
3611 // Calculate and remember argument location.
3612 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3617 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3618 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3619 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3620 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3621 MachineFunction &MF = DAG.getMachineFunction();
3623 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3624 // might overwrite each other in case of tail call optimization.
3625 SmallVector<SDValue, 8> MemOpChains2;
3626 // Do not flag preceding copytoreg stuff together with the following stuff.
3628 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3630 if (!MemOpChains2.empty())
3631 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3633 // Store the return address to the appropriate stack slot.
3634 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3635 isPPC64, isDarwinABI, dl);
3637 // Emit callseq_end just before tailcall node.
3638 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3639 DAG.getIntPtrConstant(0, true), InFlag, dl);
3640 InFlag = Chain.getValue(1);
3643 // Is this global address that of a function that can be called by name? (as
3644 // opposed to something that must hold a descriptor for an indirect call).
3645 static bool isFunctionGlobalAddress(SDValue Callee) {
3646 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3647 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3648 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3651 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3658 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3659 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3660 bool isTailCall, bool IsPatchPoint,
3661 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3662 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3663 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3665 bool isPPC64 = Subtarget.isPPC64();
3666 bool isSVR4ABI = Subtarget.isSVR4ABI();
3667 bool isELFv2ABI = Subtarget.isELFv2ABI();
3669 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3670 NodeTys.push_back(MVT::Other); // Returns a chain
3671 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3673 unsigned CallOpc = PPCISD::CALL;
3675 bool needIndirectCall = true;
3676 if (!isSVR4ABI || !isPPC64)
3677 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3678 // If this is an absolute destination address, use the munged value.
3679 Callee = SDValue(Dest, 0);
3680 needIndirectCall = false;
3683 if (isFunctionGlobalAddress(Callee)) {
3684 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3685 // A call to a TLS address is actually an indirect call to a
3686 // thread-specific pointer.
3687 unsigned OpFlags = 0;
3688 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3689 (Subtarget.getTargetTriple().isMacOSX() &&
3690 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3691 (G->getGlobal()->isDeclaration() ||
3692 G->getGlobal()->isWeakForLinker())) ||
3693 (Subtarget.isTargetELF() && !isPPC64 &&
3694 !G->getGlobal()->hasLocalLinkage() &&
3695 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3696 // PC-relative references to external symbols should go through $stub,
3697 // unless we're building with the leopard linker or later, which
3698 // automatically synthesizes these stubs.
3699 OpFlags = PPCII::MO_PLT_OR_STUB;
3702 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3703 // every direct call is) turn it into a TargetGlobalAddress /
3704 // TargetExternalSymbol node so that legalize doesn't hack it.
3705 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3706 Callee.getValueType(), 0, OpFlags);
3707 needIndirectCall = false;
3710 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3711 unsigned char OpFlags = 0;
3713 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3714 (Subtarget.getTargetTriple().isMacOSX() &&
3715 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3716 (Subtarget.isTargetELF() && !isPPC64 &&
3717 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3718 // PC-relative references to external symbols should go through $stub,
3719 // unless we're building with the leopard linker or later, which
3720 // automatically synthesizes these stubs.
3721 OpFlags = PPCII::MO_PLT_OR_STUB;
3724 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3726 needIndirectCall = false;
3730 // We'll form an invalid direct call when lowering a patchpoint; the full
3731 // sequence for an indirect call is complicated, and many of the
3732 // instructions introduced might have side effects (and, thus, can't be
3733 // removed later). The call itself will be removed as soon as the
3734 // argument/return lowering is complete, so the fact that it has the wrong
3735 // kind of operands should not really matter.
3736 needIndirectCall = false;
3739 if (needIndirectCall) {
3740 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3741 // to do the call, we can't use PPCISD::CALL.
3742 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3744 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3745 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3746 // entry point, but to the function descriptor (the function entry point
3747 // address is part of the function descriptor though).
3748 // The function descriptor is a three doubleword structure with the
3749 // following fields: function entry point, TOC base address and
3750 // environment pointer.
3751 // Thus for a call through a function pointer, the following actions need
3753 // 1. Save the TOC of the caller in the TOC save area of its stack
3754 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3755 // 2. Load the address of the function entry point from the function
3757 // 3. Load the TOC of the callee from the function descriptor into r2.
3758 // 4. Load the environment pointer from the function descriptor into
3760 // 5. Branch to the function entry point address.
3761 // 6. On return of the callee, the TOC of the caller needs to be
3762 // restored (this is done in FinishCall()).
3764 // The loads are scheduled at the beginning of the call sequence, and the
3765 // register copies are flagged together to ensure that no other
3766 // operations can be scheduled in between. E.g. without flagging the
3767 // copies together, a TOC access in the caller could be scheduled between
3768 // the assignment of the callee TOC and the branch to the callee, which
3769 // results in the TOC access going through the TOC of the callee instead
3770 // of going through the TOC of the caller, which leads to incorrect code.
3772 // Load the address of the function entry point from the function
3774 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
3775 if (LDChain.getValueType() == MVT::Glue)
3776 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
3778 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
3780 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
3781 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
3782 false, false, LoadsInv, 8);
3784 // Load environment pointer into r11.
3785 SDValue PtrOff = DAG.getIntPtrConstant(16);
3786 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3787 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
3788 MPI.getWithOffset(16), false, false,
3791 SDValue TOCOff = DAG.getIntPtrConstant(8);
3792 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3793 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
3794 MPI.getWithOffset(8), false, false,
3797 setUsesTOCBasePtr(DAG);
3798 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
3800 Chain = TOCVal.getValue(0);
3801 InFlag = TOCVal.getValue(1);
3803 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3806 Chain = EnvVal.getValue(0);
3807 InFlag = EnvVal.getValue(1);
3809 MTCTROps[0] = Chain;
3810 MTCTROps[1] = LoadFuncPtr;
3811 MTCTROps[2] = InFlag;
3814 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3815 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3816 InFlag = Chain.getValue(1);
3819 NodeTys.push_back(MVT::Other);
3820 NodeTys.push_back(MVT::Glue);
3821 Ops.push_back(Chain);
3822 CallOpc = PPCISD::BCTRL;
3823 Callee.setNode(nullptr);
3824 // Add use of X11 (holding environment pointer)
3825 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3826 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3827 // Add CTR register as callee so a bctr can be emitted later.
3829 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3832 // If this is a direct call, pass the chain and the callee.
3833 if (Callee.getNode()) {
3834 Ops.push_back(Chain);
3835 Ops.push_back(Callee);
3837 // If this is a call to __tls_get_addr, find the symbol whose address
3838 // is to be taken and add it to the list. This will be used to
3839 // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3840 // We find the symbol by walking the chain to the CopyFromReg, walking
3841 // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3842 // pulling the symbol from that node.
3843 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3844 if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3845 assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3846 SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3847 SDValue TGTAddr = AddI->getOperand(1);
3848 assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3849 "Didn't find target global TLS address where we expected one");
3850 Ops.push_back(TGTAddr);
3851 CallOpc = PPCISD::CALL_TLS;
3854 // If this is a tail call add stack pointer delta.
3856 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3858 // Add argument registers to the end of the list so that they are known live
3860 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3861 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3862 RegsToPass[i].second.getValueType()));
3864 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
3866 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
3867 setUsesTOCBasePtr(DAG);
3868 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3875 bool isLocalCall(const SDValue &Callee)
3877 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3878 return !G->getGlobal()->isDeclaration() &&
3879 !G->getGlobal()->isWeakForLinker();
3884 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3885 CallingConv::ID CallConv, bool isVarArg,
3886 const SmallVectorImpl<ISD::InputArg> &Ins,
3887 SDLoc dl, SelectionDAG &DAG,
3888 SmallVectorImpl<SDValue> &InVals) const {
3890 SmallVector<CCValAssign, 16> RVLocs;
3891 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3893 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3895 // Copy all of the result registers out of their specified physreg.
3896 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3897 CCValAssign &VA = RVLocs[i];
3898 assert(VA.isRegLoc() && "Can only return in registers!");
3900 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3901 VA.getLocReg(), VA.getLocVT(), InFlag);
3902 Chain = Val.getValue(1);
3903 InFlag = Val.getValue(2);
3905 switch (VA.getLocInfo()) {
3906 default: llvm_unreachable("Unknown loc info!");
3907 case CCValAssign::Full: break;
3908 case CCValAssign::AExt:
3909 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3911 case CCValAssign::ZExt:
3912 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3913 DAG.getValueType(VA.getValVT()));
3914 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3916 case CCValAssign::SExt:
3917 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3918 DAG.getValueType(VA.getValVT()));
3919 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3923 InVals.push_back(Val);
3930 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3931 bool isTailCall, bool isVarArg, bool IsPatchPoint,
3933 SmallVector<std::pair<unsigned, SDValue>, 8>
3935 SDValue InFlag, SDValue Chain,
3936 SDValue CallSeqStart, SDValue &Callee,
3937 int SPDiff, unsigned NumBytes,
3938 const SmallVectorImpl<ISD::InputArg> &Ins,
3939 SmallVectorImpl<SDValue> &InVals,
3940 ImmutableCallSite *CS) const {
3942 bool isELFv2ABI = Subtarget.isELFv2ABI();
3943 std::vector<EVT> NodeTys;
3944 SmallVector<SDValue, 8> Ops;
3945 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
3946 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
3947 Ops, NodeTys, CS, Subtarget);
3949 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3950 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3951 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3953 // When performing tail call optimization the callee pops its arguments off
3954 // the stack. Account for this here so these bytes can be pushed back on in
3955 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3956 int BytesCalleePops =
3957 (CallConv == CallingConv::Fast &&
3958 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3960 // Add a register mask operand representing the call-preserved registers.
3961 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3962 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3963 assert(Mask && "Missing call preserved mask for calling convention");
3964 Ops.push_back(DAG.getRegisterMask(Mask));
3966 if (InFlag.getNode())
3967 Ops.push_back(InFlag);
3971 assert(((Callee.getOpcode() == ISD::Register &&
3972 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3973 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3974 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3975 isa<ConstantSDNode>(Callee)) &&
3976 "Expecting an global address, external symbol, absolute value or register");
3978 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3981 // Add a NOP immediately after the branch instruction when using the 64-bit
3982 // SVR4 ABI. At link time, if caller and callee are in a different module and
3983 // thus have a different TOC, the call will be replaced with a call to a stub
3984 // function which saves the current TOC, loads the TOC of the callee and
3985 // branches to the callee. The NOP will be replaced with a load instruction
3986 // which restores the TOC of the caller from the TOC save slot of the current
3987 // stack frame. If caller and callee belong to the same module (and have the
3988 // same TOC), the NOP will remain unchanged.
3990 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
3992 if (CallOpc == PPCISD::BCTRL) {
3993 // This is a call through a function pointer.
3994 // Restore the caller TOC from the save area into R2.
3995 // See PrepareCall() for more information about calls through function
3996 // pointers in the 64-bit SVR4 ABI.
3997 // We are using a target-specific load with r2 hard coded, because the
3998 // result of a target-independent load would never go directly into r2,
3999 // since r2 is a reserved register (which prevents the register allocator
4000 // from allocating it), resulting in an additional register being
4001 // allocated and an unnecessary move instruction being generated.
4002 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4004 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4005 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4006 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4007 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4008 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4010 // The address needs to go after the chain input but before the flag (or
4011 // any other variadic arguments).
4012 Ops.insert(std::next(Ops.begin()), AddTOC);
4013 } else if ((CallOpc == PPCISD::CALL) &&
4014 (!isLocalCall(Callee) ||
4015 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4016 // Otherwise insert NOP for non-local calls.
4017 CallOpc = PPCISD::CALL_NOP;
4018 } else if (CallOpc == PPCISD::CALL_TLS)
4019 // For 64-bit SVR4, TLS calls are always non-local.
4020 CallOpc = PPCISD::CALL_NOP_TLS;
4023 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4024 InFlag = Chain.getValue(1);
4026 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4027 DAG.getIntPtrConstant(BytesCalleePops, true),
4030 InFlag = Chain.getValue(1);
4032 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4033 Ins, dl, DAG, InVals);
4037 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4038 SmallVectorImpl<SDValue> &InVals) const {
4039 SelectionDAG &DAG = CLI.DAG;
4041 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4042 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4043 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4044 SDValue Chain = CLI.Chain;
4045 SDValue Callee = CLI.Callee;
4046 bool &isTailCall = CLI.IsTailCall;
4047 CallingConv::ID CallConv = CLI.CallConv;
4048 bool isVarArg = CLI.IsVarArg;
4049 bool IsPatchPoint = CLI.IsPatchPoint;
4050 ImmutableCallSite *CS = CLI.CS;
4053 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4056 if (!isTailCall && CS && CS->isMustTailCall())
4057 report_fatal_error("failed to perform tail call elimination on a call "
4058 "site marked musttail");
4060 if (Subtarget.isSVR4ABI()) {
4061 if (Subtarget.isPPC64())
4062 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4063 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4064 dl, DAG, InVals, CS);
4066 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4067 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4068 dl, DAG, InVals, CS);
4071 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4072 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4073 dl, DAG, InVals, CS);
4077 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4078 CallingConv::ID CallConv, bool isVarArg,
4079 bool isTailCall, bool IsPatchPoint,
4080 const SmallVectorImpl<ISD::OutputArg> &Outs,
4081 const SmallVectorImpl<SDValue> &OutVals,
4082 const SmallVectorImpl<ISD::InputArg> &Ins,
4083 SDLoc dl, SelectionDAG &DAG,
4084 SmallVectorImpl<SDValue> &InVals,
4085 ImmutableCallSite *CS) const {
4086 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4087 // of the 32-bit SVR4 ABI stack frame layout.
4089 assert((CallConv == CallingConv::C ||
4090 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4092 unsigned PtrByteSize = 4;
4094 MachineFunction &MF = DAG.getMachineFunction();
4096 // Mark this function as potentially containing a function that contains a
4097 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4098 // and restoring the callers stack pointer in this functions epilog. This is
4099 // done because by tail calling the called function might overwrite the value
4100 // in this function's (MF) stack pointer stack slot 0(SP).
4101 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4102 CallConv == CallingConv::Fast)
4103 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4105 // Count how many bytes are to be pushed on the stack, including the linkage
4106 // area, parameter list area and the part of the local variable space which
4107 // contains copies of aggregates which are passed by value.
4109 // Assign locations to all of the outgoing arguments.
4110 SmallVector<CCValAssign, 16> ArgLocs;
4111 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4114 // Reserve space for the linkage area on the stack.
4115 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4119 // Handle fixed and variable vector arguments differently.
4120 // Fixed vector arguments go into registers as long as registers are
4121 // available. Variable vector arguments always go into memory.
4122 unsigned NumArgs = Outs.size();
4124 for (unsigned i = 0; i != NumArgs; ++i) {
4125 MVT ArgVT = Outs[i].VT;
4126 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4129 if (Outs[i].IsFixed) {
4130 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4133 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4139 errs() << "Call operand #" << i << " has unhandled type "
4140 << EVT(ArgVT).getEVTString() << "\n";
4142 llvm_unreachable(nullptr);
4146 // All arguments are treated the same.
4147 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4150 // Assign locations to all of the outgoing aggregate by value arguments.
4151 SmallVector<CCValAssign, 16> ByValArgLocs;
4152 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4153 ByValArgLocs, *DAG.getContext());
4155 // Reserve stack space for the allocations in CCInfo.
4156 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4158 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4160 // Size of the linkage area, parameter list area and the part of the local
4161 // space variable where copies of aggregates which are passed by value are
4163 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4165 // Calculate by how many bytes the stack has to be adjusted in case of tail
4166 // call optimization.
4167 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4169 // Adjust the stack pointer for the new arguments...
4170 // These operations are automatically eliminated by the prolog/epilog pass
4171 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4173 SDValue CallSeqStart = Chain;
4175 // Load the return address and frame pointer so it can be moved somewhere else
4178 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4181 // Set up a copy of the stack pointer for use loading and storing any
4182 // arguments that may not fit in the registers available for argument
4184 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4186 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4187 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4188 SmallVector<SDValue, 8> MemOpChains;
4190 bool seenFloatArg = false;
4191 // Walk the register/memloc assignments, inserting copies/loads.
4192 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4195 CCValAssign &VA = ArgLocs[i];
4196 SDValue Arg = OutVals[i];
4197 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4199 if (Flags.isByVal()) {
4200 // Argument is an aggregate which is passed by value, thus we need to
4201 // create a copy of it in the local variable space of the current stack
4202 // frame (which is the stack frame of the caller) and pass the address of
4203 // this copy to the callee.
4204 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4205 CCValAssign &ByValVA = ByValArgLocs[j++];
4206 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4208 // Memory reserved in the local variable space of the callers stack frame.
4209 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4211 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4212 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4214 // Create a copy of the argument in the local area of the current
4216 SDValue MemcpyCall =
4217 CreateCopyOfByValArgument(Arg, PtrOff,
4218 CallSeqStart.getNode()->getOperand(0),
4221 // This must go outside the CALLSEQ_START..END.
4222 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4223 CallSeqStart.getNode()->getOperand(1),
4225 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4226 NewCallSeqStart.getNode());
4227 Chain = CallSeqStart = NewCallSeqStart;
4229 // Pass the address of the aggregate copy on the stack either in a
4230 // physical register or in the parameter list area of the current stack
4231 // frame to the callee.
4235 if (VA.isRegLoc()) {
4236 if (Arg.getValueType() == MVT::i1)
4237 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4239 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4240 // Put argument in a physical register.
4241 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4243 // Put argument in the parameter list area of the current stack frame.
4244 assert(VA.isMemLoc());
4245 unsigned LocMemOffset = VA.getLocMemOffset();
4248 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4249 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4251 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4252 MachinePointerInfo(),
4255 // Calculate and remember argument location.
4256 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4262 if (!MemOpChains.empty())
4263 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4265 // Build a sequence of copy-to-reg nodes chained together with token chain
4266 // and flag operands which copy the outgoing args into the appropriate regs.
4268 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4269 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4270 RegsToPass[i].second, InFlag);
4271 InFlag = Chain.getValue(1);
4274 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4277 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4278 SDValue Ops[] = { Chain, InFlag };
4280 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4281 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4283 InFlag = Chain.getValue(1);
4287 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4288 false, TailCallArguments);
4290 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4291 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4292 NumBytes, Ins, InVals, CS);
4295 // Copy an argument into memory, being careful to do this outside the
4296 // call sequence for the call to which the argument belongs.
4298 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4299 SDValue CallSeqStart,
4300 ISD::ArgFlagsTy Flags,
4303 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4304 CallSeqStart.getNode()->getOperand(0),
4306 // The MEMCPY must go outside the CALLSEQ_START..END.
4307 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4308 CallSeqStart.getNode()->getOperand(1),
4310 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4311 NewCallSeqStart.getNode());
4312 return NewCallSeqStart;
4316 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4317 CallingConv::ID CallConv, bool isVarArg,
4318 bool isTailCall, bool IsPatchPoint,
4319 const SmallVectorImpl<ISD::OutputArg> &Outs,
4320 const SmallVectorImpl<SDValue> &OutVals,
4321 const SmallVectorImpl<ISD::InputArg> &Ins,
4322 SDLoc dl, SelectionDAG &DAG,
4323 SmallVectorImpl<SDValue> &InVals,
4324 ImmutableCallSite *CS) const {
4326 bool isELFv2ABI = Subtarget.isELFv2ABI();
4327 bool isLittleEndian = Subtarget.isLittleEndian();
4328 unsigned NumOps = Outs.size();
4330 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4331 unsigned PtrByteSize = 8;
4333 MachineFunction &MF = DAG.getMachineFunction();
4335 // Mark this function as potentially containing a function that contains a
4336 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4337 // and restoring the callers stack pointer in this functions epilog. This is
4338 // done because by tail calling the called function might overwrite the value
4339 // in this function's (MF) stack pointer stack slot 0(SP).
4340 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4341 CallConv == CallingConv::Fast)
4342 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4344 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4345 "fastcc not supported on varargs functions");
4347 // Count how many bytes are to be pushed on the stack, including the linkage
4348 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4349 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4350 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4351 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4353 unsigned NumBytes = LinkageSize;
4354 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4356 static const MCPhysReg GPR[] = {
4357 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4358 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4360 static const MCPhysReg *FPR = GetFPR();
4362 static const MCPhysReg VR[] = {
4363 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4364 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4366 static const MCPhysReg VSRH[] = {
4367 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4368 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4371 const unsigned NumGPRs = array_lengthof(GPR);
4372 const unsigned NumFPRs = 13;
4373 const unsigned NumVRs = array_lengthof(VR);
4375 // When using the fast calling convention, we don't provide backing for
4376 // arguments that will be in registers.
4377 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4379 // Add up all the space actually used.
4380 for (unsigned i = 0; i != NumOps; ++i) {
4381 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4382 EVT ArgVT = Outs[i].VT;
4383 EVT OrigVT = Outs[i].ArgVT;
4385 if (CallConv == CallingConv::Fast) {
4386 if (Flags.isByVal())
4387 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4389 switch (ArgVT.getSimpleVT().SimpleTy) {
4390 default: llvm_unreachable("Unexpected ValueType for argument!");
4394 if (++NumGPRsUsed <= NumGPRs)
4399 if (++NumFPRsUsed <= NumFPRs)
4408 if (++NumVRsUsed <= NumVRs)
4414 /* Respect alignment of argument on the stack. */
4416 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4417 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4419 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4420 if (Flags.isInConsecutiveRegsLast())
4421 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4424 unsigned NumBytesActuallyUsed = NumBytes;
4426 // The prolog code of the callee may store up to 8 GPR argument registers to
4427 // the stack, allowing va_start to index over them in memory if its varargs.
4428 // Because we cannot tell if this is needed on the caller side, we have to
4429 // conservatively assume that it is needed. As such, make sure we have at
4430 // least enough stack space for the caller to store the 8 GPRs.
4431 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4432 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4434 // Tail call needs the stack to be aligned.
4435 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4436 CallConv == CallingConv::Fast)
4437 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4439 // Calculate by how many bytes the stack has to be adjusted in case of tail
4440 // call optimization.
4441 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4443 // To protect arguments on the stack from being clobbered in a tail call,
4444 // force all the loads to happen before doing any other lowering.
4446 Chain = DAG.getStackArgumentTokenFactor(Chain);
4448 // Adjust the stack pointer for the new arguments...
4449 // These operations are automatically eliminated by the prolog/epilog pass
4450 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4452 SDValue CallSeqStart = Chain;
4454 // Load the return address and frame pointer so it can be move somewhere else
4457 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4460 // Set up a copy of the stack pointer for use loading and storing any
4461 // arguments that may not fit in the registers available for argument
4463 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4465 // Figure out which arguments are going to go in registers, and which in
4466 // memory. Also, if this is a vararg function, floating point operations
4467 // must be stored to our stack, and loaded into integer regs as well, if
4468 // any integer regs are available for argument passing.
4469 unsigned ArgOffset = LinkageSize;
4471 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4472 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4474 SmallVector<SDValue, 8> MemOpChains;
4475 for (unsigned i = 0; i != NumOps; ++i) {
4476 SDValue Arg = OutVals[i];
4477 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4478 EVT ArgVT = Outs[i].VT;
4479 EVT OrigVT = Outs[i].ArgVT;
4481 // PtrOff will be used to store the current argument to the stack if a
4482 // register cannot be found for it.
4485 // We re-align the argument offset for each argument, except when using the
4486 // fast calling convention, when we need to make sure we do that only when
4487 // we'll actually use a stack slot.
4488 auto ComputePtrOff = [&]() {
4489 /* Respect alignment of argument on the stack. */
4491 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4492 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4494 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4496 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4499 if (CallConv != CallingConv::Fast) {
4502 /* Compute GPR index associated with argument offset. */
4503 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4504 GPR_idx = std::min(GPR_idx, NumGPRs);
4507 // Promote integers to 64-bit values.
4508 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4509 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4510 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4511 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4514 // FIXME memcpy is used way more than necessary. Correctness first.
4515 // Note: "by value" is code for passing a structure by value, not
4517 if (Flags.isByVal()) {
4518 // Note: Size includes alignment padding, so
4519 // struct x { short a; char b; }
4520 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4521 // These are the proper values we need for right-justifying the
4522 // aggregate in a parameter register.
4523 unsigned Size = Flags.getByValSize();
4525 // An empty aggregate parameter takes up no storage and no
4530 if (CallConv == CallingConv::Fast)
4533 // All aggregates smaller than 8 bytes must be passed right-justified.
4534 if (Size==1 || Size==2 || Size==4) {
4535 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4536 if (GPR_idx != NumGPRs) {
4537 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4538 MachinePointerInfo(), VT,
4539 false, false, false, 0);
4540 MemOpChains.push_back(Load.getValue(1));
4541 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4543 ArgOffset += PtrByteSize;
4548 if (GPR_idx == NumGPRs && Size < 8) {
4549 SDValue AddPtr = PtrOff;
4550 if (!isLittleEndian) {
4551 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4552 PtrOff.getValueType());
4553 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4555 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4558 ArgOffset += PtrByteSize;
4561 // Copy entire object into memory. There are cases where gcc-generated
4562 // code assumes it is there, even if it could be put entirely into
4563 // registers. (This is not what the doc says.)
4565 // FIXME: The above statement is likely due to a misunderstanding of the
4566 // documents. All arguments must be copied into the parameter area BY
4567 // THE CALLEE in the event that the callee takes the address of any
4568 // formal argument. That has not yet been implemented. However, it is
4569 // reasonable to use the stack area as a staging area for the register
4572 // Skip this for small aggregates, as we will use the same slot for a
4573 // right-justified copy, below.
4575 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4579 // When a register is available, pass a small aggregate right-justified.
4580 if (Size < 8 && GPR_idx != NumGPRs) {
4581 // The easiest way to get this right-justified in a register
4582 // is to copy the structure into the rightmost portion of a
4583 // local variable slot, then load the whole slot into the
4585 // FIXME: The memcpy seems to produce pretty awful code for
4586 // small aggregates, particularly for packed ones.
4587 // FIXME: It would be preferable to use the slot in the
4588 // parameter save area instead of a new local variable.
4589 SDValue AddPtr = PtrOff;
4590 if (!isLittleEndian) {
4591 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4592 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4594 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4598 // Load the slot into the register.
4599 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4600 MachinePointerInfo(),
4601 false, false, false, 0);
4602 MemOpChains.push_back(Load.getValue(1));
4603 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4605 // Done with this argument.
4606 ArgOffset += PtrByteSize;
4610 // For aggregates larger than PtrByteSize, copy the pieces of the
4611 // object that fit into registers from the parameter save area.
4612 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4613 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4614 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4615 if (GPR_idx != NumGPRs) {
4616 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4617 MachinePointerInfo(),
4618 false, false, false, 0);
4619 MemOpChains.push_back(Load.getValue(1));
4620 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4621 ArgOffset += PtrByteSize;
4623 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4630 switch (Arg.getSimpleValueType().SimpleTy) {
4631 default: llvm_unreachable("Unexpected ValueType for argument!");
4635 // These can be scalar arguments or elements of an integer array type
4636 // passed directly. Clang may use those instead of "byval" aggregate
4637 // types to avoid forcing arguments to memory unnecessarily.
4638 if (GPR_idx != NumGPRs) {
4639 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4641 if (CallConv == CallingConv::Fast)
4644 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4645 true, isTailCall, false, MemOpChains,
4646 TailCallArguments, dl);
4647 if (CallConv == CallingConv::Fast)
4648 ArgOffset += PtrByteSize;
4650 if (CallConv != CallingConv::Fast)
4651 ArgOffset += PtrByteSize;
4655 // These can be scalar arguments or elements of a float array type
4656 // passed directly. The latter are used to implement ELFv2 homogenous
4657 // float aggregates.
4659 // Named arguments go into FPRs first, and once they overflow, the
4660 // remaining arguments go into GPRs and then the parameter save area.
4661 // Unnamed arguments for vararg functions always go to GPRs and
4662 // then the parameter save area. For now, put all arguments to vararg
4663 // routines always in both locations (FPR *and* GPR or stack slot).
4664 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4665 bool NeededLoad = false;
4667 // First load the argument into the next available FPR.
4668 if (FPR_idx != NumFPRs)
4669 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4671 // Next, load the argument into GPR or stack slot if needed.
4672 if (!NeedGPROrStack)
4674 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4675 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4676 // once we support fp <-> gpr moves.
4678 // In the non-vararg case, this can only ever happen in the
4679 // presence of f32 array types, since otherwise we never run
4680 // out of FPRs before running out of GPRs.
4683 // Double values are always passed in a single GPR.
4684 if (Arg.getValueType() != MVT::f32) {
4685 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4687 // Non-array float values are extended and passed in a GPR.
4688 } else if (!Flags.isInConsecutiveRegs()) {
4689 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4690 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4692 // If we have an array of floats, we collect every odd element
4693 // together with its predecessor into one GPR.
4694 } else if (ArgOffset % PtrByteSize != 0) {
4696 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4697 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4698 if (!isLittleEndian)
4700 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4702 // The final element, if even, goes into the first half of a GPR.
4703 } else if (Flags.isInConsecutiveRegsLast()) {
4704 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4705 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4706 if (!isLittleEndian)
4707 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4708 DAG.getConstant(32, MVT::i32));
4710 // Non-final even elements are skipped; they will be handled
4711 // together the with subsequent argument on the next go-around.
4715 if (ArgVal.getNode())
4716 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4718 if (CallConv == CallingConv::Fast)
4721 // Single-precision floating-point values are mapped to the
4722 // second (rightmost) word of the stack doubleword.
4723 if (Arg.getValueType() == MVT::f32 &&
4724 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4725 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4726 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4729 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4730 true, isTailCall, false, MemOpChains,
4731 TailCallArguments, dl);
4735 // When passing an array of floats, the array occupies consecutive
4736 // space in the argument area; only round up to the next doubleword
4737 // at the end of the array. Otherwise, each float takes 8 bytes.
4738 if (CallConv != CallingConv::Fast || NeededLoad) {
4739 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4740 Flags.isInConsecutiveRegs()) ? 4 : 8;
4741 if (Flags.isInConsecutiveRegsLast())
4742 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4752 // These can be scalar arguments or elements of a vector array type
4753 // passed directly. The latter are used to implement ELFv2 homogenous
4754 // vector aggregates.
4756 // For a varargs call, named arguments go into VRs or on the stack as
4757 // usual; unnamed arguments always go to the stack or the corresponding
4758 // GPRs when within range. For now, we always put the value in both
4759 // locations (or even all three).
4761 // We could elide this store in the case where the object fits
4762 // entirely in R registers. Maybe later.
4763 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4764 MachinePointerInfo(), false, false, 0);
4765 MemOpChains.push_back(Store);
4766 if (VR_idx != NumVRs) {
4767 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4768 MachinePointerInfo(),
4769 false, false, false, 0);
4770 MemOpChains.push_back(Load.getValue(1));
4772 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4773 Arg.getSimpleValueType() == MVT::v2i64) ?
4774 VSRH[VR_idx] : VR[VR_idx];
4777 RegsToPass.push_back(std::make_pair(VReg, Load));
4780 for (unsigned i=0; i<16; i+=PtrByteSize) {
4781 if (GPR_idx == NumGPRs)
4783 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4784 DAG.getConstant(i, PtrVT));
4785 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4786 false, false, false, 0);
4787 MemOpChains.push_back(Load.getValue(1));
4788 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4793 // Non-varargs Altivec params go into VRs or on the stack.
4794 if (VR_idx != NumVRs) {
4795 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4796 Arg.getSimpleValueType() == MVT::v2i64) ?
4797 VSRH[VR_idx] : VR[VR_idx];
4800 RegsToPass.push_back(std::make_pair(VReg, Arg));
4802 if (CallConv == CallingConv::Fast)
4805 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4806 true, isTailCall, true, MemOpChains,
4807 TailCallArguments, dl);
4808 if (CallConv == CallingConv::Fast)
4812 if (CallConv != CallingConv::Fast)
4818 assert(NumBytesActuallyUsed == ArgOffset);
4819 (void)NumBytesActuallyUsed;
4821 if (!MemOpChains.empty())
4822 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4824 // Check if this is an indirect call (MTCTR/BCTRL).
4825 // See PrepareCall() for more information about calls through function
4826 // pointers in the 64-bit SVR4 ABI.
4827 if (!isTailCall && !IsPatchPoint &&
4828 !isFunctionGlobalAddress(Callee) &&
4829 !isa<ExternalSymbolSDNode>(Callee)) {
4830 // Load r2 into a virtual register and store it to the TOC save area.
4831 setUsesTOCBasePtr(DAG);
4832 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4833 // TOC save area offset.
4834 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4835 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4836 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4837 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
4838 MachinePointerInfo::getStack(TOCSaveOffset),
4840 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4841 // This does not mean the MTCTR instruction must use R12; it's easier
4842 // to model this as an extra parameter, so do that.
4843 if (isELFv2ABI && !IsPatchPoint)
4844 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4847 // Build a sequence of copy-to-reg nodes chained together with token chain
4848 // and flag operands which copy the outgoing args into the appropriate regs.
4850 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4851 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4852 RegsToPass[i].second, InFlag);
4853 InFlag = Chain.getValue(1);
4857 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4858 FPOp, true, TailCallArguments);
4860 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4861 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4862 NumBytes, Ins, InVals, CS);
4866 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4867 CallingConv::ID CallConv, bool isVarArg,
4868 bool isTailCall, bool IsPatchPoint,
4869 const SmallVectorImpl<ISD::OutputArg> &Outs,
4870 const SmallVectorImpl<SDValue> &OutVals,
4871 const SmallVectorImpl<ISD::InputArg> &Ins,
4872 SDLoc dl, SelectionDAG &DAG,
4873 SmallVectorImpl<SDValue> &InVals,
4874 ImmutableCallSite *CS) const {
4876 unsigned NumOps = Outs.size();
4878 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4879 bool isPPC64 = PtrVT == MVT::i64;
4880 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4882 MachineFunction &MF = DAG.getMachineFunction();
4884 // Mark this function as potentially containing a function that contains a
4885 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4886 // and restoring the callers stack pointer in this functions epilog. This is
4887 // done because by tail calling the called function might overwrite the value
4888 // in this function's (MF) stack pointer stack slot 0(SP).
4889 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4890 CallConv == CallingConv::Fast)
4891 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4893 // Count how many bytes are to be pushed on the stack, including the linkage
4894 // area, and parameter passing area. We start with 24/48 bytes, which is
4895 // prereserved space for [SP][CR][LR][3 x unused].
4896 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4898 unsigned NumBytes = LinkageSize;
4900 // Add up all the space actually used.
4901 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4902 // they all go in registers, but we must reserve stack space for them for
4903 // possible use by the caller. In varargs or 64-bit calls, parameters are
4904 // assigned stack space in order, with padding so Altivec parameters are
4906 unsigned nAltivecParamsAtEnd = 0;
4907 for (unsigned i = 0; i != NumOps; ++i) {
4908 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4909 EVT ArgVT = Outs[i].VT;
4910 // Varargs Altivec parameters are padded to a 16 byte boundary.
4911 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4912 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4913 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4914 if (!isVarArg && !isPPC64) {
4915 // Non-varargs Altivec parameters go after all the non-Altivec
4916 // parameters; handle those later so we know how much padding we need.
4917 nAltivecParamsAtEnd++;
4920 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4921 NumBytes = ((NumBytes+15)/16)*16;
4923 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4926 // Allow for Altivec parameters at the end, if needed.
4927 if (nAltivecParamsAtEnd) {
4928 NumBytes = ((NumBytes+15)/16)*16;
4929 NumBytes += 16*nAltivecParamsAtEnd;
4932 // The prolog code of the callee may store up to 8 GPR argument registers to
4933 // the stack, allowing va_start to index over them in memory if its varargs.
4934 // Because we cannot tell if this is needed on the caller side, we have to
4935 // conservatively assume that it is needed. As such, make sure we have at
4936 // least enough stack space for the caller to store the 8 GPRs.
4937 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4939 // Tail call needs the stack to be aligned.
4940 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4941 CallConv == CallingConv::Fast)
4942 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4944 // Calculate by how many bytes the stack has to be adjusted in case of tail
4945 // call optimization.
4946 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4948 // To protect arguments on the stack from being clobbered in a tail call,
4949 // force all the loads to happen before doing any other lowering.
4951 Chain = DAG.getStackArgumentTokenFactor(Chain);
4953 // Adjust the stack pointer for the new arguments...
4954 // These operations are automatically eliminated by the prolog/epilog pass
4955 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4957 SDValue CallSeqStart = Chain;
4959 // Load the return address and frame pointer so it can be move somewhere else
4962 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4965 // Set up a copy of the stack pointer for use loading and storing any
4966 // arguments that may not fit in the registers available for argument
4970 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4972 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4974 // Figure out which arguments are going to go in registers, and which in
4975 // memory. Also, if this is a vararg function, floating point operations
4976 // must be stored to our stack, and loaded into integer regs as well, if
4977 // any integer regs are available for argument passing.
4978 unsigned ArgOffset = LinkageSize;
4979 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4981 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4982 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4983 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4985 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4986 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4987 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4989 static const MCPhysReg *FPR = GetFPR();
4991 static const MCPhysReg VR[] = {
4992 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4993 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4995 const unsigned NumGPRs = array_lengthof(GPR_32);
4996 const unsigned NumFPRs = 13;
4997 const unsigned NumVRs = array_lengthof(VR);
4999 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5001 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5002 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5004 SmallVector<SDValue, 8> MemOpChains;
5005 for (unsigned i = 0; i != NumOps; ++i) {
5006 SDValue Arg = OutVals[i];
5007 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5009 // PtrOff will be used to store the current argument to the stack if a
5010 // register cannot be found for it.
5013 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5015 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5017 // On PPC64, promote integers to 64-bit values.
5018 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5019 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5020 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5021 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5024 // FIXME memcpy is used way more than necessary. Correctness first.
5025 // Note: "by value" is code for passing a structure by value, not
5027 if (Flags.isByVal()) {
5028 unsigned Size = Flags.getByValSize();
5029 // Very small objects are passed right-justified. Everything else is
5030 // passed left-justified.
5031 if (Size==1 || Size==2) {
5032 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5033 if (GPR_idx != NumGPRs) {
5034 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5035 MachinePointerInfo(), VT,
5036 false, false, false, 0);
5037 MemOpChains.push_back(Load.getValue(1));
5038 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5040 ArgOffset += PtrByteSize;
5042 SDValue Const = DAG.getConstant(PtrByteSize - Size,
5043 PtrOff.getValueType());
5044 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5045 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5048 ArgOffset += PtrByteSize;
5052 // Copy entire object into memory. There are cases where gcc-generated
5053 // code assumes it is there, even if it could be put entirely into
5054 // registers. (This is not what the doc says.)
5055 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5059 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5060 // copy the pieces of the object that fit into registers from the
5061 // parameter save area.
5062 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5063 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5064 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5065 if (GPR_idx != NumGPRs) {
5066 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
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));
5071 ArgOffset += PtrByteSize;
5073 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5080 switch (Arg.getSimpleValueType().SimpleTy) {
5081 default: llvm_unreachable("Unexpected ValueType for argument!");
5085 if (GPR_idx != NumGPRs) {
5086 if (Arg.getValueType() == MVT::i1)
5087 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5089 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5091 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5092 isPPC64, isTailCall, false, MemOpChains,
5093 TailCallArguments, dl);
5095 ArgOffset += PtrByteSize;
5099 if (FPR_idx != NumFPRs) {
5100 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5103 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5104 MachinePointerInfo(), false, false, 0);
5105 MemOpChains.push_back(Store);
5107 // Float varargs are always shadowed in available integer registers
5108 if (GPR_idx != NumGPRs) {
5109 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5110 MachinePointerInfo(), false, false,
5112 MemOpChains.push_back(Load.getValue(1));
5113 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5115 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5116 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5117 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5118 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5119 MachinePointerInfo(),
5120 false, false, false, 0);
5121 MemOpChains.push_back(Load.getValue(1));
5122 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5125 // If we have any FPRs remaining, we may also have GPRs remaining.
5126 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5128 if (GPR_idx != NumGPRs)
5130 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5131 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5135 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5136 isPPC64, isTailCall, false, MemOpChains,
5137 TailCallArguments, dl);
5141 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5148 // These go aligned on the stack, or in the corresponding R registers
5149 // when within range. The Darwin PPC ABI doc claims they also go in
5150 // V registers; in fact gcc does this only for arguments that are
5151 // prototyped, not for those that match the ... We do it for all
5152 // arguments, seems to work.
5153 while (ArgOffset % 16 !=0) {
5154 ArgOffset += PtrByteSize;
5155 if (GPR_idx != NumGPRs)
5158 // We could elide this store in the case where the object fits
5159 // entirely in R registers. Maybe later.
5160 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5161 DAG.getConstant(ArgOffset, PtrVT));
5162 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5163 MachinePointerInfo(), false, false, 0);
5164 MemOpChains.push_back(Store);
5165 if (VR_idx != NumVRs) {
5166 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5167 MachinePointerInfo(),
5168 false, false, false, 0);
5169 MemOpChains.push_back(Load.getValue(1));
5170 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5173 for (unsigned i=0; i<16; i+=PtrByteSize) {
5174 if (GPR_idx == NumGPRs)
5176 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5177 DAG.getConstant(i, PtrVT));
5178 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5179 false, false, false, 0);
5180 MemOpChains.push_back(Load.getValue(1));
5181 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5186 // Non-varargs Altivec params generally go in registers, but have
5187 // stack space allocated at the end.
5188 if (VR_idx != NumVRs) {
5189 // Doesn't have GPR space allocated.
5190 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5191 } else if (nAltivecParamsAtEnd==0) {
5192 // We are emitting Altivec params in order.
5193 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5194 isPPC64, isTailCall, true, MemOpChains,
5195 TailCallArguments, dl);
5201 // If all Altivec parameters fit in registers, as they usually do,
5202 // they get stack space following the non-Altivec parameters. We
5203 // don't track this here because nobody below needs it.
5204 // If there are more Altivec parameters than fit in registers emit
5206 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5208 // Offset is aligned; skip 1st 12 params which go in V registers.
5209 ArgOffset = ((ArgOffset+15)/16)*16;
5211 for (unsigned i = 0; i != NumOps; ++i) {
5212 SDValue Arg = OutVals[i];
5213 EVT ArgType = Outs[i].VT;
5214 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5215 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5218 // We are emitting Altivec params in order.
5219 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5220 isPPC64, isTailCall, true, MemOpChains,
5221 TailCallArguments, dl);
5228 if (!MemOpChains.empty())
5229 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5231 // On Darwin, R12 must contain the address of an indirect callee. This does
5232 // not mean the MTCTR instruction must use R12; it's easier to model this as
5233 // an extra parameter, so do that.
5235 !isFunctionGlobalAddress(Callee) &&
5236 !isa<ExternalSymbolSDNode>(Callee) &&
5237 !isBLACompatibleAddress(Callee, DAG))
5238 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5239 PPC::R12), Callee));
5241 // Build a sequence of copy-to-reg nodes chained together with token chain
5242 // and flag operands which copy the outgoing args into the appropriate regs.
5244 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5245 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5246 RegsToPass[i].second, InFlag);
5247 InFlag = Chain.getValue(1);
5251 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5252 FPOp, true, TailCallArguments);
5254 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5255 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5256 NumBytes, Ins, InVals, CS);
5260 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5261 MachineFunction &MF, bool isVarArg,
5262 const SmallVectorImpl<ISD::OutputArg> &Outs,
5263 LLVMContext &Context) const {
5264 SmallVector<CCValAssign, 16> RVLocs;
5265 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5266 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5270 PPCTargetLowering::LowerReturn(SDValue Chain,
5271 CallingConv::ID CallConv, bool isVarArg,
5272 const SmallVectorImpl<ISD::OutputArg> &Outs,
5273 const SmallVectorImpl<SDValue> &OutVals,
5274 SDLoc dl, SelectionDAG &DAG) const {
5276 SmallVector<CCValAssign, 16> RVLocs;
5277 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5279 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5282 SmallVector<SDValue, 4> RetOps(1, Chain);
5284 // Copy the result values into the output registers.
5285 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5286 CCValAssign &VA = RVLocs[i];
5287 assert(VA.isRegLoc() && "Can only return in registers!");
5289 SDValue Arg = OutVals[i];
5291 switch (VA.getLocInfo()) {
5292 default: llvm_unreachable("Unknown loc info!");
5293 case CCValAssign::Full: break;
5294 case CCValAssign::AExt:
5295 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5297 case CCValAssign::ZExt:
5298 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5300 case CCValAssign::SExt:
5301 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5305 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5306 Flag = Chain.getValue(1);
5307 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5310 RetOps[0] = Chain; // Update chain.
5312 // Add the flag if we have it.
5314 RetOps.push_back(Flag);
5316 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5319 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5320 const PPCSubtarget &Subtarget) const {
5321 // When we pop the dynamic allocation we need to restore the SP link.
5324 // Get the corect type for pointers.
5325 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5327 // Construct the stack pointer operand.
5328 bool isPPC64 = Subtarget.isPPC64();
5329 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5330 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5332 // Get the operands for the STACKRESTORE.
5333 SDValue Chain = Op.getOperand(0);
5334 SDValue SaveSP = Op.getOperand(1);
5336 // Load the old link SP.
5337 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5338 MachinePointerInfo(),
5339 false, false, false, 0);
5341 // Restore the stack pointer.
5342 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5344 // Store the old link SP.
5345 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5352 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5353 MachineFunction &MF = DAG.getMachineFunction();
5354 bool isPPC64 = Subtarget.isPPC64();
5355 bool isDarwinABI = Subtarget.isDarwinABI();
5356 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5358 // Get current frame pointer save index. The users of this index will be
5359 // primarily DYNALLOC instructions.
5360 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5361 int RASI = FI->getReturnAddrSaveIndex();
5363 // If the frame pointer save index hasn't been defined yet.
5365 // Find out what the fix offset of the frame pointer save area.
5366 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5367 // Allocate the frame index for frame pointer save area.
5368 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5370 FI->setReturnAddrSaveIndex(RASI);
5372 return DAG.getFrameIndex(RASI, PtrVT);
5376 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5377 MachineFunction &MF = DAG.getMachineFunction();
5378 bool isPPC64 = Subtarget.isPPC64();
5379 bool isDarwinABI = Subtarget.isDarwinABI();
5380 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5382 // Get current frame pointer save index. The users of this index will be
5383 // primarily DYNALLOC instructions.
5384 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5385 int FPSI = FI->getFramePointerSaveIndex();
5387 // If the frame pointer save index hasn't been defined yet.
5389 // Find out what the fix offset of the frame pointer save area.
5390 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5393 // Allocate the frame index for frame pointer save area.
5394 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5396 FI->setFramePointerSaveIndex(FPSI);
5398 return DAG.getFrameIndex(FPSI, PtrVT);
5401 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5403 const PPCSubtarget &Subtarget) const {
5405 SDValue Chain = Op.getOperand(0);
5406 SDValue Size = Op.getOperand(1);
5409 // Get the corect type for pointers.
5410 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5412 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5413 DAG.getConstant(0, PtrVT), Size);
5414 // Construct a node for the frame pointer save index.
5415 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5416 // Build a DYNALLOC node.
5417 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5418 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5419 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5422 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5423 SelectionDAG &DAG) const {
5425 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5426 DAG.getVTList(MVT::i32, MVT::Other),
5427 Op.getOperand(0), Op.getOperand(1));
5430 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5431 SelectionDAG &DAG) const {
5433 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5434 Op.getOperand(0), Op.getOperand(1));
5437 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5438 assert(Op.getValueType() == MVT::i1 &&
5439 "Custom lowering only for i1 loads");
5441 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5444 LoadSDNode *LD = cast<LoadSDNode>(Op);
5446 SDValue Chain = LD->getChain();
5447 SDValue BasePtr = LD->getBasePtr();
5448 MachineMemOperand *MMO = LD->getMemOperand();
5450 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5451 BasePtr, MVT::i8, MMO);
5452 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5454 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5455 return DAG.getMergeValues(Ops, dl);
5458 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5459 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5460 "Custom lowering only for i1 stores");
5462 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5465 StoreSDNode *ST = cast<StoreSDNode>(Op);
5467 SDValue Chain = ST->getChain();
5468 SDValue BasePtr = ST->getBasePtr();
5469 SDValue Value = ST->getValue();
5470 MachineMemOperand *MMO = ST->getMemOperand();
5472 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5473 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5476 // FIXME: Remove this once the ANDI glue bug is fixed:
5477 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5478 assert(Op.getValueType() == MVT::i1 &&
5479 "Custom lowering only for i1 results");
5482 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5486 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5488 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5489 // Not FP? Not a fsel.
5490 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5491 !Op.getOperand(2).getValueType().isFloatingPoint())
5494 // We might be able to do better than this under some circumstances, but in
5495 // general, fsel-based lowering of select is a finite-math-only optimization.
5496 // For more information, see section F.3 of the 2.06 ISA specification.
5497 if (!DAG.getTarget().Options.NoInfsFPMath ||
5498 !DAG.getTarget().Options.NoNaNsFPMath)
5501 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5503 EVT ResVT = Op.getValueType();
5504 EVT CmpVT = Op.getOperand(0).getValueType();
5505 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5506 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5509 // If the RHS of the comparison is a 0.0, we don't need to do the
5510 // subtraction at all.
5512 if (isFloatingPointZero(RHS))
5514 default: break; // SETUO etc aren't handled by fsel.
5518 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5519 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5520 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5521 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5522 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5523 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5524 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5527 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5530 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5531 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5532 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5535 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5538 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5539 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5540 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5541 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5546 default: break; // SETUO etc aren't handled by fsel.
5550 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5551 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5552 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5553 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5554 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5555 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5556 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5557 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5560 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5561 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5562 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5563 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5566 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5567 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5568 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5569 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5572 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5573 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5574 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5575 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5578 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5579 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5580 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5581 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5586 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5589 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5590 SDValue Src = Op.getOperand(0);
5591 if (Src.getValueType() == MVT::f32)
5592 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5595 switch (Op.getSimpleValueType().SimpleTy) {
5596 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5599 Op.getOpcode() == ISD::FP_TO_SINT
5601 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5605 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5606 "i64 FP_TO_UINT is supported only with FPCVT");
5607 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5613 // Convert the FP value to an int value through memory.
5614 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5615 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5616 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5617 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5618 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5620 // Emit a store to the stack slot.
5623 MachineFunction &MF = DAG.getMachineFunction();
5624 MachineMemOperand *MMO =
5625 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5626 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5627 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5628 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5630 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5631 MPI, false, false, 0);
5633 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5635 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5636 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5637 DAG.getConstant(4, FIPtr.getValueType()));
5638 MPI = MPI.getWithOffset(4);
5646 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5649 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5651 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5652 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5656 // We're trying to insert a regular store, S, and then a load, L. If the
5657 // incoming value, O, is a load, we might just be able to have our load use the
5658 // address used by O. However, we don't know if anything else will store to
5659 // that address before we can load from it. To prevent this situation, we need
5660 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5661 // the same chain operand as O, we create a token factor from the chain results
5662 // of O and L, and we replace all uses of O's chain result with that token
5663 // factor (see spliceIntoChain below for this last part).
5664 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5667 ISD::LoadExtType ET) const {
5669 if (ET == ISD::NON_EXTLOAD &&
5670 (Op.getOpcode() == ISD::FP_TO_UINT ||
5671 Op.getOpcode() == ISD::FP_TO_SINT) &&
5672 isOperationLegalOrCustom(Op.getOpcode(),
5673 Op.getOperand(0).getValueType())) {
5675 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5679 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5680 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5681 LD->isNonTemporal())
5683 if (LD->getMemoryVT() != MemVT)
5686 RLI.Ptr = LD->getBasePtr();
5687 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5688 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5689 "Non-pre-inc AM on PPC?");
5690 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5694 RLI.Chain = LD->getChain();
5695 RLI.MPI = LD->getPointerInfo();
5696 RLI.IsInvariant = LD->isInvariant();
5697 RLI.Alignment = LD->getAlignment();
5698 RLI.AAInfo = LD->getAAInfo();
5699 RLI.Ranges = LD->getRanges();
5701 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5705 // Given the head of the old chain, ResChain, insert a token factor containing
5706 // it and NewResChain, and make users of ResChain now be users of that token
5708 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5709 SDValue NewResChain,
5710 SelectionDAG &DAG) const {
5714 SDLoc dl(NewResChain);
5716 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5717 NewResChain, DAG.getUNDEF(MVT::Other));
5718 assert(TF.getNode() != NewResChain.getNode() &&
5719 "A new TF really is required here");
5721 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5722 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5725 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5726 SelectionDAG &DAG) const {
5728 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5729 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5732 if (Op.getOperand(0).getValueType() == MVT::i1)
5733 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5734 DAG.getConstantFP(1.0, Op.getValueType()),
5735 DAG.getConstantFP(0.0, Op.getValueType()));
5737 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5738 "UINT_TO_FP is supported only with FPCVT");
5740 // If we have FCFIDS, then use it when converting to single-precision.
5741 // Otherwise, convert to double-precision and then round.
5742 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5743 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
5745 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
5747 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5751 if (Op.getOperand(0).getValueType() == MVT::i64) {
5752 SDValue SINT = Op.getOperand(0);
5753 // When converting to single-precision, we actually need to convert
5754 // to double-precision first and then round to single-precision.
5755 // To avoid double-rounding effects during that operation, we have
5756 // to prepare the input operand. Bits that might be truncated when
5757 // converting to double-precision are replaced by a bit that won't
5758 // be lost at this stage, but is below the single-precision rounding
5761 // However, if -enable-unsafe-fp-math is in effect, accept double
5762 // rounding to avoid the extra overhead.
5763 if (Op.getValueType() == MVT::f32 &&
5764 !Subtarget.hasFPCVT() &&
5765 !DAG.getTarget().Options.UnsafeFPMath) {
5767 // Twiddle input to make sure the low 11 bits are zero. (If this
5768 // is the case, we are guaranteed the value will fit into the 53 bit
5769 // mantissa of an IEEE double-precision value without rounding.)
5770 // If any of those low 11 bits were not zero originally, make sure
5771 // bit 12 (value 2048) is set instead, so that the final rounding
5772 // to single-precision gets the correct result.
5773 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5774 SINT, DAG.getConstant(2047, MVT::i64));
5775 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5776 Round, DAG.getConstant(2047, MVT::i64));
5777 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5778 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5779 Round, DAG.getConstant(-2048, MVT::i64));
5781 // However, we cannot use that value unconditionally: if the magnitude
5782 // of the input value is small, the bit-twiddling we did above might
5783 // end up visibly changing the output. Fortunately, in that case, we
5784 // don't need to twiddle bits since the original input will convert
5785 // exactly to double-precision floating-point already. Therefore,
5786 // construct a conditional to use the original value if the top 11
5787 // bits are all sign-bit copies, and use the rounded value computed
5789 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5790 SINT, DAG.getConstant(53, MVT::i32));
5791 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5792 Cond, DAG.getConstant(1, MVT::i64));
5793 Cond = DAG.getSetCC(dl, MVT::i32,
5794 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5796 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5802 MachineFunction &MF = DAG.getMachineFunction();
5803 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5804 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5805 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5807 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5808 } else if (Subtarget.hasLFIWAX() &&
5809 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5810 MachineMemOperand *MMO =
5811 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5812 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5813 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5814 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5815 DAG.getVTList(MVT::f64, MVT::Other),
5816 Ops, MVT::i32, MMO);
5817 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5818 } else if (Subtarget.hasFPCVT() &&
5819 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5820 MachineMemOperand *MMO =
5821 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5822 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5823 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5824 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5825 DAG.getVTList(MVT::f64, MVT::Other),
5826 Ops, MVT::i32, MMO);
5827 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5828 } else if (((Subtarget.hasLFIWAX() &&
5829 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5830 (Subtarget.hasFPCVT() &&
5831 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5832 SINT.getOperand(0).getValueType() == MVT::i32) {
5833 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5834 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5836 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5837 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5840 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5841 MachinePointerInfo::getFixedStack(FrameIdx),
5844 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5845 "Expected an i32 store");
5849 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5852 MachineMemOperand *MMO =
5853 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5854 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5855 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5856 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5857 PPCISD::LFIWZX : PPCISD::LFIWAX,
5858 dl, DAG.getVTList(MVT::f64, MVT::Other),
5859 Ops, MVT::i32, MMO);
5861 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5863 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5865 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5866 FP = DAG.getNode(ISD::FP_ROUND, dl,
5867 MVT::f32, FP, DAG.getIntPtrConstant(0));
5871 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5872 "Unhandled INT_TO_FP type in custom expander!");
5873 // Since we only generate this in 64-bit mode, we can take advantage of
5874 // 64-bit registers. In particular, sign extend the input value into the
5875 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5876 // then lfd it and fcfid it.
5877 MachineFunction &MF = DAG.getMachineFunction();
5878 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5879 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5882 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5885 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5887 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5888 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5890 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5891 MachinePointerInfo::getFixedStack(FrameIdx),
5894 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5895 "Expected an i32 store");
5899 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5903 MachineMemOperand *MMO =
5904 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5905 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5906 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5907 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5908 PPCISD::LFIWZX : PPCISD::LFIWAX,
5909 dl, DAG.getVTList(MVT::f64, MVT::Other),
5910 Ops, MVT::i32, MMO);
5912 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5914 assert(Subtarget.isPPC64() &&
5915 "i32->FP without LFIWAX supported only on PPC64");
5917 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5918 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5920 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5923 // STD the extended value into the stack slot.
5924 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5925 MachinePointerInfo::getFixedStack(FrameIdx),
5928 // Load the value as a double.
5929 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5930 MachinePointerInfo::getFixedStack(FrameIdx),
5931 false, false, false, 0);
5934 // FCFID it and return it.
5935 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5936 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5937 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5941 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5942 SelectionDAG &DAG) const {
5945 The rounding mode is in bits 30:31 of FPSR, and has the following
5952 FLT_ROUNDS, on the other hand, expects the following:
5959 To perform the conversion, we do:
5960 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5963 MachineFunction &MF = DAG.getMachineFunction();
5964 EVT VT = Op.getValueType();
5965 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5967 // Save FP Control Word to register
5969 MVT::f64, // return register
5970 MVT::Glue // unused in this context
5972 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5974 // Save FP register to stack slot
5975 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5976 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5977 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5978 StackSlot, MachinePointerInfo(), false, false,0);
5980 // Load FP Control Word from low 32 bits of stack slot.
5981 SDValue Four = DAG.getConstant(4, PtrVT);
5982 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5983 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5984 false, false, false, 0);
5986 // Transform as necessary
5988 DAG.getNode(ISD::AND, dl, MVT::i32,
5989 CWD, DAG.getConstant(3, MVT::i32));
5991 DAG.getNode(ISD::SRL, dl, MVT::i32,
5992 DAG.getNode(ISD::AND, dl, MVT::i32,
5993 DAG.getNode(ISD::XOR, dl, MVT::i32,
5994 CWD, DAG.getConstant(3, MVT::i32)),
5995 DAG.getConstant(3, MVT::i32)),
5996 DAG.getConstant(1, MVT::i32));
5999 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6001 return DAG.getNode((VT.getSizeInBits() < 16 ?
6002 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6005 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6006 EVT VT = Op.getValueType();
6007 unsigned BitWidth = VT.getSizeInBits();
6009 assert(Op.getNumOperands() == 3 &&
6010 VT == Op.getOperand(1).getValueType() &&
6013 // Expand into a bunch of logical ops. Note that these ops
6014 // depend on the PPC behavior for oversized shift amounts.
6015 SDValue Lo = Op.getOperand(0);
6016 SDValue Hi = Op.getOperand(1);
6017 SDValue Amt = Op.getOperand(2);
6018 EVT AmtVT = Amt.getValueType();
6020 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6021 DAG.getConstant(BitWidth, AmtVT), Amt);
6022 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6023 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6024 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6025 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6026 DAG.getConstant(-BitWidth, AmtVT));
6027 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6028 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6029 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6030 SDValue OutOps[] = { OutLo, OutHi };
6031 return DAG.getMergeValues(OutOps, dl);
6034 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6035 EVT VT = Op.getValueType();
6037 unsigned BitWidth = VT.getSizeInBits();
6038 assert(Op.getNumOperands() == 3 &&
6039 VT == Op.getOperand(1).getValueType() &&
6042 // Expand into a bunch of logical ops. Note that these ops
6043 // depend on the PPC behavior for oversized shift amounts.
6044 SDValue Lo = Op.getOperand(0);
6045 SDValue Hi = Op.getOperand(1);
6046 SDValue Amt = Op.getOperand(2);
6047 EVT AmtVT = Amt.getValueType();
6049 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6050 DAG.getConstant(BitWidth, AmtVT), Amt);
6051 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6052 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6053 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6054 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6055 DAG.getConstant(-BitWidth, AmtVT));
6056 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6057 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6058 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6059 SDValue OutOps[] = { OutLo, OutHi };
6060 return DAG.getMergeValues(OutOps, dl);
6063 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6065 EVT VT = Op.getValueType();
6066 unsigned BitWidth = VT.getSizeInBits();
6067 assert(Op.getNumOperands() == 3 &&
6068 VT == Op.getOperand(1).getValueType() &&
6071 // Expand into a bunch of logical ops, followed by a select_cc.
6072 SDValue Lo = Op.getOperand(0);
6073 SDValue Hi = Op.getOperand(1);
6074 SDValue Amt = Op.getOperand(2);
6075 EVT AmtVT = Amt.getValueType();
6077 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6078 DAG.getConstant(BitWidth, AmtVT), Amt);
6079 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6080 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6081 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6082 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6083 DAG.getConstant(-BitWidth, AmtVT));
6084 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6085 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6086 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6087 Tmp4, Tmp6, ISD::SETLE);
6088 SDValue OutOps[] = { OutLo, OutHi };
6089 return DAG.getMergeValues(OutOps, dl);
6092 //===----------------------------------------------------------------------===//
6093 // Vector related lowering.
6096 /// BuildSplatI - Build a canonical splati of Val with an element size of
6097 /// SplatSize. Cast the result to VT.
6098 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6099 SelectionDAG &DAG, SDLoc dl) {
6100 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6102 static const EVT VTys[] = { // canonical VT to use for each size.
6103 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6106 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6108 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6112 EVT CanonicalVT = VTys[SplatSize-1];
6114 // Build a canonical splat for this value.
6115 SDValue Elt = DAG.getConstant(Val, MVT::i32);
6116 SmallVector<SDValue, 8> Ops;
6117 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6118 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6119 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6122 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6123 /// specified intrinsic ID.
6124 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6125 SelectionDAG &DAG, SDLoc dl,
6126 EVT DestVT = MVT::Other) {
6127 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6128 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6129 DAG.getConstant(IID, MVT::i32), Op);
6132 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6133 /// specified intrinsic ID.
6134 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6135 SelectionDAG &DAG, SDLoc dl,
6136 EVT DestVT = MVT::Other) {
6137 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6138 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6139 DAG.getConstant(IID, MVT::i32), LHS, RHS);
6142 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6143 /// specified intrinsic ID.
6144 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6145 SDValue Op2, SelectionDAG &DAG,
6146 SDLoc dl, EVT DestVT = MVT::Other) {
6147 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6148 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6149 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6153 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6154 /// amount. The result has the specified value type.
6155 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6156 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6157 // Force LHS/RHS to be the right type.
6158 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6159 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6162 for (unsigned i = 0; i != 16; ++i)
6164 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6165 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6168 // If this is a case we can't handle, return null and let the default
6169 // expansion code take care of it. If we CAN select this case, and if it
6170 // selects to a single instruction, return Op. Otherwise, if we can codegen
6171 // this case more efficiently than a constant pool load, lower it to the
6172 // sequence of ops that should be used.
6173 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6174 SelectionDAG &DAG) const {
6176 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6177 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6179 // Check if this is a splat of a constant value.
6180 APInt APSplatBits, APSplatUndef;
6181 unsigned SplatBitSize;
6183 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6184 HasAnyUndefs, 0, true) || SplatBitSize > 32)
6187 unsigned SplatBits = APSplatBits.getZExtValue();
6188 unsigned SplatUndef = APSplatUndef.getZExtValue();
6189 unsigned SplatSize = SplatBitSize / 8;
6191 // First, handle single instruction cases.
6194 if (SplatBits == 0) {
6195 // Canonicalize all zero vectors to be v4i32.
6196 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6197 SDValue Z = DAG.getConstant(0, MVT::i32);
6198 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6199 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6204 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6205 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6207 if (SextVal >= -16 && SextVal <= 15)
6208 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6211 // Two instruction sequences.
6213 // If this value is in the range [-32,30] and is even, use:
6214 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6215 // If this value is in the range [17,31] and is odd, use:
6216 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6217 // If this value is in the range [-31,-17] and is odd, use:
6218 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6219 // Note the last two are three-instruction sequences.
6220 if (SextVal >= -32 && SextVal <= 31) {
6221 // To avoid having these optimizations undone by constant folding,
6222 // we convert to a pseudo that will be expanded later into one of
6224 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6225 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6226 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6227 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6228 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6229 if (VT == Op.getValueType())
6232 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6235 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6236 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6238 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6239 // Make -1 and vspltisw -1:
6240 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6242 // Make the VSLW intrinsic, computing 0x8000_0000.
6243 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6246 // xor by OnesV to invert it.
6247 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6248 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6251 // The remaining cases assume either big endian element order or
6252 // a splat-size that equates to the element size of the vector
6253 // to be built. An example that doesn't work for little endian is
6254 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6255 // and a vector element size of 16 bits. The code below will
6256 // produce the vector in big endian element order, which for little
6257 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6259 // For now, just avoid these optimizations in that case.
6260 // FIXME: Develop correct optimizations for LE with mismatched
6261 // splat and element sizes.
6263 if (Subtarget.isLittleEndian() &&
6264 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6267 // Check to see if this is a wide variety of vsplti*, binop self cases.
6268 static const signed char SplatCsts[] = {
6269 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6270 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6273 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6274 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6275 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6276 int i = SplatCsts[idx];
6278 // Figure out what shift amount will be used by altivec if shifted by i in
6280 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6282 // vsplti + shl self.
6283 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6284 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6285 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6286 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6287 Intrinsic::ppc_altivec_vslw
6289 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6290 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6293 // vsplti + srl self.
6294 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6295 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6296 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6297 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6298 Intrinsic::ppc_altivec_vsrw
6300 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6301 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6304 // vsplti + sra self.
6305 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6306 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6307 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6308 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6309 Intrinsic::ppc_altivec_vsraw
6311 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6312 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6315 // vsplti + rol self.
6316 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6317 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6318 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6319 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6320 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6321 Intrinsic::ppc_altivec_vrlw
6323 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6324 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6327 // t = vsplti c, result = vsldoi t, t, 1
6328 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6329 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6330 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6332 // t = vsplti c, result = vsldoi t, t, 2
6333 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6334 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6335 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6337 // t = vsplti c, result = vsldoi t, t, 3
6338 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6339 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6340 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6347 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6348 /// the specified operations to build the shuffle.
6349 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6350 SDValue RHS, SelectionDAG &DAG,
6352 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6353 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6354 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6357 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6369 if (OpNum == OP_COPY) {
6370 if (LHSID == (1*9+2)*9+3) return LHS;
6371 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6375 SDValue OpLHS, OpRHS;
6376 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6377 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6381 default: llvm_unreachable("Unknown i32 permute!");
6383 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6384 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6385 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6386 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6389 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6390 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6391 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6392 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6395 for (unsigned i = 0; i != 16; ++i)
6396 ShufIdxs[i] = (i&3)+0;
6399 for (unsigned i = 0; i != 16; ++i)
6400 ShufIdxs[i] = (i&3)+4;
6403 for (unsigned i = 0; i != 16; ++i)
6404 ShufIdxs[i] = (i&3)+8;
6407 for (unsigned i = 0; i != 16; ++i)
6408 ShufIdxs[i] = (i&3)+12;
6411 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6413 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6415 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6417 EVT VT = OpLHS.getValueType();
6418 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6419 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6420 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6421 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6424 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6425 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6426 /// return the code it can be lowered into. Worst case, it can always be
6427 /// lowered into a vperm.
6428 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6429 SelectionDAG &DAG) const {
6431 SDValue V1 = Op.getOperand(0);
6432 SDValue V2 = Op.getOperand(1);
6433 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6434 EVT VT = Op.getValueType();
6435 bool isLittleEndian = Subtarget.isLittleEndian();
6437 // Cases that are handled by instructions that take permute immediates
6438 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6439 // selected by the instruction selector.
6440 if (V2.getOpcode() == ISD::UNDEF) {
6441 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6442 PPC::isSplatShuffleMask(SVOp, 2) ||
6443 PPC::isSplatShuffleMask(SVOp, 4) ||
6444 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6445 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6446 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6447 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6448 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6449 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6450 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6451 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6452 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6457 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6458 // and produce a fixed permutation. If any of these match, do not lower to
6460 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6461 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6462 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6463 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6464 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6465 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6466 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6467 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6468 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6469 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6472 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6473 // perfect shuffle table to emit an optimal matching sequence.
6474 ArrayRef<int> PermMask = SVOp->getMask();
6476 unsigned PFIndexes[4];
6477 bool isFourElementShuffle = true;
6478 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6479 unsigned EltNo = 8; // Start out undef.
6480 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6481 if (PermMask[i*4+j] < 0)
6482 continue; // Undef, ignore it.
6484 unsigned ByteSource = PermMask[i*4+j];
6485 if ((ByteSource & 3) != j) {
6486 isFourElementShuffle = false;
6491 EltNo = ByteSource/4;
6492 } else if (EltNo != ByteSource/4) {
6493 isFourElementShuffle = false;
6497 PFIndexes[i] = EltNo;
6500 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6501 // perfect shuffle vector to determine if it is cost effective to do this as
6502 // discrete instructions, or whether we should use a vperm.
6503 // For now, we skip this for little endian until such time as we have a
6504 // little-endian perfect shuffle table.
6505 if (isFourElementShuffle && !isLittleEndian) {
6506 // Compute the index in the perfect shuffle table.
6507 unsigned PFTableIndex =
6508 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6510 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6511 unsigned Cost = (PFEntry >> 30);
6513 // Determining when to avoid vperm is tricky. Many things affect the cost
6514 // of vperm, particularly how many times the perm mask needs to be computed.
6515 // For example, if the perm mask can be hoisted out of a loop or is already
6516 // used (perhaps because there are multiple permutes with the same shuffle
6517 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6518 // the loop requires an extra register.
6520 // As a compromise, we only emit discrete instructions if the shuffle can be
6521 // generated in 3 or fewer operations. When we have loop information
6522 // available, if this block is within a loop, we should avoid using vperm
6523 // for 3-operation perms and use a constant pool load instead.
6525 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6528 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6529 // vector that will get spilled to the constant pool.
6530 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6532 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6533 // that it is in input element units, not in bytes. Convert now.
6535 // For little endian, the order of the input vectors is reversed, and
6536 // the permutation mask is complemented with respect to 31. This is
6537 // necessary to produce proper semantics with the big-endian-biased vperm
6539 EVT EltVT = V1.getValueType().getVectorElementType();
6540 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6542 SmallVector<SDValue, 16> ResultMask;
6543 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6544 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6546 for (unsigned j = 0; j != BytesPerElement; ++j)
6548 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6551 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6555 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6558 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6561 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6565 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6566 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6567 /// information about the intrinsic.
6568 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6570 unsigned IntrinsicID =
6571 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6574 switch (IntrinsicID) {
6575 default: return false;
6576 // Comparison predicates.
6577 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6578 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6579 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6580 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6581 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6582 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6583 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6584 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6585 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6586 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6587 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6588 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6589 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6591 // Normal Comparisons.
6592 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6593 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6594 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6595 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6596 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6597 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6598 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6599 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6600 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6601 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6602 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6603 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6604 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6609 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6610 /// lower, do it, otherwise return null.
6611 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6612 SelectionDAG &DAG) const {
6613 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6614 // opcode number of the comparison.
6618 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6619 return SDValue(); // Don't custom lower most intrinsics.
6621 // If this is a non-dot comparison, make the VCMP node and we are done.
6623 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6624 Op.getOperand(1), Op.getOperand(2),
6625 DAG.getConstant(CompareOpc, MVT::i32));
6626 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6629 // Create the PPCISD altivec 'dot' comparison node.
6631 Op.getOperand(2), // LHS
6632 Op.getOperand(3), // RHS
6633 DAG.getConstant(CompareOpc, MVT::i32)
6635 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6636 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6638 // Now that we have the comparison, emit a copy from the CR to a GPR.
6639 // This is flagged to the above dot comparison.
6640 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6641 DAG.getRegister(PPC::CR6, MVT::i32),
6642 CompNode.getValue(1));
6644 // Unpack the result based on how the target uses it.
6645 unsigned BitNo; // Bit # of CR6.
6646 bool InvertBit; // Invert result?
6647 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6648 default: // Can't happen, don't crash on invalid number though.
6649 case 0: // Return the value of the EQ bit of CR6.
6650 BitNo = 0; InvertBit = false;
6652 case 1: // Return the inverted value of the EQ bit of CR6.
6653 BitNo = 0; InvertBit = true;
6655 case 2: // Return the value of the LT bit of CR6.
6656 BitNo = 2; InvertBit = false;
6658 case 3: // Return the inverted value of the LT bit of CR6.
6659 BitNo = 2; InvertBit = true;
6663 // Shift the bit into the low position.
6664 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6665 DAG.getConstant(8-(3-BitNo), MVT::i32));
6667 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6668 DAG.getConstant(1, MVT::i32));
6670 // If we are supposed to, toggle the bit.
6672 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6673 DAG.getConstant(1, MVT::i32));
6677 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6678 SelectionDAG &DAG) const {
6680 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6681 // instructions), but for smaller types, we need to first extend up to v2i32
6682 // before doing going farther.
6683 if (Op.getValueType() == MVT::v2i64) {
6684 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6685 if (ExtVT != MVT::v2i32) {
6686 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6687 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6688 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6689 ExtVT.getVectorElementType(), 4)));
6690 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6691 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6692 DAG.getValueType(MVT::v2i32));
6701 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6702 SelectionDAG &DAG) const {
6704 // Create a stack slot that is 16-byte aligned.
6705 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6706 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6707 EVT PtrVT = getPointerTy();
6708 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6710 // Store the input value into Value#0 of the stack slot.
6711 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6712 Op.getOperand(0), FIdx, MachinePointerInfo(),
6715 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6716 false, false, false, 0);
6719 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6721 if (Op.getValueType() == MVT::v4i32) {
6722 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6724 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6725 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6727 SDValue RHSSwap = // = vrlw RHS, 16
6728 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6730 // Shrinkify inputs to v8i16.
6731 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6732 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6733 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6735 // Low parts multiplied together, generating 32-bit results (we ignore the
6737 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6738 LHS, RHS, DAG, dl, MVT::v4i32);
6740 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6741 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6742 // Shift the high parts up 16 bits.
6743 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6745 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6746 } else if (Op.getValueType() == MVT::v8i16) {
6747 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6749 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6751 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6752 LHS, RHS, Zero, DAG, dl);
6753 } else if (Op.getValueType() == MVT::v16i8) {
6754 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6755 bool isLittleEndian = Subtarget.isLittleEndian();
6757 // Multiply the even 8-bit parts, producing 16-bit sums.
6758 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6759 LHS, RHS, DAG, dl, MVT::v8i16);
6760 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6762 // Multiply the odd 8-bit parts, producing 16-bit sums.
6763 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6764 LHS, RHS, DAG, dl, MVT::v8i16);
6765 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6767 // Merge the results together. Because vmuleub and vmuloub are
6768 // instructions with a big-endian bias, we must reverse the
6769 // element numbering and reverse the meaning of "odd" and "even"
6770 // when generating little endian code.
6772 for (unsigned i = 0; i != 8; ++i) {
6773 if (isLittleEndian) {
6775 Ops[i*2+1] = 2*i+16;
6778 Ops[i*2+1] = 2*i+1+16;
6782 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6784 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6786 llvm_unreachable("Unknown mul to lower!");
6790 /// LowerOperation - Provide custom lowering hooks for some operations.
6792 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6793 switch (Op.getOpcode()) {
6794 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6795 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6796 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6797 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6798 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6799 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6800 case ISD::SETCC: return LowerSETCC(Op, DAG);
6801 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6802 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6804 return LowerVASTART(Op, DAG, Subtarget);
6807 return LowerVAARG(Op, DAG, Subtarget);
6810 return LowerVACOPY(Op, DAG, Subtarget);
6812 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6813 case ISD::DYNAMIC_STACKALLOC:
6814 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6816 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6817 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6819 case ISD::LOAD: return LowerLOAD(Op, DAG);
6820 case ISD::STORE: return LowerSTORE(Op, DAG);
6821 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6822 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6823 case ISD::FP_TO_UINT:
6824 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6826 case ISD::UINT_TO_FP:
6827 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6828 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6830 // Lower 64-bit shifts.
6831 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6832 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6833 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6835 // Vector-related lowering.
6836 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6837 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6838 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6839 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6840 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6841 case ISD::MUL: return LowerMUL(Op, DAG);
6843 // For counter-based loop handling.
6844 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6846 // Frame & Return address.
6847 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6848 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6852 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6853 SmallVectorImpl<SDValue>&Results,
6854 SelectionDAG &DAG) const {
6856 switch (N->getOpcode()) {
6858 llvm_unreachable("Do not know how to custom type legalize this operation!");
6859 case ISD::READCYCLECOUNTER: {
6860 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6861 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6863 Results.push_back(RTB);
6864 Results.push_back(RTB.getValue(1));
6865 Results.push_back(RTB.getValue(2));
6868 case ISD::INTRINSIC_W_CHAIN: {
6869 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6870 Intrinsic::ppc_is_decremented_ctr_nonzero)
6873 assert(N->getValueType(0) == MVT::i1 &&
6874 "Unexpected result type for CTR decrement intrinsic");
6875 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6876 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6877 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6880 Results.push_back(NewInt);
6881 Results.push_back(NewInt.getValue(1));
6885 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
6888 EVT VT = N->getValueType(0);
6890 if (VT == MVT::i64) {
6891 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6893 Results.push_back(NewNode);
6894 Results.push_back(NewNode.getValue(1));
6898 case ISD::FP_ROUND_INREG: {
6899 assert(N->getValueType(0) == MVT::ppcf128);
6900 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6901 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6902 MVT::f64, N->getOperand(0),
6903 DAG.getIntPtrConstant(0));
6904 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6905 MVT::f64, N->getOperand(0),
6906 DAG.getIntPtrConstant(1));
6908 // Add the two halves of the long double in round-to-zero mode.
6909 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6911 // We know the low half is about to be thrown away, so just use something
6913 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6917 case ISD::FP_TO_SINT:
6918 // LowerFP_TO_INT() can only handle f32 and f64.
6919 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6921 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6927 //===----------------------------------------------------------------------===//
6928 // Other Lowering Code
6929 //===----------------------------------------------------------------------===//
6931 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6932 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6933 Function *Func = Intrinsic::getDeclaration(M, Id);
6934 return Builder.CreateCall(Func);
6937 // The mappings for emitLeading/TrailingFence is taken from
6938 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6939 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6940 AtomicOrdering Ord, bool IsStore,
6941 bool IsLoad) const {
6942 if (Ord == SequentiallyConsistent)
6943 return callIntrinsic(Builder, Intrinsic::ppc_sync);
6944 else if (isAtLeastRelease(Ord))
6945 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6950 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6951 AtomicOrdering Ord, bool IsStore,
6952 bool IsLoad) const {
6953 if (IsLoad && isAtLeastAcquire(Ord))
6954 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6955 // FIXME: this is too conservative, a dependent branch + isync is enough.
6956 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6957 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6958 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6964 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6965 bool is64bit, unsigned BinOpcode) const {
6966 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6967 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6969 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6970 MachineFunction *F = BB->getParent();
6971 MachineFunction::iterator It = BB;
6974 unsigned dest = MI->getOperand(0).getReg();
6975 unsigned ptrA = MI->getOperand(1).getReg();
6976 unsigned ptrB = MI->getOperand(2).getReg();
6977 unsigned incr = MI->getOperand(3).getReg();
6978 DebugLoc dl = MI->getDebugLoc();
6980 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6981 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6982 F->insert(It, loopMBB);
6983 F->insert(It, exitMBB);
6984 exitMBB->splice(exitMBB->begin(), BB,
6985 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6986 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6988 MachineRegisterInfo &RegInfo = F->getRegInfo();
6989 unsigned TmpReg = (!BinOpcode) ? incr :
6990 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6991 : &PPC::GPRCRegClass);
6995 // fallthrough --> loopMBB
6996 BB->addSuccessor(loopMBB);
6999 // l[wd]arx dest, ptr
7000 // add r0, dest, incr
7001 // st[wd]cx. r0, ptr
7003 // fallthrough --> exitMBB
7005 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7006 .addReg(ptrA).addReg(ptrB);
7008 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7009 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7010 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7011 BuildMI(BB, dl, TII->get(PPC::BCC))
7012 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7013 BB->addSuccessor(loopMBB);
7014 BB->addSuccessor(exitMBB);
7023 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7024 MachineBasicBlock *BB,
7025 bool is8bit, // operation
7026 unsigned BinOpcode) const {
7027 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7028 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7029 // In 64 bit mode we have to use 64 bits for addresses, even though the
7030 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7031 // registers without caring whether they're 32 or 64, but here we're
7032 // doing actual arithmetic on the addresses.
7033 bool is64bit = Subtarget.isPPC64();
7034 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7036 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7037 MachineFunction *F = BB->getParent();
7038 MachineFunction::iterator It = BB;
7041 unsigned dest = MI->getOperand(0).getReg();
7042 unsigned ptrA = MI->getOperand(1).getReg();
7043 unsigned ptrB = MI->getOperand(2).getReg();
7044 unsigned incr = MI->getOperand(3).getReg();
7045 DebugLoc dl = MI->getDebugLoc();
7047 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7048 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7049 F->insert(It, loopMBB);
7050 F->insert(It, exitMBB);
7051 exitMBB->splice(exitMBB->begin(), BB,
7052 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7053 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7055 MachineRegisterInfo &RegInfo = F->getRegInfo();
7056 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7057 : &PPC::GPRCRegClass;
7058 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7059 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7060 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7061 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7062 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7063 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7064 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7065 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7066 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7067 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7068 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7070 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7074 // fallthrough --> loopMBB
7075 BB->addSuccessor(loopMBB);
7077 // The 4-byte load must be aligned, while a char or short may be
7078 // anywhere in the word. Hence all this nasty bookkeeping code.
7079 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7080 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7081 // xori shift, shift1, 24 [16]
7082 // rlwinm ptr, ptr1, 0, 0, 29
7083 // slw incr2, incr, shift
7084 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7085 // slw mask, mask2, shift
7087 // lwarx tmpDest, ptr
7088 // add tmp, tmpDest, incr2
7089 // andc tmp2, tmpDest, mask
7090 // and tmp3, tmp, mask
7091 // or tmp4, tmp3, tmp2
7094 // fallthrough --> exitMBB
7095 // srw dest, tmpDest, shift
7096 if (ptrA != ZeroReg) {
7097 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7098 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7099 .addReg(ptrA).addReg(ptrB);
7103 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7104 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7105 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7106 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7108 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7109 .addReg(Ptr1Reg).addImm(0).addImm(61);
7111 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7112 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7113 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7114 .addReg(incr).addReg(ShiftReg);
7116 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7118 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7119 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7121 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7122 .addReg(Mask2Reg).addReg(ShiftReg);
7125 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7126 .addReg(ZeroReg).addReg(PtrReg);
7128 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7129 .addReg(Incr2Reg).addReg(TmpDestReg);
7130 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7131 .addReg(TmpDestReg).addReg(MaskReg);
7132 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7133 .addReg(TmpReg).addReg(MaskReg);
7134 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7135 .addReg(Tmp3Reg).addReg(Tmp2Reg);
7136 BuildMI(BB, dl, TII->get(PPC::STWCX))
7137 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7138 BuildMI(BB, dl, TII->get(PPC::BCC))
7139 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7140 BB->addSuccessor(loopMBB);
7141 BB->addSuccessor(exitMBB);
7146 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7151 llvm::MachineBasicBlock*
7152 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7153 MachineBasicBlock *MBB) const {
7154 DebugLoc DL = MI->getDebugLoc();
7155 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7157 MachineFunction *MF = MBB->getParent();
7158 MachineRegisterInfo &MRI = MF->getRegInfo();
7160 const BasicBlock *BB = MBB->getBasicBlock();
7161 MachineFunction::iterator I = MBB;
7165 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7166 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7168 unsigned DstReg = MI->getOperand(0).getReg();
7169 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7170 assert(RC->hasType(MVT::i32) && "Invalid destination!");
7171 unsigned mainDstReg = MRI.createVirtualRegister(RC);
7172 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7174 MVT PVT = getPointerTy();
7175 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7176 "Invalid Pointer Size!");
7177 // For v = setjmp(buf), we generate
7180 // SjLjSetup mainMBB
7186 // buf[LabelOffset] = LR
7190 // v = phi(main, restore)
7193 MachineBasicBlock *thisMBB = MBB;
7194 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7195 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7196 MF->insert(I, mainMBB);
7197 MF->insert(I, sinkMBB);
7199 MachineInstrBuilder MIB;
7201 // Transfer the remainder of BB and its successor edges to sinkMBB.
7202 sinkMBB->splice(sinkMBB->begin(), MBB,
7203 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7204 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7206 // Note that the structure of the jmp_buf used here is not compatible
7207 // with that used by libc, and is not designed to be. Specifically, it
7208 // stores only those 'reserved' registers that LLVM does not otherwise
7209 // understand how to spill. Also, by convention, by the time this
7210 // intrinsic is called, Clang has already stored the frame address in the
7211 // first slot of the buffer and stack address in the third. Following the
7212 // X86 target code, we'll store the jump address in the second slot. We also
7213 // need to save the TOC pointer (R2) to handle jumps between shared
7214 // libraries, and that will be stored in the fourth slot. The thread
7215 // identifier (R13) is not affected.
7218 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7219 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7220 const int64_t BPOffset = 4 * PVT.getStoreSize();
7222 // Prepare IP either in reg.
7223 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7224 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7225 unsigned BufReg = MI->getOperand(1).getReg();
7227 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7228 setUsesTOCBasePtr(*MBB->getParent());
7229 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7233 MIB.setMemRefs(MMOBegin, MMOEnd);
7236 // Naked functions never have a base pointer, and so we use r1. For all
7237 // other functions, this decision must be delayed until during PEI.
7239 if (MF->getFunction()->getAttributes().hasAttribute(
7240 AttributeSet::FunctionIndex, Attribute::Naked))
7241 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7243 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7245 MIB = BuildMI(*thisMBB, MI, DL,
7246 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7250 MIB.setMemRefs(MMOBegin, MMOEnd);
7253 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7254 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7255 MIB.addRegMask(TRI->getNoPreservedMask());
7257 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7259 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7261 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7263 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7264 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7269 BuildMI(mainMBB, DL,
7270 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7273 if (Subtarget.isPPC64()) {
7274 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7276 .addImm(LabelOffset)
7279 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7281 .addImm(LabelOffset)
7285 MIB.setMemRefs(MMOBegin, MMOEnd);
7287 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7288 mainMBB->addSuccessor(sinkMBB);
7291 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7292 TII->get(PPC::PHI), DstReg)
7293 .addReg(mainDstReg).addMBB(mainMBB)
7294 .addReg(restoreDstReg).addMBB(thisMBB);
7296 MI->eraseFromParent();
7301 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7302 MachineBasicBlock *MBB) const {
7303 DebugLoc DL = MI->getDebugLoc();
7304 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7306 MachineFunction *MF = MBB->getParent();
7307 MachineRegisterInfo &MRI = MF->getRegInfo();
7310 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7311 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7313 MVT PVT = getPointerTy();
7314 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7315 "Invalid Pointer Size!");
7317 const TargetRegisterClass *RC =
7318 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7319 unsigned Tmp = MRI.createVirtualRegister(RC);
7320 // Since FP is only updated here but NOT referenced, it's treated as GPR.
7321 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7322 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7326 : (Subtarget.isSVR4ABI() &&
7327 MF->getTarget().getRelocationModel() == Reloc::PIC_
7331 MachineInstrBuilder MIB;
7333 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7334 const int64_t SPOffset = 2 * PVT.getStoreSize();
7335 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7336 const int64_t BPOffset = 4 * PVT.getStoreSize();
7338 unsigned BufReg = MI->getOperand(0).getReg();
7340 // Reload FP (the jumped-to function may not have had a
7341 // frame pointer, and if so, then its r31 will be restored
7343 if (PVT == MVT::i64) {
7344 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7348 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7352 MIB.setMemRefs(MMOBegin, MMOEnd);
7355 if (PVT == MVT::i64) {
7356 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7357 .addImm(LabelOffset)
7360 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7361 .addImm(LabelOffset)
7364 MIB.setMemRefs(MMOBegin, MMOEnd);
7367 if (PVT == MVT::i64) {
7368 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7372 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7376 MIB.setMemRefs(MMOBegin, MMOEnd);
7379 if (PVT == MVT::i64) {
7380 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7384 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7388 MIB.setMemRefs(MMOBegin, MMOEnd);
7391 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7392 setUsesTOCBasePtr(*MBB->getParent());
7393 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7397 MIB.setMemRefs(MMOBegin, MMOEnd);
7401 BuildMI(*MBB, MI, DL,
7402 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7403 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7405 MI->eraseFromParent();
7410 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7411 MachineBasicBlock *BB) const {
7412 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
7413 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7414 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
7415 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7416 // Call lowering should have added an r2 operand to indicate a dependence
7417 // on the TOC base pointer value. It can't however, because there is no
7418 // way to mark the dependence as implicit there, and so the stackmap code
7419 // will confuse it with a regular operand. Instead, add the dependence
7421 setUsesTOCBasePtr(*BB->getParent());
7422 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
7425 return emitPatchPoint(MI, BB);
7428 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7429 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7430 return emitEHSjLjSetJmp(MI, BB);
7431 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7432 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7433 return emitEHSjLjLongJmp(MI, BB);
7436 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7438 // To "insert" these instructions we actually have to insert their
7439 // control-flow patterns.
7440 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7441 MachineFunction::iterator It = BB;
7444 MachineFunction *F = BB->getParent();
7446 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7447 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7448 MI->getOpcode() == PPC::SELECT_I4 ||
7449 MI->getOpcode() == PPC::SELECT_I8)) {
7450 SmallVector<MachineOperand, 2> Cond;
7451 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7452 MI->getOpcode() == PPC::SELECT_CC_I8)
7453 Cond.push_back(MI->getOperand(4));
7455 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7456 Cond.push_back(MI->getOperand(1));
7458 DebugLoc dl = MI->getDebugLoc();
7459 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7460 Cond, MI->getOperand(2).getReg(),
7461 MI->getOperand(3).getReg());
7462 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7463 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7464 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7465 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7466 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7467 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7468 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7469 MI->getOpcode() == PPC::SELECT_I4 ||
7470 MI->getOpcode() == PPC::SELECT_I8 ||
7471 MI->getOpcode() == PPC::SELECT_F4 ||
7472 MI->getOpcode() == PPC::SELECT_F8 ||
7473 MI->getOpcode() == PPC::SELECT_VRRC ||
7474 MI->getOpcode() == PPC::SELECT_VSFRC ||
7475 MI->getOpcode() == PPC::SELECT_VSRC) {
7476 // The incoming instruction knows the destination vreg to set, the
7477 // condition code register to branch on, the true/false values to
7478 // select between, and a branch opcode to use.
7483 // cmpTY ccX, r1, r2
7485 // fallthrough --> copy0MBB
7486 MachineBasicBlock *thisMBB = BB;
7487 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7488 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7489 DebugLoc dl = MI->getDebugLoc();
7490 F->insert(It, copy0MBB);
7491 F->insert(It, sinkMBB);
7493 // Transfer the remainder of BB and its successor edges to sinkMBB.
7494 sinkMBB->splice(sinkMBB->begin(), BB,
7495 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7496 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7498 // Next, add the true and fallthrough blocks as its successors.
7499 BB->addSuccessor(copy0MBB);
7500 BB->addSuccessor(sinkMBB);
7502 if (MI->getOpcode() == PPC::SELECT_I4 ||
7503 MI->getOpcode() == PPC::SELECT_I8 ||
7504 MI->getOpcode() == PPC::SELECT_F4 ||
7505 MI->getOpcode() == PPC::SELECT_F8 ||
7506 MI->getOpcode() == PPC::SELECT_VRRC ||
7507 MI->getOpcode() == PPC::SELECT_VSFRC ||
7508 MI->getOpcode() == PPC::SELECT_VSRC) {
7509 BuildMI(BB, dl, TII->get(PPC::BC))
7510 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7512 unsigned SelectPred = MI->getOperand(4).getImm();
7513 BuildMI(BB, dl, TII->get(PPC::BCC))
7514 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7518 // %FalseValue = ...
7519 // # fallthrough to sinkMBB
7522 // Update machine-CFG edges
7523 BB->addSuccessor(sinkMBB);
7526 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7529 BuildMI(*BB, BB->begin(), dl,
7530 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7531 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7532 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7533 } else if (MI->getOpcode() == PPC::ReadTB) {
7534 // To read the 64-bit time-base register on a 32-bit target, we read the
7535 // two halves. Should the counter have wrapped while it was being read, we
7536 // need to try again.
7539 // mfspr Rx,TBU # load from TBU
7540 // mfspr Ry,TB # load from TB
7541 // mfspr Rz,TBU # load from TBU
7542 // cmpw crX,Rx,Rz # check if ‘old’=’new’
7543 // bne readLoop # branch if they're not equal
7546 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7547 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7548 DebugLoc dl = MI->getDebugLoc();
7549 F->insert(It, readMBB);
7550 F->insert(It, sinkMBB);
7552 // Transfer the remainder of BB and its successor edges to sinkMBB.
7553 sinkMBB->splice(sinkMBB->begin(), BB,
7554 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7555 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7557 BB->addSuccessor(readMBB);
7560 MachineRegisterInfo &RegInfo = F->getRegInfo();
7561 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7562 unsigned LoReg = MI->getOperand(0).getReg();
7563 unsigned HiReg = MI->getOperand(1).getReg();
7565 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7566 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7567 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7569 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7571 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7572 .addReg(HiReg).addReg(ReadAgainReg);
7573 BuildMI(BB, dl, TII->get(PPC::BCC))
7574 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7576 BB->addSuccessor(readMBB);
7577 BB->addSuccessor(sinkMBB);
7579 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7580 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7581 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7582 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7583 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7584 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7585 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7586 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7588 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7589 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7590 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7591 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7592 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7593 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7594 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7595 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7597 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7598 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7599 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7600 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7601 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7602 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7603 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7604 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7606 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7607 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7608 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7609 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7610 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7611 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7612 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7613 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7615 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7616 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7617 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7618 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7619 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7620 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7621 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7622 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7624 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7625 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7626 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7627 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7628 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7629 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7630 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7631 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7633 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7634 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7635 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7636 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7637 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7638 BB = EmitAtomicBinary(MI, BB, false, 0);
7639 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7640 BB = EmitAtomicBinary(MI, BB, true, 0);
7642 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7643 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7644 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7646 unsigned dest = MI->getOperand(0).getReg();
7647 unsigned ptrA = MI->getOperand(1).getReg();
7648 unsigned ptrB = MI->getOperand(2).getReg();
7649 unsigned oldval = MI->getOperand(3).getReg();
7650 unsigned newval = MI->getOperand(4).getReg();
7651 DebugLoc dl = MI->getDebugLoc();
7653 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7654 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7655 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7656 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7657 F->insert(It, loop1MBB);
7658 F->insert(It, loop2MBB);
7659 F->insert(It, midMBB);
7660 F->insert(It, exitMBB);
7661 exitMBB->splice(exitMBB->begin(), BB,
7662 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7663 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7667 // fallthrough --> loopMBB
7668 BB->addSuccessor(loop1MBB);
7671 // l[wd]arx dest, ptr
7672 // cmp[wd] dest, oldval
7675 // st[wd]cx. newval, ptr
7679 // st[wd]cx. dest, ptr
7682 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7683 .addReg(ptrA).addReg(ptrB);
7684 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7685 .addReg(oldval).addReg(dest);
7686 BuildMI(BB, dl, TII->get(PPC::BCC))
7687 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7688 BB->addSuccessor(loop2MBB);
7689 BB->addSuccessor(midMBB);
7692 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7693 .addReg(newval).addReg(ptrA).addReg(ptrB);
7694 BuildMI(BB, dl, TII->get(PPC::BCC))
7695 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7696 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7697 BB->addSuccessor(loop1MBB);
7698 BB->addSuccessor(exitMBB);
7701 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7702 .addReg(dest).addReg(ptrA).addReg(ptrB);
7703 BB->addSuccessor(exitMBB);
7708 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7709 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7710 // We must use 64-bit registers for addresses when targeting 64-bit,
7711 // since we're actually doing arithmetic on them. Other registers
7713 bool is64bit = Subtarget.isPPC64();
7714 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7716 unsigned dest = MI->getOperand(0).getReg();
7717 unsigned ptrA = MI->getOperand(1).getReg();
7718 unsigned ptrB = MI->getOperand(2).getReg();
7719 unsigned oldval = MI->getOperand(3).getReg();
7720 unsigned newval = MI->getOperand(4).getReg();
7721 DebugLoc dl = MI->getDebugLoc();
7723 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7724 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7725 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7726 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7727 F->insert(It, loop1MBB);
7728 F->insert(It, loop2MBB);
7729 F->insert(It, midMBB);
7730 F->insert(It, exitMBB);
7731 exitMBB->splice(exitMBB->begin(), BB,
7732 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7733 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7735 MachineRegisterInfo &RegInfo = F->getRegInfo();
7736 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7737 : &PPC::GPRCRegClass;
7738 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7739 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7740 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7741 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7742 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7743 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7744 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7745 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7746 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7747 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7748 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7749 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7750 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7752 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7753 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7756 // fallthrough --> loopMBB
7757 BB->addSuccessor(loop1MBB);
7759 // The 4-byte load must be aligned, while a char or short may be
7760 // anywhere in the word. Hence all this nasty bookkeeping code.
7761 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7762 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7763 // xori shift, shift1, 24 [16]
7764 // rlwinm ptr, ptr1, 0, 0, 29
7765 // slw newval2, newval, shift
7766 // slw oldval2, oldval,shift
7767 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7768 // slw mask, mask2, shift
7769 // and newval3, newval2, mask
7770 // and oldval3, oldval2, mask
7772 // lwarx tmpDest, ptr
7773 // and tmp, tmpDest, mask
7774 // cmpw tmp, oldval3
7777 // andc tmp2, tmpDest, mask
7778 // or tmp4, tmp2, newval3
7783 // stwcx. tmpDest, ptr
7785 // srw dest, tmpDest, shift
7786 if (ptrA != ZeroReg) {
7787 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7788 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7789 .addReg(ptrA).addReg(ptrB);
7793 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7794 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7795 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7796 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7798 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7799 .addReg(Ptr1Reg).addImm(0).addImm(61);
7801 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7802 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7803 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7804 .addReg(newval).addReg(ShiftReg);
7805 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7806 .addReg(oldval).addReg(ShiftReg);
7808 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7810 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7811 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7812 .addReg(Mask3Reg).addImm(65535);
7814 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7815 .addReg(Mask2Reg).addReg(ShiftReg);
7816 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7817 .addReg(NewVal2Reg).addReg(MaskReg);
7818 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7819 .addReg(OldVal2Reg).addReg(MaskReg);
7822 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7823 .addReg(ZeroReg).addReg(PtrReg);
7824 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7825 .addReg(TmpDestReg).addReg(MaskReg);
7826 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7827 .addReg(TmpReg).addReg(OldVal3Reg);
7828 BuildMI(BB, dl, TII->get(PPC::BCC))
7829 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7830 BB->addSuccessor(loop2MBB);
7831 BB->addSuccessor(midMBB);
7834 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7835 .addReg(TmpDestReg).addReg(MaskReg);
7836 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7837 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7838 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7839 .addReg(ZeroReg).addReg(PtrReg);
7840 BuildMI(BB, dl, TII->get(PPC::BCC))
7841 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7842 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7843 BB->addSuccessor(loop1MBB);
7844 BB->addSuccessor(exitMBB);
7847 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7848 .addReg(ZeroReg).addReg(PtrReg);
7849 BB->addSuccessor(exitMBB);
7854 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7856 } else if (MI->getOpcode() == PPC::FADDrtz) {
7857 // This pseudo performs an FADD with rounding mode temporarily forced
7858 // to round-to-zero. We emit this via custom inserter since the FPSCR
7859 // is not modeled at the SelectionDAG level.
7860 unsigned Dest = MI->getOperand(0).getReg();
7861 unsigned Src1 = MI->getOperand(1).getReg();
7862 unsigned Src2 = MI->getOperand(2).getReg();
7863 DebugLoc dl = MI->getDebugLoc();
7865 MachineRegisterInfo &RegInfo = F->getRegInfo();
7866 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7868 // Save FPSCR value.
7869 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7871 // Set rounding mode to round-to-zero.
7872 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7873 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7875 // Perform addition.
7876 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7878 // Restore FPSCR value.
7879 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
7880 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7881 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7882 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7883 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7884 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7885 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7886 PPC::ANDIo8 : PPC::ANDIo;
7887 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7888 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7890 MachineRegisterInfo &RegInfo = F->getRegInfo();
7891 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7892 &PPC::GPRCRegClass :
7893 &PPC::G8RCRegClass);
7895 DebugLoc dl = MI->getDebugLoc();
7896 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7897 .addReg(MI->getOperand(1).getReg()).addImm(1);
7898 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7899 MI->getOperand(0).getReg())
7900 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7902 llvm_unreachable("Unexpected instr type to insert");
7905 MI->eraseFromParent(); // The pseudo instruction is gone now.
7909 //===----------------------------------------------------------------------===//
7910 // Target Optimization Hooks
7911 //===----------------------------------------------------------------------===//
7913 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7914 DAGCombinerInfo &DCI,
7915 unsigned &RefinementSteps,
7916 bool &UseOneConstNR) const {
7917 EVT VT = Operand.getValueType();
7918 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7919 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7920 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7921 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7922 // Convergence is quadratic, so we essentially double the number of digits
7923 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7924 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7925 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7926 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7927 if (VT.getScalarType() == MVT::f64)
7929 UseOneConstNR = true;
7930 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7935 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7936 DAGCombinerInfo &DCI,
7937 unsigned &RefinementSteps) const {
7938 EVT VT = Operand.getValueType();
7939 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7940 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7941 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7942 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7943 // Convergence is quadratic, so we essentially double the number of digits
7944 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7945 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7946 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7947 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7948 if (VT.getScalarType() == MVT::f64)
7950 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7955 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7956 // Note: This functionality is used only when unsafe-fp-math is enabled, and
7957 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7958 // enabled for division), this functionality is redundant with the default
7959 // combiner logic (once the division -> reciprocal/multiply transformation
7960 // has taken place). As a result, this matters more for older cores than for
7963 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7964 // reciprocal if there are two or more FDIVs (for embedded cores with only
7965 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7966 switch (Subtarget.getDarwinDirective()) {
7968 return NumUsers > 2;
7971 case PPC::DIR_E500mc:
7972 case PPC::DIR_E5500:
7973 return NumUsers > 1;
7977 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7978 unsigned Bytes, int Dist,
7979 SelectionDAG &DAG) {
7980 if (VT.getSizeInBits() / 8 != Bytes)
7983 SDValue BaseLoc = Base->getBasePtr();
7984 if (Loc.getOpcode() == ISD::FrameIndex) {
7985 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7987 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7988 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7989 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7990 int FS = MFI->getObjectSize(FI);
7991 int BFS = MFI->getObjectSize(BFI);
7992 if (FS != BFS || FS != (int)Bytes) return false;
7993 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7997 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7998 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8002 const GlobalValue *GV1 = nullptr;
8003 const GlobalValue *GV2 = nullptr;
8004 int64_t Offset1 = 0;
8005 int64_t Offset2 = 0;
8006 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8007 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8008 if (isGA1 && isGA2 && GV1 == GV2)
8009 return Offset1 == (Offset2 + Dist*Bytes);
8013 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8014 // not enforce equality of the chain operands.
8015 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8016 unsigned Bytes, int Dist,
8017 SelectionDAG &DAG) {
8018 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8019 EVT VT = LS->getMemoryVT();
8020 SDValue Loc = LS->getBasePtr();
8021 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8024 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8026 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8027 default: return false;
8028 case Intrinsic::ppc_altivec_lvx:
8029 case Intrinsic::ppc_altivec_lvxl:
8030 case Intrinsic::ppc_vsx_lxvw4x:
8033 case Intrinsic::ppc_vsx_lxvd2x:
8036 case Intrinsic::ppc_altivec_lvebx:
8039 case Intrinsic::ppc_altivec_lvehx:
8042 case Intrinsic::ppc_altivec_lvewx:
8047 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8050 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8052 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8053 default: return false;
8054 case Intrinsic::ppc_altivec_stvx:
8055 case Intrinsic::ppc_altivec_stvxl:
8056 case Intrinsic::ppc_vsx_stxvw4x:
8059 case Intrinsic::ppc_vsx_stxvd2x:
8062 case Intrinsic::ppc_altivec_stvebx:
8065 case Intrinsic::ppc_altivec_stvehx:
8068 case Intrinsic::ppc_altivec_stvewx:
8073 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8079 // Return true is there is a nearyby consecutive load to the one provided
8080 // (regardless of alignment). We search up and down the chain, looking though
8081 // token factors and other loads (but nothing else). As a result, a true result
8082 // indicates that it is safe to create a new consecutive load adjacent to the
8084 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8085 SDValue Chain = LD->getChain();
8086 EVT VT = LD->getMemoryVT();
8088 SmallSet<SDNode *, 16> LoadRoots;
8089 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8090 SmallSet<SDNode *, 16> Visited;
8092 // First, search up the chain, branching to follow all token-factor operands.
8093 // If we find a consecutive load, then we're done, otherwise, record all
8094 // nodes just above the top-level loads and token factors.
8095 while (!Queue.empty()) {
8096 SDNode *ChainNext = Queue.pop_back_val();
8097 if (!Visited.insert(ChainNext).second)
8100 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8101 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8104 if (!Visited.count(ChainLD->getChain().getNode()))
8105 Queue.push_back(ChainLD->getChain().getNode());
8106 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8107 for (const SDUse &O : ChainNext->ops())
8108 if (!Visited.count(O.getNode()))
8109 Queue.push_back(O.getNode());
8111 LoadRoots.insert(ChainNext);
8114 // Second, search down the chain, starting from the top-level nodes recorded
8115 // in the first phase. These top-level nodes are the nodes just above all
8116 // loads and token factors. Starting with their uses, recursively look though
8117 // all loads (just the chain uses) and token factors to find a consecutive
8122 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8123 IE = LoadRoots.end(); I != IE; ++I) {
8124 Queue.push_back(*I);
8126 while (!Queue.empty()) {
8127 SDNode *LoadRoot = Queue.pop_back_val();
8128 if (!Visited.insert(LoadRoot).second)
8131 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8132 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8135 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8136 UE = LoadRoot->use_end(); UI != UE; ++UI)
8137 if (((isa<MemSDNode>(*UI) &&
8138 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8139 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8140 Queue.push_back(*UI);
8147 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8148 DAGCombinerInfo &DCI) const {
8149 SelectionDAG &DAG = DCI.DAG;
8152 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8153 // If we're tracking CR bits, we need to be careful that we don't have:
8154 // trunc(binary-ops(zext(x), zext(y)))
8156 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8157 // such that we're unnecessarily moving things into GPRs when it would be
8158 // better to keep them in CR bits.
8160 // Note that trunc here can be an actual i1 trunc, or can be the effective
8161 // truncation that comes from a setcc or select_cc.
8162 if (N->getOpcode() == ISD::TRUNCATE &&
8163 N->getValueType(0) != MVT::i1)
8166 if (N->getOperand(0).getValueType() != MVT::i32 &&
8167 N->getOperand(0).getValueType() != MVT::i64)
8170 if (N->getOpcode() == ISD::SETCC ||
8171 N->getOpcode() == ISD::SELECT_CC) {
8172 // If we're looking at a comparison, then we need to make sure that the
8173 // high bits (all except for the first) don't matter the result.
8175 cast<CondCodeSDNode>(N->getOperand(
8176 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8177 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8179 if (ISD::isSignedIntSetCC(CC)) {
8180 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
8181 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
8183 } else if (ISD::isUnsignedIntSetCC(CC)) {
8184 if (!DAG.MaskedValueIsZero(N->getOperand(0),
8185 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
8186 !DAG.MaskedValueIsZero(N->getOperand(1),
8187 APInt::getHighBitsSet(OpBits, OpBits-1)))
8190 // This is neither a signed nor an unsigned comparison, just make sure
8191 // that the high bits are equal.
8192 APInt Op1Zero, Op1One;
8193 APInt Op2Zero, Op2One;
8194 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8195 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8197 // We don't really care about what is known about the first bit (if
8198 // anything), so clear it in all masks prior to comparing them.
8199 Op1Zero.clearBit(0); Op1One.clearBit(0);
8200 Op2Zero.clearBit(0); Op2One.clearBit(0);
8202 if (Op1Zero != Op2Zero || Op1One != Op2One)
8207 // We now know that the higher-order bits are irrelevant, we just need to
8208 // make sure that all of the intermediate operations are bit operations, and
8209 // all inputs are extensions.
8210 if (N->getOperand(0).getOpcode() != ISD::AND &&
8211 N->getOperand(0).getOpcode() != ISD::OR &&
8212 N->getOperand(0).getOpcode() != ISD::XOR &&
8213 N->getOperand(0).getOpcode() != ISD::SELECT &&
8214 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8215 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8216 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8217 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8218 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8221 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8222 N->getOperand(1).getOpcode() != ISD::AND &&
8223 N->getOperand(1).getOpcode() != ISD::OR &&
8224 N->getOperand(1).getOpcode() != ISD::XOR &&
8225 N->getOperand(1).getOpcode() != ISD::SELECT &&
8226 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8227 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8228 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8229 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8230 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8233 SmallVector<SDValue, 4> Inputs;
8234 SmallVector<SDValue, 8> BinOps, PromOps;
8235 SmallPtrSet<SDNode *, 16> Visited;
8237 for (unsigned i = 0; i < 2; ++i) {
8238 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8239 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8240 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8241 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8242 isa<ConstantSDNode>(N->getOperand(i)))
8243 Inputs.push_back(N->getOperand(i));
8245 BinOps.push_back(N->getOperand(i));
8247 if (N->getOpcode() == ISD::TRUNCATE)
8251 // Visit all inputs, collect all binary operations (and, or, xor and
8252 // select) that are all fed by extensions.
8253 while (!BinOps.empty()) {
8254 SDValue BinOp = BinOps.back();
8257 if (!Visited.insert(BinOp.getNode()).second)
8260 PromOps.push_back(BinOp);
8262 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8263 // The condition of the select is not promoted.
8264 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8266 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8269 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8270 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8271 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8272 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8273 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8274 Inputs.push_back(BinOp.getOperand(i));
8275 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8276 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8277 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8278 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8279 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8280 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8281 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8282 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8283 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8284 BinOps.push_back(BinOp.getOperand(i));
8286 // We have an input that is not an extension or another binary
8287 // operation; we'll abort this transformation.
8293 // Make sure that this is a self-contained cluster of operations (which
8294 // is not quite the same thing as saying that everything has only one
8296 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8297 if (isa<ConstantSDNode>(Inputs[i]))
8300 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8301 UE = Inputs[i].getNode()->use_end();
8304 if (User != N && !Visited.count(User))
8307 // Make sure that we're not going to promote the non-output-value
8308 // operand(s) or SELECT or SELECT_CC.
8309 // FIXME: Although we could sometimes handle this, and it does occur in
8310 // practice that one of the condition inputs to the select is also one of
8311 // the outputs, we currently can't deal with this.
8312 if (User->getOpcode() == ISD::SELECT) {
8313 if (User->getOperand(0) == Inputs[i])
8315 } else if (User->getOpcode() == ISD::SELECT_CC) {
8316 if (User->getOperand(0) == Inputs[i] ||
8317 User->getOperand(1) == Inputs[i])
8323 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8324 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8325 UE = PromOps[i].getNode()->use_end();
8328 if (User != N && !Visited.count(User))
8331 // Make sure that we're not going to promote the non-output-value
8332 // operand(s) or SELECT or SELECT_CC.
8333 // FIXME: Although we could sometimes handle this, and it does occur in
8334 // practice that one of the condition inputs to the select is also one of
8335 // the outputs, we currently can't deal with this.
8336 if (User->getOpcode() == ISD::SELECT) {
8337 if (User->getOperand(0) == PromOps[i])
8339 } else if (User->getOpcode() == ISD::SELECT_CC) {
8340 if (User->getOperand(0) == PromOps[i] ||
8341 User->getOperand(1) == PromOps[i])
8347 // Replace all inputs with the extension operand.
8348 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8349 // Constants may have users outside the cluster of to-be-promoted nodes,
8350 // and so we need to replace those as we do the promotions.
8351 if (isa<ConstantSDNode>(Inputs[i]))
8354 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
8357 // Replace all operations (these are all the same, but have a different
8358 // (i1) return type). DAG.getNode will validate that the types of
8359 // a binary operator match, so go through the list in reverse so that
8360 // we've likely promoted both operands first. Any intermediate truncations or
8361 // extensions disappear.
8362 while (!PromOps.empty()) {
8363 SDValue PromOp = PromOps.back();
8366 if (PromOp.getOpcode() == ISD::TRUNCATE ||
8367 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8368 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8369 PromOp.getOpcode() == ISD::ANY_EXTEND) {
8370 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8371 PromOp.getOperand(0).getValueType() != MVT::i1) {
8372 // The operand is not yet ready (see comment below).
8373 PromOps.insert(PromOps.begin(), PromOp);
8377 SDValue RepValue = PromOp.getOperand(0);
8378 if (isa<ConstantSDNode>(RepValue))
8379 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8381 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8386 switch (PromOp.getOpcode()) {
8387 default: C = 0; break;
8388 case ISD::SELECT: C = 1; break;
8389 case ISD::SELECT_CC: C = 2; break;
8392 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8393 PromOp.getOperand(C).getValueType() != MVT::i1) ||
8394 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8395 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8396 // The to-be-promoted operands of this node have not yet been
8397 // promoted (this should be rare because we're going through the
8398 // list backward, but if one of the operands has several users in
8399 // this cluster of to-be-promoted nodes, it is possible).
8400 PromOps.insert(PromOps.begin(), PromOp);
8404 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8405 PromOp.getNode()->op_end());
8407 // If there are any constant inputs, make sure they're replaced now.
8408 for (unsigned i = 0; i < 2; ++i)
8409 if (isa<ConstantSDNode>(Ops[C+i]))
8410 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8412 DAG.ReplaceAllUsesOfValueWith(PromOp,
8413 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8416 // Now we're left with the initial truncation itself.
8417 if (N->getOpcode() == ISD::TRUNCATE)
8418 return N->getOperand(0);
8420 // Otherwise, this is a comparison. The operands to be compared have just
8421 // changed type (to i1), but everything else is the same.
8422 return SDValue(N, 0);
8425 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8426 DAGCombinerInfo &DCI) const {
8427 SelectionDAG &DAG = DCI.DAG;
8430 // If we're tracking CR bits, we need to be careful that we don't have:
8431 // zext(binary-ops(trunc(x), trunc(y)))
8433 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8434 // such that we're unnecessarily moving things into CR bits that can more
8435 // efficiently stay in GPRs. Note that if we're not certain that the high
8436 // bits are set as required by the final extension, we still may need to do
8437 // some masking to get the proper behavior.
8439 // This same functionality is important on PPC64 when dealing with
8440 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8441 // the return values of functions. Because it is so similar, it is handled
8444 if (N->getValueType(0) != MVT::i32 &&
8445 N->getValueType(0) != MVT::i64)
8448 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
8449 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
8452 if (N->getOperand(0).getOpcode() != ISD::AND &&
8453 N->getOperand(0).getOpcode() != ISD::OR &&
8454 N->getOperand(0).getOpcode() != ISD::XOR &&
8455 N->getOperand(0).getOpcode() != ISD::SELECT &&
8456 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8459 SmallVector<SDValue, 4> Inputs;
8460 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8461 SmallPtrSet<SDNode *, 16> Visited;
8463 // Visit all inputs, collect all binary operations (and, or, xor and
8464 // select) that are all fed by truncations.
8465 while (!BinOps.empty()) {
8466 SDValue BinOp = BinOps.back();
8469 if (!Visited.insert(BinOp.getNode()).second)
8472 PromOps.push_back(BinOp);
8474 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8475 // The condition of the select is not promoted.
8476 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8478 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8481 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8482 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8483 Inputs.push_back(BinOp.getOperand(i));
8484 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8485 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8486 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8487 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8488 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8489 BinOps.push_back(BinOp.getOperand(i));
8491 // We have an input that is not a truncation or another binary
8492 // operation; we'll abort this transformation.
8498 // The operands of a select that must be truncated when the select is
8499 // promoted because the operand is actually part of the to-be-promoted set.
8500 DenseMap<SDNode *, EVT> SelectTruncOp[2];
8502 // Make sure that this is a self-contained cluster of operations (which
8503 // is not quite the same thing as saying that everything has only one
8505 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8506 if (isa<ConstantSDNode>(Inputs[i]))
8509 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8510 UE = Inputs[i].getNode()->use_end();
8513 if (User != N && !Visited.count(User))
8516 // If we're going to promote the non-output-value operand(s) or SELECT or
8517 // SELECT_CC, record them for truncation.
8518 if (User->getOpcode() == ISD::SELECT) {
8519 if (User->getOperand(0) == Inputs[i])
8520 SelectTruncOp[0].insert(std::make_pair(User,
8521 User->getOperand(0).getValueType()));
8522 } else if (User->getOpcode() == ISD::SELECT_CC) {
8523 if (User->getOperand(0) == Inputs[i])
8524 SelectTruncOp[0].insert(std::make_pair(User,
8525 User->getOperand(0).getValueType()));
8526 if (User->getOperand(1) == Inputs[i])
8527 SelectTruncOp[1].insert(std::make_pair(User,
8528 User->getOperand(1).getValueType()));
8533 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8534 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8535 UE = PromOps[i].getNode()->use_end();
8538 if (User != N && !Visited.count(User))
8541 // If we're going to promote the non-output-value operand(s) or SELECT or
8542 // SELECT_CC, record them for truncation.
8543 if (User->getOpcode() == ISD::SELECT) {
8544 if (User->getOperand(0) == PromOps[i])
8545 SelectTruncOp[0].insert(std::make_pair(User,
8546 User->getOperand(0).getValueType()));
8547 } else if (User->getOpcode() == ISD::SELECT_CC) {
8548 if (User->getOperand(0) == PromOps[i])
8549 SelectTruncOp[0].insert(std::make_pair(User,
8550 User->getOperand(0).getValueType()));
8551 if (User->getOperand(1) == PromOps[i])
8552 SelectTruncOp[1].insert(std::make_pair(User,
8553 User->getOperand(1).getValueType()));
8558 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8559 bool ReallyNeedsExt = false;
8560 if (N->getOpcode() != ISD::ANY_EXTEND) {
8561 // If all of the inputs are not already sign/zero extended, then
8562 // we'll still need to do that at the end.
8563 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8564 if (isa<ConstantSDNode>(Inputs[i]))
8568 Inputs[i].getOperand(0).getValueSizeInBits();
8569 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8571 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8572 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8573 APInt::getHighBitsSet(OpBits,
8574 OpBits-PromBits))) ||
8575 (N->getOpcode() == ISD::SIGN_EXTEND &&
8576 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8577 (OpBits-(PromBits-1)))) {
8578 ReallyNeedsExt = true;
8584 // Replace all inputs, either with the truncation operand, or a
8585 // truncation or extension to the final output type.
8586 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8587 // Constant inputs need to be replaced with the to-be-promoted nodes that
8588 // use them because they might have users outside of the cluster of
8590 if (isa<ConstantSDNode>(Inputs[i]))
8593 SDValue InSrc = Inputs[i].getOperand(0);
8594 if (Inputs[i].getValueType() == N->getValueType(0))
8595 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8596 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8597 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8598 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8599 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8600 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8601 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8603 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8604 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8607 // Replace all operations (these are all the same, but have a different
8608 // (promoted) return type). DAG.getNode will validate that the types of
8609 // a binary operator match, so go through the list in reverse so that
8610 // we've likely promoted both operands first.
8611 while (!PromOps.empty()) {
8612 SDValue PromOp = PromOps.back();
8616 switch (PromOp.getOpcode()) {
8617 default: C = 0; break;
8618 case ISD::SELECT: C = 1; break;
8619 case ISD::SELECT_CC: C = 2; break;
8622 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8623 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8624 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8625 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8626 // The to-be-promoted operands of this node have not yet been
8627 // promoted (this should be rare because we're going through the
8628 // list backward, but if one of the operands has several users in
8629 // this cluster of to-be-promoted nodes, it is possible).
8630 PromOps.insert(PromOps.begin(), PromOp);
8634 // For SELECT and SELECT_CC nodes, we do a similar check for any
8635 // to-be-promoted comparison inputs.
8636 if (PromOp.getOpcode() == ISD::SELECT ||
8637 PromOp.getOpcode() == ISD::SELECT_CC) {
8638 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8639 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8640 (SelectTruncOp[1].count(PromOp.getNode()) &&
8641 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8642 PromOps.insert(PromOps.begin(), PromOp);
8647 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8648 PromOp.getNode()->op_end());
8650 // If this node has constant inputs, then they'll need to be promoted here.
8651 for (unsigned i = 0; i < 2; ++i) {
8652 if (!isa<ConstantSDNode>(Ops[C+i]))
8654 if (Ops[C+i].getValueType() == N->getValueType(0))
8657 if (N->getOpcode() == ISD::SIGN_EXTEND)
8658 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8659 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8660 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8662 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8665 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8666 // truncate them again to the original value type.
8667 if (PromOp.getOpcode() == ISD::SELECT ||
8668 PromOp.getOpcode() == ISD::SELECT_CC) {
8669 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8670 if (SI0 != SelectTruncOp[0].end())
8671 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8672 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8673 if (SI1 != SelectTruncOp[1].end())
8674 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8677 DAG.ReplaceAllUsesOfValueWith(PromOp,
8678 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8681 // Now we're left with the initial extension itself.
8682 if (!ReallyNeedsExt)
8683 return N->getOperand(0);
8685 // To zero extend, just mask off everything except for the first bit (in the
8687 if (N->getOpcode() == ISD::ZERO_EXTEND)
8688 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8689 DAG.getConstant(APInt::getLowBitsSet(
8690 N->getValueSizeInBits(0), PromBits),
8691 N->getValueType(0)));
8693 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8694 "Invalid extension type");
8695 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8697 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8698 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8699 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8700 N->getOperand(0), ShiftCst), ShiftCst);
8703 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8704 DAGCombinerInfo &DCI) const {
8705 assert((N->getOpcode() == ISD::SINT_TO_FP ||
8706 N->getOpcode() == ISD::UINT_TO_FP) &&
8707 "Need an int -> FP conversion node here");
8709 if (!Subtarget.has64BitSupport())
8712 SelectionDAG &DAG = DCI.DAG;
8716 // Don't handle ppc_fp128 here or i1 conversions.
8717 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8719 if (Op.getOperand(0).getValueType() == MVT::i1)
8722 // For i32 intermediate values, unfortunately, the conversion functions
8723 // leave the upper 32 bits of the value are undefined. Within the set of
8724 // scalar instructions, we have no method for zero- or sign-extending the
8725 // value. Thus, we cannot handle i32 intermediate values here.
8726 if (Op.getOperand(0).getValueType() == MVT::i32)
8729 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8730 "UINT_TO_FP is supported only with FPCVT");
8732 // If we have FCFIDS, then use it when converting to single-precision.
8733 // Otherwise, convert to double-precision and then round.
8734 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8735 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8737 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8739 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8743 // If we're converting from a float, to an int, and back to a float again,
8744 // then we don't need the store/load pair at all.
8745 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8746 Subtarget.hasFPCVT()) ||
8747 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8748 SDValue Src = Op.getOperand(0).getOperand(0);
8749 if (Src.getValueType() == MVT::f32) {
8750 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8751 DCI.AddToWorklist(Src.getNode());
8755 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8758 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8759 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8761 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8762 FP = DAG.getNode(ISD::FP_ROUND, dl,
8763 MVT::f32, FP, DAG.getIntPtrConstant(0));
8764 DCI.AddToWorklist(FP.getNode());
8773 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8774 // builtins) into loads with swaps.
8775 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8776 DAGCombinerInfo &DCI) const {
8777 SelectionDAG &DAG = DCI.DAG;
8781 MachineMemOperand *MMO;
8783 switch (N->getOpcode()) {
8785 llvm_unreachable("Unexpected opcode for little endian VSX load");
8787 LoadSDNode *LD = cast<LoadSDNode>(N);
8788 Chain = LD->getChain();
8789 Base = LD->getBasePtr();
8790 MMO = LD->getMemOperand();
8791 // If the MMO suggests this isn't a load of a full vector, leave
8792 // things alone. For a built-in, we have to make the change for
8793 // correctness, so if there is a size problem that will be a bug.
8794 if (MMO->getSize() < 16)
8798 case ISD::INTRINSIC_W_CHAIN: {
8799 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8800 Chain = Intrin->getChain();
8801 Base = Intrin->getBasePtr();
8802 MMO = Intrin->getMemOperand();
8807 MVT VecTy = N->getValueType(0).getSimpleVT();
8808 SDValue LoadOps[] = { Chain, Base };
8809 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8810 DAG.getVTList(VecTy, MVT::Other),
8811 LoadOps, VecTy, MMO);
8812 DCI.AddToWorklist(Load.getNode());
8813 Chain = Load.getValue(1);
8814 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8815 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8816 DCI.AddToWorklist(Swap.getNode());
8820 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8821 // builtins) into stores with swaps.
8822 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8823 DAGCombinerInfo &DCI) const {
8824 SelectionDAG &DAG = DCI.DAG;
8829 MachineMemOperand *MMO;
8831 switch (N->getOpcode()) {
8833 llvm_unreachable("Unexpected opcode for little endian VSX store");
8835 StoreSDNode *ST = cast<StoreSDNode>(N);
8836 Chain = ST->getChain();
8837 Base = ST->getBasePtr();
8838 MMO = ST->getMemOperand();
8840 // If the MMO suggests this isn't a store of a full vector, leave
8841 // things alone. For a built-in, we have to make the change for
8842 // correctness, so if there is a size problem that will be a bug.
8843 if (MMO->getSize() < 16)
8847 case ISD::INTRINSIC_VOID: {
8848 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8849 Chain = Intrin->getChain();
8850 // Intrin->getBasePtr() oddly does not get what we want.
8851 Base = Intrin->getOperand(3);
8852 MMO = Intrin->getMemOperand();
8858 SDValue Src = N->getOperand(SrcOpnd);
8859 MVT VecTy = Src.getValueType().getSimpleVT();
8860 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8861 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8862 DCI.AddToWorklist(Swap.getNode());
8863 Chain = Swap.getValue(1);
8864 SDValue StoreOps[] = { Chain, Swap, Base };
8865 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8866 DAG.getVTList(MVT::Other),
8867 StoreOps, VecTy, MMO);
8868 DCI.AddToWorklist(Store.getNode());
8872 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8873 DAGCombinerInfo &DCI) const {
8874 SelectionDAG &DAG = DCI.DAG;
8876 switch (N->getOpcode()) {
8879 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8880 if (C->isNullValue()) // 0 << V -> 0.
8881 return N->getOperand(0);
8885 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8886 if (C->isNullValue()) // 0 >>u V -> 0.
8887 return N->getOperand(0);
8891 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8892 if (C->isNullValue() || // 0 >>s V -> 0.
8893 C->isAllOnesValue()) // -1 >>s V -> -1.
8894 return N->getOperand(0);
8897 case ISD::SIGN_EXTEND:
8898 case ISD::ZERO_EXTEND:
8899 case ISD::ANY_EXTEND:
8900 return DAGCombineExtBoolTrunc(N, DCI);
8903 case ISD::SELECT_CC:
8904 return DAGCombineTruncBoolExt(N, DCI);
8905 case ISD::SINT_TO_FP:
8906 case ISD::UINT_TO_FP:
8907 return combineFPToIntToFP(N, DCI);
8909 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8910 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
8911 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8912 N->getOperand(1).getValueType() == MVT::i32 &&
8913 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8914 SDValue Val = N->getOperand(1).getOperand(0);
8915 if (Val.getValueType() == MVT::f32) {
8916 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8917 DCI.AddToWorklist(Val.getNode());
8919 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8920 DCI.AddToWorklist(Val.getNode());
8923 N->getOperand(0), Val, N->getOperand(2),
8924 DAG.getValueType(N->getOperand(1).getValueType())
8927 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8928 DAG.getVTList(MVT::Other), Ops,
8929 cast<StoreSDNode>(N)->getMemoryVT(),
8930 cast<StoreSDNode>(N)->getMemOperand());
8931 DCI.AddToWorklist(Val.getNode());
8935 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8936 if (cast<StoreSDNode>(N)->isUnindexed() &&
8937 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8938 N->getOperand(1).getNode()->hasOneUse() &&
8939 (N->getOperand(1).getValueType() == MVT::i32 ||
8940 N->getOperand(1).getValueType() == MVT::i16 ||
8941 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
8942 N->getOperand(1).getValueType() == MVT::i64))) {
8943 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8944 // Do an any-extend to 32-bits if this is a half-word input.
8945 if (BSwapOp.getValueType() == MVT::i16)
8946 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8949 N->getOperand(0), BSwapOp, N->getOperand(2),
8950 DAG.getValueType(N->getOperand(1).getValueType())
8953 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8954 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8955 cast<StoreSDNode>(N)->getMemOperand());
8958 // For little endian, VSX stores require generating xxswapd/lxvd2x.
8959 EVT VT = N->getOperand(1).getValueType();
8960 if (VT.isSimple()) {
8961 MVT StoreVT = VT.getSimpleVT();
8962 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8963 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8964 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8965 return expandVSXStoreForLE(N, DCI);
8970 LoadSDNode *LD = cast<LoadSDNode>(N);
8971 EVT VT = LD->getValueType(0);
8973 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8974 if (VT.isSimple()) {
8975 MVT LoadVT = VT.getSimpleVT();
8976 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8977 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8978 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8979 return expandVSXLoadForLE(N, DCI);
8982 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8983 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8984 if (ISD::isNON_EXTLoad(N) && VT.isVector() && Subtarget.hasAltivec() &&
8985 // P8 and later hardware should just use LOAD.
8986 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8987 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8988 LD->getAlignment() < ABIAlignment) {
8989 // This is a type-legal unaligned Altivec load.
8990 SDValue Chain = LD->getChain();
8991 SDValue Ptr = LD->getBasePtr();
8992 bool isLittleEndian = Subtarget.isLittleEndian();
8994 // This implements the loading of unaligned vectors as described in
8995 // the venerable Apple Velocity Engine overview. Specifically:
8996 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8997 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8999 // The general idea is to expand a sequence of one or more unaligned
9000 // loads into an alignment-based permutation-control instruction (lvsl
9001 // or lvsr), a series of regular vector loads (which always truncate
9002 // their input address to an aligned address), and a series of
9003 // permutations. The results of these permutations are the requested
9004 // loaded values. The trick is that the last "extra" load is not taken
9005 // from the address you might suspect (sizeof(vector) bytes after the
9006 // last requested load), but rather sizeof(vector) - 1 bytes after the
9007 // last requested vector. The point of this is to avoid a page fault if
9008 // the base address happened to be aligned. This works because if the
9009 // base address is aligned, then adding less than a full vector length
9010 // will cause the last vector in the sequence to be (re)loaded.
9011 // Otherwise, the next vector will be fetched as you might suspect was
9014 // We might be able to reuse the permutation generation from
9015 // a different base address offset from this one by an aligned amount.
9016 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9017 // optimization later.
9018 Intrinsic::ID Intr = (isLittleEndian ?
9019 Intrinsic::ppc_altivec_lvsr :
9020 Intrinsic::ppc_altivec_lvsl);
9021 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
9023 // Create the new MMO for the new base load. It is like the original MMO,
9024 // but represents an area in memory almost twice the vector size centered
9025 // on the original address. If the address is unaligned, we might start
9026 // reading up to (sizeof(vector)-1) bytes below the address of the
9027 // original unaligned load.
9028 MachineFunction &MF = DAG.getMachineFunction();
9029 MachineMemOperand *BaseMMO =
9030 MF.getMachineMemOperand(LD->getMemOperand(),
9031 -LD->getMemoryVT().getStoreSize()+1,
9032 2*LD->getMemoryVT().getStoreSize()-1);
9034 // Create the new base load.
9035 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
9037 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9039 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9040 DAG.getVTList(MVT::v4i32, MVT::Other),
9041 BaseLoadOps, MVT::v4i32, BaseMMO);
9043 // Note that the value of IncOffset (which is provided to the next
9044 // load's pointer info offset value, and thus used to calculate the
9045 // alignment), and the value of IncValue (which is actually used to
9046 // increment the pointer value) are different! This is because we
9047 // require the next load to appear to be aligned, even though it
9048 // is actually offset from the base pointer by a lesser amount.
9049 int IncOffset = VT.getSizeInBits() / 8;
9050 int IncValue = IncOffset;
9052 // Walk (both up and down) the chain looking for another load at the real
9053 // (aligned) offset (the alignment of the other load does not matter in
9054 // this case). If found, then do not use the offset reduction trick, as
9055 // that will prevent the loads from being later combined (as they would
9056 // otherwise be duplicates).
9057 if (!findConsecutiveLoad(LD, DAG))
9060 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9061 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9063 MachineMemOperand *ExtraMMO =
9064 MF.getMachineMemOperand(LD->getMemOperand(),
9065 1, 2*LD->getMemoryVT().getStoreSize()-1);
9066 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9068 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9069 DAG.getVTList(MVT::v4i32, MVT::Other),
9070 ExtraLoadOps, MVT::v4i32, ExtraMMO);
9072 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9073 BaseLoad.getValue(1), ExtraLoad.getValue(1));
9075 // Because vperm has a big-endian bias, we must reverse the order
9076 // of the input vectors and complement the permute control vector
9077 // when generating little endian code. We have already handled the
9078 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9079 // and ExtraLoad here.
9082 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9083 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9085 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9086 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9088 if (VT != MVT::v4i32)
9089 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
9091 // The output of the permutation is our loaded result, the TokenFactor is
9093 DCI.CombineTo(N, Perm, TF);
9094 return SDValue(N, 0);
9098 case ISD::INTRINSIC_WO_CHAIN: {
9099 bool isLittleEndian = Subtarget.isLittleEndian();
9100 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9101 : Intrinsic::ppc_altivec_lvsl);
9102 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
9103 N->getOperand(1)->getOpcode() == ISD::ADD) {
9104 SDValue Add = N->getOperand(1);
9106 if (DAG.MaskedValueIsZero(
9108 APInt::getAllOnesValue(4 /* 16 byte alignment */)
9110 Add.getValueType().getScalarType().getSizeInBits()))) {
9111 SDNode *BasePtr = Add->getOperand(0).getNode();
9112 for (SDNode::use_iterator UI = BasePtr->use_begin(),
9113 UE = BasePtr->use_end();
9115 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9116 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
9118 // We've found another LVSL/LVSR, and this address is an aligned
9119 // multiple of that one. The results will be the same, so use the
9120 // one we've just found instead.
9122 return SDValue(*UI, 0);
9130 case ISD::INTRINSIC_W_CHAIN: {
9131 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9132 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9133 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9136 case Intrinsic::ppc_vsx_lxvw4x:
9137 case Intrinsic::ppc_vsx_lxvd2x:
9138 return expandVSXLoadForLE(N, DCI);
9143 case ISD::INTRINSIC_VOID: {
9144 // For little endian, VSX stores require generating xxswapd/stxvd2x.
9145 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9146 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9149 case Intrinsic::ppc_vsx_stxvw4x:
9150 case Intrinsic::ppc_vsx_stxvd2x:
9151 return expandVSXStoreForLE(N, DCI);
9157 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
9158 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
9159 N->getOperand(0).hasOneUse() &&
9160 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
9161 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9162 N->getValueType(0) == MVT::i64))) {
9163 SDValue Load = N->getOperand(0);
9164 LoadSDNode *LD = cast<LoadSDNode>(Load);
9165 // Create the byte-swapping load.
9167 LD->getChain(), // Chain
9168 LD->getBasePtr(), // Ptr
9169 DAG.getValueType(N->getValueType(0)) // VT
9172 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
9173 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
9174 MVT::i64 : MVT::i32, MVT::Other),
9175 Ops, LD->getMemoryVT(), LD->getMemOperand());
9177 // If this is an i16 load, insert the truncate.
9178 SDValue ResVal = BSLoad;
9179 if (N->getValueType(0) == MVT::i16)
9180 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
9182 // First, combine the bswap away. This makes the value produced by the
9184 DCI.CombineTo(N, ResVal);
9186 // Next, combine the load away, we give it a bogus result value but a real
9187 // chain result. The result value is dead because the bswap is dead.
9188 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9190 // Return N so it doesn't get rechecked!
9191 return SDValue(N, 0);
9195 case PPCISD::VCMP: {
9196 // If a VCMPo node already exists with exactly the same operands as this
9197 // node, use its result instead of this node (VCMPo computes both a CR6 and
9198 // a normal output).
9200 if (!N->getOperand(0).hasOneUse() &&
9201 !N->getOperand(1).hasOneUse() &&
9202 !N->getOperand(2).hasOneUse()) {
9204 // Scan all of the users of the LHS, looking for VCMPo's that match.
9205 SDNode *VCMPoNode = nullptr;
9207 SDNode *LHSN = N->getOperand(0).getNode();
9208 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9210 if (UI->getOpcode() == PPCISD::VCMPo &&
9211 UI->getOperand(1) == N->getOperand(1) &&
9212 UI->getOperand(2) == N->getOperand(2) &&
9213 UI->getOperand(0) == N->getOperand(0)) {
9218 // If there is no VCMPo node, or if the flag value has a single use, don't
9220 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9223 // Look at the (necessarily single) use of the flag value. If it has a
9224 // chain, this transformation is more complex. Note that multiple things
9225 // could use the value result, which we should ignore.
9226 SDNode *FlagUser = nullptr;
9227 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9228 FlagUser == nullptr; ++UI) {
9229 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9231 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9232 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9239 // If the user is a MFOCRF instruction, we know this is safe.
9240 // Otherwise we give up for right now.
9241 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9242 return SDValue(VCMPoNode, 0);
9247 SDValue Cond = N->getOperand(1);
9248 SDValue Target = N->getOperand(2);
9250 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9251 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9252 Intrinsic::ppc_is_decremented_ctr_nonzero) {
9254 // We now need to make the intrinsic dead (it cannot be instruction
9256 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9257 assert(Cond.getNode()->hasOneUse() &&
9258 "Counter decrement has more than one use");
9260 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9261 N->getOperand(0), Target);
9266 // If this is a branch on an altivec predicate comparison, lower this so
9267 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
9268 // lowering is done pre-legalize, because the legalizer lowers the predicate
9269 // compare down to code that is difficult to reassemble.
9270 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9271 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9273 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9274 // value. If so, pass-through the AND to get to the intrinsic.
9275 if (LHS.getOpcode() == ISD::AND &&
9276 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9277 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9278 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9279 isa<ConstantSDNode>(LHS.getOperand(1)) &&
9280 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9282 LHS = LHS.getOperand(0);
9284 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9285 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9286 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9287 isa<ConstantSDNode>(RHS)) {
9288 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9289 "Counter decrement comparison is not EQ or NE");
9291 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9292 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9293 (CC == ISD::SETNE && !Val);
9295 // We now need to make the intrinsic dead (it cannot be instruction
9297 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9298 assert(LHS.getNode()->hasOneUse() &&
9299 "Counter decrement has more than one use");
9301 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9302 N->getOperand(0), N->getOperand(4));
9308 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9309 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9310 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9311 assert(isDot && "Can't compare against a vector result!");
9313 // If this is a comparison against something other than 0/1, then we know
9314 // that the condition is never/always true.
9315 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9316 if (Val != 0 && Val != 1) {
9317 if (CC == ISD::SETEQ) // Cond never true, remove branch.
9318 return N->getOperand(0);
9319 // Always !=, turn it into an unconditional branch.
9320 return DAG.getNode(ISD::BR, dl, MVT::Other,
9321 N->getOperand(0), N->getOperand(4));
9324 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9326 // Create the PPCISD altivec 'dot' comparison node.
9328 LHS.getOperand(2), // LHS of compare
9329 LHS.getOperand(3), // RHS of compare
9330 DAG.getConstant(CompareOpc, MVT::i32)
9332 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9333 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9335 // Unpack the result based on how the target uses it.
9336 PPC::Predicate CompOpc;
9337 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9338 default: // Can't happen, don't crash on invalid number though.
9339 case 0: // Branch on the value of the EQ bit of CR6.
9340 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9342 case 1: // Branch on the inverted value of the EQ bit of CR6.
9343 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9345 case 2: // Branch on the value of the LT bit of CR6.
9346 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9348 case 3: // Branch on the inverted value of the LT bit of CR6.
9349 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9353 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9354 DAG.getConstant(CompOpc, MVT::i32),
9355 DAG.getRegister(PPC::CR6, MVT::i32),
9356 N->getOperand(4), CompNode.getValue(1));
9366 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9368 std::vector<SDNode *> *Created) const {
9369 // fold (sdiv X, pow2)
9370 EVT VT = N->getValueType(0);
9371 if (VT == MVT::i64 && !Subtarget.isPPC64())
9373 if ((VT != MVT::i32 && VT != MVT::i64) ||
9374 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9378 SDValue N0 = N->getOperand(0);
9380 bool IsNegPow2 = (-Divisor).isPowerOf2();
9381 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9382 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9384 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9386 Created->push_back(Op.getNode());
9389 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9391 Created->push_back(Op.getNode());
9397 //===----------------------------------------------------------------------===//
9398 // Inline Assembly Support
9399 //===----------------------------------------------------------------------===//
9401 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9404 const SelectionDAG &DAG,
9405 unsigned Depth) const {
9406 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9407 switch (Op.getOpcode()) {
9409 case PPCISD::LBRX: {
9410 // lhbrx is known to have the top bits cleared out.
9411 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9412 KnownZero = 0xFFFF0000;
9415 case ISD::INTRINSIC_WO_CHAIN: {
9416 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9418 case Intrinsic::ppc_altivec_vcmpbfp_p:
9419 case Intrinsic::ppc_altivec_vcmpeqfp_p:
9420 case Intrinsic::ppc_altivec_vcmpequb_p:
9421 case Intrinsic::ppc_altivec_vcmpequh_p:
9422 case Intrinsic::ppc_altivec_vcmpequw_p:
9423 case Intrinsic::ppc_altivec_vcmpgefp_p:
9424 case Intrinsic::ppc_altivec_vcmpgtfp_p:
9425 case Intrinsic::ppc_altivec_vcmpgtsb_p:
9426 case Intrinsic::ppc_altivec_vcmpgtsh_p:
9427 case Intrinsic::ppc_altivec_vcmpgtsw_p:
9428 case Intrinsic::ppc_altivec_vcmpgtub_p:
9429 case Intrinsic::ppc_altivec_vcmpgtuh_p:
9430 case Intrinsic::ppc_altivec_vcmpgtuw_p:
9431 KnownZero = ~1U; // All bits but the low one are known to be zero.
9438 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9439 switch (Subtarget.getDarwinDirective()) {
9444 case PPC::DIR_PWR5X:
9446 case PPC::DIR_PWR6X:
9448 case PPC::DIR_PWR8: {
9452 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
9454 // For small loops (between 5 and 8 instructions), align to a 32-byte
9455 // boundary so that the entire loop fits in one instruction-cache line.
9456 uint64_t LoopSize = 0;
9457 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9458 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9459 LoopSize += TII->GetInstSizeInBytes(J);
9461 if (LoopSize > 16 && LoopSize <= 32)
9468 return TargetLowering::getPrefLoopAlignment(ML);
9471 /// getConstraintType - Given a constraint, return the type of
9472 /// constraint it is for this target.
9473 PPCTargetLowering::ConstraintType
9474 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9475 if (Constraint.size() == 1) {
9476 switch (Constraint[0]) {
9483 return C_RegisterClass;
9485 // FIXME: While Z does indicate a memory constraint, it specifically
9486 // indicates an r+r address (used in conjunction with the 'y' modifier
9487 // in the replacement string). Currently, we're forcing the base
9488 // register to be r0 in the asm printer (which is interpreted as zero)
9489 // and forming the complete address in the second register. This is
9493 } else if (Constraint == "wc") { // individual CR bits.
9494 return C_RegisterClass;
9495 } else if (Constraint == "wa" || Constraint == "wd" ||
9496 Constraint == "wf" || Constraint == "ws") {
9497 return C_RegisterClass; // VSX registers.
9499 return TargetLowering::getConstraintType(Constraint);
9502 /// Examine constraint type and operand type and determine a weight value.
9503 /// This object must already have been set up with the operand type
9504 /// and the current alternative constraint selected.
9505 TargetLowering::ConstraintWeight
9506 PPCTargetLowering::getSingleConstraintMatchWeight(
9507 AsmOperandInfo &info, const char *constraint) const {
9508 ConstraintWeight weight = CW_Invalid;
9509 Value *CallOperandVal = info.CallOperandVal;
9510 // If we don't have a value, we can't do a match,
9511 // but allow it at the lowest weight.
9512 if (!CallOperandVal)
9514 Type *type = CallOperandVal->getType();
9516 // Look at the constraint type.
9517 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9518 return CW_Register; // an individual CR bit.
9519 else if ((StringRef(constraint) == "wa" ||
9520 StringRef(constraint) == "wd" ||
9521 StringRef(constraint) == "wf") &&
9524 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9527 switch (*constraint) {
9529 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9532 if (type->isIntegerTy())
9533 weight = CW_Register;
9536 if (type->isFloatTy())
9537 weight = CW_Register;
9540 if (type->isDoubleTy())
9541 weight = CW_Register;
9544 if (type->isVectorTy())
9545 weight = CW_Register;
9548 weight = CW_Register;
9557 std::pair<unsigned, const TargetRegisterClass*>
9558 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9560 if (Constraint.size() == 1) {
9561 // GCC RS6000 Constraint Letters
9562 switch (Constraint[0]) {
9564 if (VT == MVT::i64 && Subtarget.isPPC64())
9565 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9566 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9568 if (VT == MVT::i64 && Subtarget.isPPC64())
9569 return std::make_pair(0U, &PPC::G8RCRegClass);
9570 return std::make_pair(0U, &PPC::GPRCRegClass);
9572 if (VT == MVT::f32 || VT == MVT::i32)
9573 return std::make_pair(0U, &PPC::F4RCRegClass);
9574 if (VT == MVT::f64 || VT == MVT::i64)
9575 return std::make_pair(0U, &PPC::F8RCRegClass);
9578 return std::make_pair(0U, &PPC::VRRCRegClass);
9580 return std::make_pair(0U, &PPC::CRRCRegClass);
9582 } else if (Constraint == "wc") { // an individual CR bit.
9583 return std::make_pair(0U, &PPC::CRBITRCRegClass);
9584 } else if (Constraint == "wa" || Constraint == "wd" ||
9585 Constraint == "wf") {
9586 return std::make_pair(0U, &PPC::VSRCRegClass);
9587 } else if (Constraint == "ws") {
9588 return std::make_pair(0U, &PPC::VSFRCRegClass);
9591 std::pair<unsigned, const TargetRegisterClass*> R =
9592 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9594 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9595 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9596 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9598 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9599 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9600 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9601 PPC::GPRCRegClass.contains(R.first)) {
9602 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9603 return std::make_pair(TRI->getMatchingSuperReg(R.first,
9604 PPC::sub_32, &PPC::G8RCRegClass),
9605 &PPC::G8RCRegClass);
9608 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9609 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9611 R.second = &PPC::CRRCRegClass;
9618 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9619 /// vector. If it is invalid, don't add anything to Ops.
9620 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9621 std::string &Constraint,
9622 std::vector<SDValue>&Ops,
9623 SelectionDAG &DAG) const {
9626 // Only support length 1 constraints.
9627 if (Constraint.length() > 1) return;
9629 char Letter = Constraint[0];
9640 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9641 if (!CST) return; // Must be an immediate to match.
9642 int64_t Value = CST->getSExtValue();
9643 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9644 // numbers are printed as such.
9646 default: llvm_unreachable("Unknown constraint letter!");
9647 case 'I': // "I" is a signed 16-bit constant.
9648 if (isInt<16>(Value))
9649 Result = DAG.getTargetConstant(Value, TCVT);
9651 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9652 if (isShiftedUInt<16, 16>(Value))
9653 Result = DAG.getTargetConstant(Value, TCVT);
9655 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9656 if (isShiftedInt<16, 16>(Value))
9657 Result = DAG.getTargetConstant(Value, TCVT);
9659 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9660 if (isUInt<16>(Value))
9661 Result = DAG.getTargetConstant(Value, TCVT);
9663 case 'M': // "M" is a constant that is greater than 31.
9665 Result = DAG.getTargetConstant(Value, TCVT);
9667 case 'N': // "N" is a positive constant that is an exact power of two.
9668 if (Value > 0 && isPowerOf2_64(Value))
9669 Result = DAG.getTargetConstant(Value, TCVT);
9671 case 'O': // "O" is the constant zero.
9673 Result = DAG.getTargetConstant(Value, TCVT);
9675 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9676 if (isInt<16>(-Value))
9677 Result = DAG.getTargetConstant(Value, TCVT);
9684 if (Result.getNode()) {
9685 Ops.push_back(Result);
9689 // Handle standard constraint letters.
9690 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9693 // isLegalAddressingMode - Return true if the addressing mode represented
9694 // by AM is legal for this target, for a load/store of the specified type.
9695 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9697 // FIXME: PPC does not allow r+i addressing modes for vectors!
9699 // PPC allows a sign-extended 16-bit immediate field.
9700 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9703 // No global is ever allowed as a base.
9707 // PPC only support r+r,
9709 case 0: // "r+i" or just "i", depending on HasBaseReg.
9712 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9714 // Otherwise we have r+r or r+i.
9717 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9719 // Allow 2*r as r+r.
9722 // No other scales are supported.
9729 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9730 SelectionDAG &DAG) const {
9731 MachineFunction &MF = DAG.getMachineFunction();
9732 MachineFrameInfo *MFI = MF.getFrameInfo();
9733 MFI->setReturnAddressIsTaken(true);
9735 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9739 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9741 // Make sure the function does not optimize away the store of the RA to
9743 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9744 FuncInfo->setLRStoreRequired();
9745 bool isPPC64 = Subtarget.isPPC64();
9746 bool isDarwinABI = Subtarget.isDarwinABI();
9749 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9752 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9753 isPPC64? MVT::i64 : MVT::i32);
9754 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9755 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9757 MachinePointerInfo(), false, false, false, 0);
9760 // Just load the return address off the stack.
9761 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9762 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9763 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9766 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9767 SelectionDAG &DAG) const {
9769 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9771 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9772 bool isPPC64 = PtrVT == MVT::i64;
9774 MachineFunction &MF = DAG.getMachineFunction();
9775 MachineFrameInfo *MFI = MF.getFrameInfo();
9776 MFI->setFrameAddressIsTaken(true);
9778 // Naked functions never have a frame pointer, and so we use r1. For all
9779 // other functions, this decision must be delayed until during PEI.
9781 if (MF.getFunction()->getAttributes().hasAttribute(
9782 AttributeSet::FunctionIndex, Attribute::Naked))
9783 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9785 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9787 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9790 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9791 FrameAddr, MachinePointerInfo(), false, false,
9796 // FIXME? Maybe this could be a TableGen attribute on some registers and
9797 // this table could be generated automatically from RegInfo.
9798 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9800 bool isPPC64 = Subtarget.isPPC64();
9801 bool isDarwinABI = Subtarget.isDarwinABI();
9803 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9804 (!isPPC64 && VT != MVT::i32))
9805 report_fatal_error("Invalid register global variable type");
9807 bool is64Bit = isPPC64 && VT == MVT::i64;
9808 unsigned Reg = StringSwitch<unsigned>(RegName)
9809 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9810 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
9811 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9812 (is64Bit ? PPC::X13 : PPC::R13))
9817 report_fatal_error("Invalid register name global variable");
9821 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9822 // The PowerPC target isn't yet aware of offsets.
9826 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9828 unsigned Intrinsic) const {
9830 switch (Intrinsic) {
9831 case Intrinsic::ppc_altivec_lvx:
9832 case Intrinsic::ppc_altivec_lvxl:
9833 case Intrinsic::ppc_altivec_lvebx:
9834 case Intrinsic::ppc_altivec_lvehx:
9835 case Intrinsic::ppc_altivec_lvewx:
9836 case Intrinsic::ppc_vsx_lxvd2x:
9837 case Intrinsic::ppc_vsx_lxvw4x: {
9839 switch (Intrinsic) {
9840 case Intrinsic::ppc_altivec_lvebx:
9843 case Intrinsic::ppc_altivec_lvehx:
9846 case Intrinsic::ppc_altivec_lvewx:
9849 case Intrinsic::ppc_vsx_lxvd2x:
9857 Info.opc = ISD::INTRINSIC_W_CHAIN;
9859 Info.ptrVal = I.getArgOperand(0);
9860 Info.offset = -VT.getStoreSize()+1;
9861 Info.size = 2*VT.getStoreSize()-1;
9864 Info.readMem = true;
9865 Info.writeMem = false;
9868 case Intrinsic::ppc_altivec_stvx:
9869 case Intrinsic::ppc_altivec_stvxl:
9870 case Intrinsic::ppc_altivec_stvebx:
9871 case Intrinsic::ppc_altivec_stvehx:
9872 case Intrinsic::ppc_altivec_stvewx:
9873 case Intrinsic::ppc_vsx_stxvd2x:
9874 case Intrinsic::ppc_vsx_stxvw4x: {
9876 switch (Intrinsic) {
9877 case Intrinsic::ppc_altivec_stvebx:
9880 case Intrinsic::ppc_altivec_stvehx:
9883 case Intrinsic::ppc_altivec_stvewx:
9886 case Intrinsic::ppc_vsx_stxvd2x:
9894 Info.opc = ISD::INTRINSIC_VOID;
9896 Info.ptrVal = I.getArgOperand(1);
9897 Info.offset = -VT.getStoreSize()+1;
9898 Info.size = 2*VT.getStoreSize()-1;
9901 Info.readMem = false;
9902 Info.writeMem = true;
9912 /// getOptimalMemOpType - Returns the target specific optimal type for load
9913 /// and store operations as a result of memset, memcpy, and memmove
9914 /// lowering. If DstAlign is zero that means it's safe to destination
9915 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9916 /// means there isn't a need to check it against alignment requirement,
9917 /// probably because the source does not need to be loaded. If 'IsMemset' is
9918 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9919 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9920 /// source is constant so it does not need to be loaded.
9921 /// It returns EVT::Other if the type should be determined using generic
9922 /// target-independent logic.
9923 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9924 unsigned DstAlign, unsigned SrcAlign,
9925 bool IsMemset, bool ZeroMemset,
9927 MachineFunction &MF) const {
9928 if (Subtarget.isPPC64()) {
9935 /// \brief Returns true if it is beneficial to convert a load of a constant
9936 /// to just the constant itself.
9937 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9939 assert(Ty->isIntegerTy());
9941 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9942 if (BitSize == 0 || BitSize > 64)
9947 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9948 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9950 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9951 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9952 return NumBits1 == 64 && NumBits2 == 32;
9955 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9956 if (!VT1.isInteger() || !VT2.isInteger())
9958 unsigned NumBits1 = VT1.getSizeInBits();
9959 unsigned NumBits2 = VT2.getSizeInBits();
9960 return NumBits1 == 64 && NumBits2 == 32;
9963 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9964 // Generally speaking, zexts are not free, but they are free when they can be
9965 // folded with other operations.
9966 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
9967 EVT MemVT = LD->getMemoryVT();
9968 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
9969 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
9970 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
9971 LD->getExtensionType() == ISD::ZEXTLOAD))
9975 // FIXME: Add other cases...
9976 // - 32-bit shifts with a zext to i64
9977 // - zext after ctlz, bswap, etc.
9978 // - zext after and by a constant mask
9980 return TargetLowering::isZExtFree(Val, VT2);
9983 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
9984 assert(VT.isFloatingPoint());
9988 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9989 return isInt<16>(Imm) || isUInt<16>(Imm);
9992 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9993 return isInt<16>(Imm) || isUInt<16>(Imm);
9996 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10000 if (DisablePPCUnaligned)
10003 // PowerPC supports unaligned memory access for simple non-vector types.
10004 // Although accessing unaligned addresses is not as efficient as accessing
10005 // aligned addresses, it is generally more efficient than manual expansion,
10006 // and generally only traps for software emulation when crossing page
10009 if (!VT.isSimple())
10012 if (VT.getSimpleVT().isVector()) {
10013 if (Subtarget.hasVSX()) {
10014 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
10015 VT != MVT::v4f32 && VT != MVT::v4i32)
10022 if (VT == MVT::ppcf128)
10031 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
10032 VT = VT.getScalarType();
10034 if (!VT.isSimple())
10037 switch (VT.getSimpleVT().SimpleTy) {
10049 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
10050 // LR is a callee-save register, but we must treat it as clobbered by any call
10051 // site. Hence we include LR in the scratch registers, which are in turn added
10052 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
10053 // to CTR, which is used by any indirect call.
10054 static const MCPhysReg ScratchRegs[] = {
10055 PPC::X12, PPC::LR8, PPC::CTR8, 0
10058 return ScratchRegs;
10062 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
10063 EVT VT , unsigned DefinedValues) const {
10064 if (VT == MVT::v2i64)
10067 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
10070 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
10071 if (DisableILPPref || Subtarget.enableMachineScheduler())
10072 return TargetLowering::getSchedulingPreference(N);
10077 // Create a fast isel object.
10079 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
10080 const TargetLibraryInfo *LibInfo) const {
10081 return PPC::createFastISel(FuncInfo, LibInfo);