1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
41 using namespace llvm;
43 // FIXME: Remove this once soft-float is supported.
44 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
45 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
48 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
51 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
54 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56 // FIXME: Remove this once the bug has been fixed!
57 extern cl::opt<bool> ANDIGlueBug;
59 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
60 : TargetLowering(TM),
61 Subtarget(*TM.getSubtargetImpl()) {
62 // Use _setjmp/_longjmp instead of setjmp/longjmp.
63 setUseUnderscoreSetJmp(true);
64 setUseUnderscoreLongJmp(true);
66 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
67 // arguments are at least 4/8 bytes aligned.
68 bool isPPC64 = Subtarget.isPPC64();
69 setMinStackArgumentAlignment(isPPC64 ? 8:4);
71 // Set up the register classes.
72 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
73 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
74 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
77 for (MVT VT : MVT::integer_valuetypes()) {
78 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
79 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
80 }
82 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84 // PowerPC has pre-inc load and store's.
85 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
86 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
90 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
91 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
96 if (Subtarget.useCRBits()) {
97 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
99 if (isPPC64 || Subtarget.hasFPCVT()) {
100 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
101 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
102 isPPC64 ? MVT::i64 : MVT::i32);
103 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
104 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
105 isPPC64 ? MVT::i64 : MVT::i32);
106 } else {
107 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
108 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
109 }
111 // PowerPC does not support direct load / store of condition registers
112 setOperationAction(ISD::LOAD, MVT::i1, Custom);
113 setOperationAction(ISD::STORE, MVT::i1, Custom);
115 // FIXME: Remove this once the ANDI glue bug is fixed:
116 if (ANDIGlueBug)
117 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
119 for (MVT VT : MVT::integer_valuetypes()) {
120 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
121 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
122 setTruncStoreAction(VT, MVT::i1, Expand);
123 }
125 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
126 }
128 // This is used in the ppcf128->int sequence. Note it has different semantics
129 // from FP_ROUND: that rounds to nearest, this rounds to zero.
130 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
132 // We do not currently implement these libm ops for PowerPC.
133 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
134 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
140 // PowerPC has no SREM/UREM instructions
141 setOperationAction(ISD::SREM, MVT::i32, Expand);
142 setOperationAction(ISD::UREM, MVT::i32, Expand);
143 setOperationAction(ISD::SREM, MVT::i64, Expand);
144 setOperationAction(ISD::UREM, MVT::i64, Expand);
146 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
147 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
148 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
149 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
150 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
151 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
152 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
153 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
154 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
156 // We don't support sin/cos/sqrt/fmod/pow
157 setOperationAction(ISD::FSIN , MVT::f64, Expand);
158 setOperationAction(ISD::FCOS , MVT::f64, Expand);
159 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
160 setOperationAction(ISD::FREM , MVT::f64, Expand);
161 setOperationAction(ISD::FPOW , MVT::f64, Expand);
162 setOperationAction(ISD::FMA , MVT::f64, Legal);
163 setOperationAction(ISD::FSIN , MVT::f32, Expand);
164 setOperationAction(ISD::FCOS , MVT::f32, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
166 setOperationAction(ISD::FREM , MVT::f32, Expand);
167 setOperationAction(ISD::FPOW , MVT::f32, Expand);
168 setOperationAction(ISD::FMA , MVT::f32, Legal);
170 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
172 // If we're enabling GP optimizations, use hardware square root
173 if (!Subtarget.hasFSQRT() &&
174 !(TM.Options.UnsafeFPMath &&
175 Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
176 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
178 if (!Subtarget.hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
181 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
183 if (Subtarget.hasFCPSGN()) {
184 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
185 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
186 } else {
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
189 }
191 if (Subtarget.hasFPRND()) {
192 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
193 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
194 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
195 setOperationAction(ISD::FROUND, MVT::f64, Legal);
197 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
200 setOperationAction(ISD::FROUND, MVT::f32, Legal);
201 }
203 // PowerPC does not have BSWAP, CTPOP or CTTZ
204 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
205 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
206 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
207 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
208 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
209 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
210 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
211 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
213 if (Subtarget.hasPOPCNTD()) {
214 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
215 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
216 } else {
217 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
218 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
219 }
221 // PowerPC does not have ROTR
222 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
223 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
225 if (!Subtarget.useCRBits()) {
226 // PowerPC does not have Select
227 setOperationAction(ISD::SELECT, MVT::i32, Expand);
228 setOperationAction(ISD::SELECT, MVT::i64, Expand);
229 setOperationAction(ISD::SELECT, MVT::f32, Expand);
230 setOperationAction(ISD::SELECT, MVT::f64, Expand);
231 }
233 // PowerPC wants to turn select_cc of FP into fsel when possible.
234 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
235 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
237 // PowerPC wants to optimize integer setcc a bit
238 if (!Subtarget.useCRBits())
239 setOperationAction(ISD::SETCC, MVT::i32, Custom);
241 // PowerPC does not have BRCOND which requires SetCC
242 if (!Subtarget.useCRBits())
243 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
245 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
247 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 // PowerPC does not have [U|S]INT_TO_FP
251 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
252 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
254 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
256 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
257 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
259 // We cannot sextinreg(i1). Expand to shifts.
260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
262 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
263 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
264 // support continuation, user-level threading, and etc.. As a result, no
265 // other SjLj exception interfaces are implemented and please don't build
266 // your own exception handling based on them.
267 // LLVM/Clang supports zero-cost DWARF exception handling.
268 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
269 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
271 // We want to legalize GlobalAddress and ConstantPool nodes into the
272 // appropriate instructions to materialize the address.
273 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
274 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
275 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
276 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
277 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
278 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
284 // TRAP is legal.
285 setOperationAction(ISD::TRAP, MVT::Other, Legal);
287 // TRAMPOLINE is custom lowered.
288 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
289 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
291 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
292 setOperationAction(ISD::VASTART , MVT::Other, Custom);
294 if (Subtarget.isSVR4ABI()) {
295 if (isPPC64) {
296 // VAARG always uses double-word chunks, so promote anything smaller.
297 setOperationAction(ISD::VAARG, MVT::i1, Promote);
298 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
299 setOperationAction(ISD::VAARG, MVT::i8, Promote);
300 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
301 setOperationAction(ISD::VAARG, MVT::i16, Promote);
302 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
303 setOperationAction(ISD::VAARG, MVT::i32, Promote);
304 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
305 setOperationAction(ISD::VAARG, MVT::Other, Expand);
306 } else {
307 // VAARG is custom lowered with the 32-bit SVR4 ABI.
308 setOperationAction(ISD::VAARG, MVT::Other, Custom);
309 setOperationAction(ISD::VAARG, MVT::i64, Custom);
310 }
311 } else
312 setOperationAction(ISD::VAARG, MVT::Other, Expand);
314 if (Subtarget.isSVR4ABI() && !isPPC64)
315 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
316 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
317 else
318 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
320 // Use the default implementation.
321 setOperationAction(ISD::VAEND , MVT::Other, Expand);
322 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
323 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
327 // We want to custom lower some of our intrinsics.
328 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
330 // To handle counter-based loop conditions.
331 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
333 // Comparisons that require checking two conditions.
334 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
335 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
336 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
337 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
338 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
339 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
340 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
341 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
342 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
347 if (Subtarget.has64BitSupport()) {
348 // They also have instructions for converting between i64 and fp.
349 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
351 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
352 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
353 // This is just the low 32 bits of a (signed) fp->i64 conversion.
354 // We cannot do this with Promote because i64 is not a legal type.
355 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
357 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
358 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
359 } else {
360 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
362 }
364 // With the instructions enabled under FPCVT, we can do everything.
365 if (Subtarget.hasFPCVT()) {
366 if (Subtarget.has64BitSupport()) {
367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
368 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
369 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
370 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
371 }
373 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
374 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
375 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
376 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
377 }
379 if (Subtarget.use64BitRegs()) {
380 // 64-bit PowerPC implementations can support i64 types directly
381 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
382 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
383 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
384 // 64-bit PowerPC wants to expand i128 shifts itself.
385 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
386 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
387 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
388 } else {
389 // 32-bit PowerPC wants to expand i64 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
393 }
395 if (Subtarget.hasAltivec()) {
396 // First set operation action for all vector types to expand. Then we
397 // will selectively turn on ones that can be effectively codegen'd.
398 for (MVT VT : MVT::vector_valuetypes()) {
399 // add/sub are legal for all supported vector VT's.
400 setOperationAction(ISD::ADD , VT, Legal);
401 setOperationAction(ISD::SUB , VT, Legal);
403 // We promote all shuffles to v16i8.
404 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
405 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
407 // We promote all non-typed operations to v4i32.
408 setOperationAction(ISD::AND , VT, Promote);
409 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
410 setOperationAction(ISD::OR , VT, Promote);
411 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
412 setOperationAction(ISD::XOR , VT, Promote);
413 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
414 setOperationAction(ISD::LOAD , VT, Promote);
415 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
416 setOperationAction(ISD::SELECT, VT, Promote);
417 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
418 setOperationAction(ISD::STORE, VT, Promote);
419 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
421 // No other operations are legal.
422 setOperationAction(ISD::MUL , VT, Expand);
423 setOperationAction(ISD::SDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UDIV, VT, Expand);
426 setOperationAction(ISD::UREM, VT, Expand);
427 setOperationAction(ISD::FDIV, VT, Expand);
428 setOperationAction(ISD::FREM, VT, Expand);
429 setOperationAction(ISD::FNEG, VT, Expand);
430 setOperationAction(ISD::FSQRT, VT, Expand);
431 setOperationAction(ISD::FLOG, VT, Expand);
432 setOperationAction(ISD::FLOG10, VT, Expand);
433 setOperationAction(ISD::FLOG2, VT, Expand);
434 setOperationAction(ISD::FEXP, VT, Expand);
435 setOperationAction(ISD::FEXP2, VT, Expand);
436 setOperationAction(ISD::FSIN, VT, Expand);
437 setOperationAction(ISD::FCOS, VT, Expand);
438 setOperationAction(ISD::FABS, VT, Expand);
439 setOperationAction(ISD::FPOWI, VT, Expand);
440 setOperationAction(ISD::FFLOOR, VT, Expand);
441 setOperationAction(ISD::FCEIL, VT, Expand);
442 setOperationAction(ISD::FTRUNC, VT, Expand);
443 setOperationAction(ISD::FRINT, VT, Expand);
444 setOperationAction(ISD::FNEARBYINT, VT, Expand);
445 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
446 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
447 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
448 setOperationAction(ISD::MULHU, VT, Expand);
449 setOperationAction(ISD::MULHS, VT, Expand);
450 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
451 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
452 setOperationAction(ISD::UDIVREM, VT, Expand);
453 setOperationAction(ISD::SDIVREM, VT, Expand);
454 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
455 setOperationAction(ISD::FPOW, VT, Expand);
456 setOperationAction(ISD::BSWAP, VT, Expand);
457 setOperationAction(ISD::CTPOP, VT, Expand);
458 setOperationAction(ISD::CTLZ, VT, Expand);
459 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
460 setOperationAction(ISD::CTTZ, VT, Expand);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
462 setOperationAction(ISD::VSELECT, VT, Expand);
463 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
465 for (MVT InnerVT : MVT::vector_valuetypes()) {
466 setTruncStoreAction(VT, InnerVT, Expand);
467 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
468 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
469 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
470 }
471 }
473 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
474 // with merges, splats, etc.
475 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
477 setOperationAction(ISD::AND , MVT::v4i32, Legal);
478 setOperationAction(ISD::OR , MVT::v4i32, Legal);
479 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
480 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
481 setOperationAction(ISD::SELECT, MVT::v4i32,
482 Subtarget.useCRBits() ? Legal : Expand);
483 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
484 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
485 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
486 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
487 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
488 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
489 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
490 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
491 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
493 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
494 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
495 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
496 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
498 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
499 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
501 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
502 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
503 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
504 }
506 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
507 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
508 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
510 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
511 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
513 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
514 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
515 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
516 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
518 // Altivec does not contain unordered floating-point compare instructions
519 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
520 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
521 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
522 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
524 if (Subtarget.hasVSX()) {
525 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
526 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
528 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
529 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
530 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
531 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
532 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
534 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
536 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
537 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
539 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
540 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
542 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
543 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
544 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
545 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
546 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
548 // Share the Altivec comparison restrictions.
549 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
550 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
551 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
552 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
554 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
555 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
557 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
559 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
561 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
562 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
564 // VSX v2i64 only supports non-arithmetic operations.
565 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
566 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
568 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
569 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
570 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
572 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
574 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
575 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
576 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
577 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
579 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
581 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
582 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
583 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
584 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
586 // Vector operation legalization checks the result type of
587 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
588 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
589 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
590 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
591 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
593 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
594 }
595 }
597 if (Subtarget.has64BitSupport())
598 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
600 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
602 if (!isPPC64) {
603 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
604 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
605 }
607 setBooleanContents(ZeroOrOneBooleanContent);
608 // Altivec instructions set fields to all zeros or all ones.
609 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
611 if (!isPPC64) {
612 // These libcalls are not available in 32-bit.
613 setLibcallName(RTLIB::SHL_I128, nullptr);
614 setLibcallName(RTLIB::SRL_I128, nullptr);
615 setLibcallName(RTLIB::SRA_I128, nullptr);
616 }
618 if (isPPC64) {
619 setStackPointerRegisterToSaveRestore(PPC::X1);
620 setExceptionPointerRegister(PPC::X3);
621 setExceptionSelectorRegister(PPC::X4);
622 } else {
623 setStackPointerRegisterToSaveRestore(PPC::R1);
624 setExceptionPointerRegister(PPC::R3);
625 setExceptionSelectorRegister(PPC::R4);
626 }
628 // We have target-specific dag combine patterns for the following nodes:
629 setTargetDAGCombine(ISD::SINT_TO_FP);
630 if (Subtarget.hasFPCVT())
631 setTargetDAGCombine(ISD::UINT_TO_FP);
632 setTargetDAGCombine(ISD::LOAD);
633 setTargetDAGCombine(ISD::STORE);
634 setTargetDAGCombine(ISD::BR_CC);
635 if (Subtarget.useCRBits())
636 setTargetDAGCombine(ISD::BRCOND);
637 setTargetDAGCombine(ISD::BSWAP);
638 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
639 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
640 setTargetDAGCombine(ISD::INTRINSIC_VOID);
642 setTargetDAGCombine(ISD::SIGN_EXTEND);
643 setTargetDAGCombine(ISD::ZERO_EXTEND);
644 setTargetDAGCombine(ISD::ANY_EXTEND);
646 if (Subtarget.useCRBits()) {
647 setTargetDAGCombine(ISD::TRUNCATE);
648 setTargetDAGCombine(ISD::SETCC);
649 setTargetDAGCombine(ISD::SELECT_CC);
650 }
652 // Use reciprocal estimates.
653 if (TM.Options.UnsafeFPMath) {
654 setTargetDAGCombine(ISD::FDIV);
655 setTargetDAGCombine(ISD::FSQRT);
656 }
658 // Darwin long double math library functions have $LDBL128 appended.
659 if (Subtarget.isDarwin()) {
660 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
661 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
662 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
663 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
664 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
665 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
666 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
667 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
668 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
669 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
670 }
672 // With 32 condition bits, we don't need to sink (and duplicate) compares
673 // aggressively in CodeGenPrep.
674 if (Subtarget.useCRBits())
675 setHasMultipleConditionRegisters();
677 setMinFunctionAlignment(2);
678 if (Subtarget.isDarwin())
679 setPrefFunctionAlignment(4);
681 switch (Subtarget.getDarwinDirective()) {
682 default: break;
683 case PPC::DIR_970:
684 case PPC::DIR_A2:
685 case PPC::DIR_E500mc:
686 case PPC::DIR_E5500:
687 case PPC::DIR_PWR4:
688 case PPC::DIR_PWR5:
689 case PPC::DIR_PWR5X:
690 case PPC::DIR_PWR6:
691 case PPC::DIR_PWR6X:
692 case PPC::DIR_PWR7:
693 case PPC::DIR_PWR8:
694 setPrefFunctionAlignment(4);
695 setPrefLoopAlignment(4);
696 break;
697 }
699 setInsertFencesForAtomic(true);
701 if (Subtarget.enableMachineScheduler())
702 setSchedulingPreference(Sched::Source);
703 else
704 setSchedulingPreference(Sched::Hybrid);
706 computeRegisterProperties();
708 // The Freescale cores do better with aggressive inlining of memcpy and
709 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
710 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
711 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
712 MaxStoresPerMemset = 32;
713 MaxStoresPerMemsetOptSize = 16;
714 MaxStoresPerMemcpy = 32;
715 MaxStoresPerMemcpyOptSize = 8;
716 MaxStoresPerMemmove = 32;
717 MaxStoresPerMemmoveOptSize = 8;
718 }
719 }
721 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
722 /// the desired ByVal argument alignment.
723 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
724 unsigned MaxMaxAlign) {
725 if (MaxAlign == MaxMaxAlign)
726 return;
727 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
728 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
729 MaxAlign = 32;
730 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
731 MaxAlign = 16;
732 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
733 unsigned EltAlign = 0;
734 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
735 if (EltAlign > MaxAlign)
736 MaxAlign = EltAlign;
737 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
738 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
739 unsigned EltAlign = 0;
740 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
741 if (EltAlign > MaxAlign)
742 MaxAlign = EltAlign;
743 if (MaxAlign == MaxMaxAlign)
744 break;
745 }
746 }
747 }
749 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
750 /// function arguments in the caller parameter area.
751 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
752 // Darwin passes everything on 4 byte boundary.
753 if (Subtarget.isDarwin())
754 return 4;
756 // 16byte and wider vectors are passed on 16byte boundary.
757 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
758 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
759 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
760 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
761 return Align;
762 }
764 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
765 switch (Opcode) {
766 default: return nullptr;
767 case PPCISD::FSEL: return "PPCISD::FSEL";
768 case PPCISD::FCFID: return "PPCISD::FCFID";
769 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
770 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
771 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
772 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
773 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
774 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
775 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
776 case PPCISD::FRE: return "PPCISD::FRE";
777 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
778 case PPCISD::STFIWX: return "PPCISD::STFIWX";
779 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
780 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
781 case PPCISD::VPERM: return "PPCISD::VPERM";
782 case PPCISD::CMPB: return "PPCISD::CMPB";
783 case PPCISD::Hi: return "PPCISD::Hi";
784 case PPCISD::Lo: return "PPCISD::Lo";
785 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
786 case PPCISD::LOAD: return "PPCISD::LOAD";
787 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
788 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
789 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
790 case PPCISD::SRL: return "PPCISD::SRL";
791 case PPCISD::SRA: return "PPCISD::SRA";
792 case PPCISD::SHL: return "PPCISD::SHL";
793 case PPCISD::CALL: return "PPCISD::CALL";
794 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
795 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS";
796 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS";
797 case PPCISD::MTCTR: return "PPCISD::MTCTR";
798 case PPCISD::BCTRL: return "PPCISD::BCTRL";
799 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
800 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
801 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
802 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
803 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
804 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
805 case PPCISD::VCMP: return "PPCISD::VCMP";
806 case PPCISD::VCMPo: return "PPCISD::VCMPo";
807 case PPCISD::LBRX: return "PPCISD::LBRX";
808 case PPCISD::STBRX: return "PPCISD::STBRX";
809 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
810 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
811 case PPCISD::LARX: return "PPCISD::LARX";
812 case PPCISD::STCX: return "PPCISD::STCX";
813 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
814 case PPCISD::BDNZ: return "PPCISD::BDNZ";
815 case PPCISD::BDZ: return "PPCISD::BDZ";
816 case PPCISD::MFFS: return "PPCISD::MFFS";
817 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
818 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
819 case PPCISD::CR6SET: return "PPCISD::CR6SET";
820 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
821 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
822 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
823 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
824 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
825 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
826 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
827 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
828 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
829 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
830 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
831 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
832 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
833 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
834 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
835 case PPCISD::SC: return "PPCISD::SC";
836 }
837 }
839 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
840 if (!VT.isVector())
841 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
842 return VT.changeVectorElementTypeToInteger();
843 }
845 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
846 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
847 return true;
848 }
850 //===----------------------------------------------------------------------===//
851 // Node matching predicates, for use by the tblgen matching code.
852 //===----------------------------------------------------------------------===//
854 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
855 static bool isFloatingPointZero(SDValue Op) {
856 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
857 return CFP->getValueAPF().isZero();
858 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
859 // Maybe this has already been legalized into the constant pool?
860 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
861 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
862 return CFP->getValueAPF().isZero();
863 }
864 return false;
865 }
867 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
868 /// true if Op is undef or if it matches the specified value.
869 static bool isConstantOrUndef(int Op, int Val) {
870 return Op < 0 || Op == Val;
871 }
873 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
874 /// VPKUHUM instruction.
875 /// The ShuffleKind distinguishes between big-endian operations with
876 /// two different inputs (0), either-endian operations with two identical
877 /// inputs (1), and little-endian operantion with two different inputs (2).
878 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
879 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
880 SelectionDAG &DAG) {
881 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
882 if (ShuffleKind == 0) {
883 if (IsLE)
884 return false;
885 for (unsigned i = 0; i != 16; ++i)
886 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
887 return false;
888 } else if (ShuffleKind == 2) {
889 if (!IsLE)
890 return false;
891 for (unsigned i = 0; i != 16; ++i)
892 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
893 return false;
894 } else if (ShuffleKind == 1) {
895 unsigned j = IsLE ? 0 : 1;
896 for (unsigned i = 0; i != 8; ++i)
897 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
898 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
899 return false;
900 }
901 return true;
902 }
904 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
905 /// VPKUWUM instruction.
906 /// The ShuffleKind distinguishes between big-endian operations with
907 /// two different inputs (0), either-endian operations with two identical
908 /// inputs (1), and little-endian operantion with two different inputs (2).
909 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
910 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
911 SelectionDAG &DAG) {
912 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
913 if (ShuffleKind == 0) {
914 if (IsLE)
915 return false;
916 for (unsigned i = 0; i != 16; i += 2)
917 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
918 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
919 return false;
920 } else if (ShuffleKind == 2) {
921 if (!IsLE)
922 return false;
923 for (unsigned i = 0; i != 16; i += 2)
924 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
925 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
926 return false;
927 } else if (ShuffleKind == 1) {
928 unsigned j = IsLE ? 0 : 2;
929 for (unsigned i = 0; i != 8; i += 2)
930 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
931 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
932 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
933 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
934 return false;
935 }
936 return true;
937 }
939 /// isVMerge - Common function, used to match vmrg* shuffles.
940 ///
941 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
942 unsigned LHSStart, unsigned RHSStart) {
943 if (N->getValueType(0) != MVT::v16i8)
944 return false;
945 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
946 "Unsupported merge size!");
948 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
949 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
950 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
951 LHSStart+j+i*UnitSize) ||
952 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
953 RHSStart+j+i*UnitSize))
954 return false;
955 }
956 return true;
957 }
959 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
960 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
961 /// The ShuffleKind distinguishes between big-endian merges with two
962 /// different inputs (0), either-endian merges with two identical inputs (1),
963 /// and little-endian merges with two different inputs (2). For the latter,
964 /// the input operands are swapped (see PPCInstrAltivec.td).
965 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
966 unsigned ShuffleKind, SelectionDAG &DAG) {
967 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
968 if (ShuffleKind == 1) // unary
969 return isVMerge(N, UnitSize, 0, 0);
970 else if (ShuffleKind == 2) // swapped
971 return isVMerge(N, UnitSize, 0, 16);
972 else
973 return false;
974 } else {
975 if (ShuffleKind == 1) // unary
976 return isVMerge(N, UnitSize, 8, 8);
977 else if (ShuffleKind == 0) // normal
978 return isVMerge(N, UnitSize, 8, 24);
979 else
980 return false;
981 }
982 }
984 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
985 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
986 /// The ShuffleKind distinguishes between big-endian merges with two
987 /// different inputs (0), either-endian merges with two identical inputs (1),
988 /// and little-endian merges with two different inputs (2). For the latter,
989 /// the input operands are swapped (see PPCInstrAltivec.td).
990 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
991 unsigned ShuffleKind, SelectionDAG &DAG) {
992 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
993 if (ShuffleKind == 1) // unary
994 return isVMerge(N, UnitSize, 8, 8);
995 else if (ShuffleKind == 2) // swapped
996 return isVMerge(N, UnitSize, 8, 24);
997 else
998 return false;
999 } else {
1000 if (ShuffleKind == 1) // unary
1001 return isVMerge(N, UnitSize, 0, 0);
1002 else if (ShuffleKind == 0) // normal
1003 return isVMerge(N, UnitSize, 0, 16);
1004 else
1005 return false;
1006 }
1007 }
1010 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1011 /// amount, otherwise return -1.
1012 /// The ShuffleKind distinguishes between big-endian operations with two
1013 /// different inputs (0), either-endian operations with two identical inputs
1014 /// (1), and little-endian operations with two different inputs (2). For the
1015 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1016 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1017 SelectionDAG &DAG) {
1018 if (N->getValueType(0) != MVT::v16i8)
1019 return -1;
1021 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1023 // Find the first non-undef value in the shuffle mask.
1024 unsigned i;
1025 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1026 /*search*/;
1028 if (i == 16) return -1; // all undef.
1030 // Otherwise, check to see if the rest of the elements are consecutively
1031 // numbered from this value.
1032 unsigned ShiftAmt = SVOp->getMaskElt(i);
1033 if (ShiftAmt < i) return -1;
1035 ShiftAmt -= i;
1036 bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1037 isLittleEndian();
1039 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1040 // Check the rest of the elements to see if they are consecutive.
1041 for (++i; i != 16; ++i)
1042 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1043 return -1;
1044 } else if (ShuffleKind == 1) {
1045 // Check the rest of the elements to see if they are consecutive.
1046 for (++i; i != 16; ++i)
1047 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1048 return -1;
1049 } else
1050 return -1;
1052 if (ShuffleKind == 2 && isLE)
1053 ShiftAmt = 16 - ShiftAmt;
1055 return ShiftAmt;
1056 }
1058 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1059 /// specifies a splat of a single element that is suitable for input to
1060 /// VSPLTB/VSPLTH/VSPLTW.
1061 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1062 assert(N->getValueType(0) == MVT::v16i8 &&
1063 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1065 // This is a splat operation if each element of the permute is the same, and
1066 // if the value doesn't reference the second vector.
1067 unsigned ElementBase = N->getMaskElt(0);
1069 // FIXME: Handle UNDEF elements too!
1070 if (ElementBase >= 16)
1071 return false;
1073 // Check that the indices are consecutive, in the case of a multi-byte element
1074 // splatted with a v16i8 mask.
1075 for (unsigned i = 1; i != EltSize; ++i)
1076 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1077 return false;
1079 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1080 if (N->getMaskElt(i) < 0) continue;
1081 for (unsigned j = 0; j != EltSize; ++j)
1082 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1083 return false;
1084 }
1085 return true;
1086 }
1088 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1089 /// are -0.0.
1090 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1091 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1093 APInt APVal, APUndef;
1094 unsigned BitSize;
1095 bool HasAnyUndefs;
1097 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1098 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1099 return CFP->getValueAPF().isNegZero();
1101 return false;
1102 }
1104 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1105 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1106 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1107 SelectionDAG &DAG) {
1108 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1109 assert(isSplatShuffleMask(SVOp, EltSize));
1110 if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1111 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1112 else
1113 return SVOp->getMaskElt(0) / EltSize;
1114 }
1116 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1117 /// by using a vspltis[bhw] instruction of the specified element size, return
1118 /// the constant being splatted. The ByteSize field indicates the number of
1119 /// bytes of each element [124] -> [bhw].
1120 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1121 SDValue OpVal(nullptr, 0);
1123 // If ByteSize of the splat is bigger than the element size of the
1124 // build_vector, then we have a case where we are checking for a splat where
1125 // multiple elements of the buildvector are folded together into a single
1126 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1127 unsigned EltSize = 16/N->getNumOperands();
1128 if (EltSize < ByteSize) {
1129 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1130 SDValue UniquedVals[4];
1131 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1133 // See if all of the elements in the buildvector agree across.
1134 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1135 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1136 // If the element isn't a constant, bail fully out.
1137 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1140 if (!UniquedVals[i&(Multiple-1)].getNode())
1141 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1142 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1143 return SDValue(); // no match.
1144 }
1146 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1147 // either constant or undef values that are identical for each chunk. See
1148 // if these chunks can form into a larger vspltis*.
1150 // Check to see if all of the leading entries are either 0 or -1. If
1151 // neither, then this won't fit into the immediate field.
1152 bool LeadingZero = true;
1153 bool LeadingOnes = true;
1154 for (unsigned i = 0; i != Multiple-1; ++i) {
1155 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1157 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1158 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1159 }
1160 // Finally, check the least significant entry.
1161 if (LeadingZero) {
1162 if (!UniquedVals[Multiple-1].getNode())
1163 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1164 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1165 if (Val < 16)
1166 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1167 }
1168 if (LeadingOnes) {
1169 if (!UniquedVals[Multiple-1].getNode())
1170 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1171 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1172 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1173 return DAG.getTargetConstant(Val, MVT::i32);
1174 }
1176 return SDValue();
1177 }
1179 // Check to see if this buildvec has a single non-undef value in its elements.
1180 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1181 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1182 if (!OpVal.getNode())
1183 OpVal = N->getOperand(i);
1184 else if (OpVal != N->getOperand(i))
1185 return SDValue();
1186 }
1188 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1190 unsigned ValSizeInBytes = EltSize;
1191 uint64_t Value = 0;
1192 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1193 Value = CN->getZExtValue();
1194 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1195 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1196 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1197 }
1199 // If the splat value is larger than the element value, then we can never do
1200 // this splat. The only case that we could fit the replicated bits into our
1201 // immediate field for would be zero, and we prefer to use vxor for it.
1202 if (ValSizeInBytes < ByteSize) return SDValue();
1204 // If the element value is larger than the splat value, cut it in half and
1205 // check to see if the two halves are equal. Continue doing this until we
1206 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1207 while (ValSizeInBytes > ByteSize) {
1208 ValSizeInBytes >>= 1;
1210 // If the top half equals the bottom half, we're still ok.
1211 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1212 (Value & ((1 << (8*ValSizeInBytes))-1)))
1213 return SDValue();
1214 }
1216 // Properly sign extend the value.
1217 int MaskVal = SignExtend32(Value, ByteSize * 8);
1219 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1220 if (MaskVal == 0) return SDValue();
1222 // Finally, if this value fits in a 5 bit sext field, return it
1223 if (SignExtend32<5>(MaskVal) == MaskVal)
1224 return DAG.getTargetConstant(MaskVal, MVT::i32);
1225 return SDValue();
1226 }
1228 //===----------------------------------------------------------------------===//
1229 // Addressing Mode Selection
1230 //===----------------------------------------------------------------------===//
1232 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1233 /// or 64-bit immediate, and if the value can be accurately represented as a
1234 /// sign extension from a 16-bit value. If so, this returns true and the
1235 /// immediate.
1236 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1237 if (!isa<ConstantSDNode>(N))
1238 return false;
1240 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1241 if (N->getValueType(0) == MVT::i32)
1242 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1243 else
1244 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1245 }
1246 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1247 return isIntS16Immediate(Op.getNode(), Imm);
1248 }
1251 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1252 /// can be represented as an indexed [r+r] operation. Returns false if it
1253 /// can be more efficiently represented with [r+imm].
1254 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1255 SDValue &Index,
1256 SelectionDAG &DAG) const {
1257 short imm = 0;
1258 if (N.getOpcode() == ISD::ADD) {
1259 if (isIntS16Immediate(N.getOperand(1), imm))
1260 return false; // r+i
1261 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1262 return false; // r+i
1264 Base = N.getOperand(0);
1265 Index = N.getOperand(1);
1266 return true;
1267 } else if (N.getOpcode() == ISD::OR) {
1268 if (isIntS16Immediate(N.getOperand(1), imm))
1269 return false; // r+i can fold it if we can.
1271 // If this is an or of disjoint bitfields, we can codegen this as an add
1272 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1273 // disjoint.
1274 APInt LHSKnownZero, LHSKnownOne;
1275 APInt RHSKnownZero, RHSKnownOne;
1276 DAG.computeKnownBits(N.getOperand(0),
1277 LHSKnownZero, LHSKnownOne);
1279 if (LHSKnownZero.getBoolValue()) {
1280 DAG.computeKnownBits(N.getOperand(1),
1281 RHSKnownZero, RHSKnownOne);
1282 // If all of the bits are known zero on the LHS or RHS, the add won't
1283 // carry.
1284 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1285 Base = N.getOperand(0);
1286 Index = N.getOperand(1);
1287 return true;
1288 }
1289 }
1290 }
1292 return false;
1293 }
1295 // If we happen to be doing an i64 load or store into a stack slot that has
1296 // less than a 4-byte alignment, then the frame-index elimination may need to
1297 // use an indexed load or store instruction (because the offset may not be a
1298 // multiple of 4). The extra register needed to hold the offset comes from the
1299 // register scavenger, and it is possible that the scavenger will need to use
1300 // an emergency spill slot. As a result, we need to make sure that a spill slot
1301 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1302 // stack slot.
1303 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1304 // FIXME: This does not handle the LWA case.
1305 if (VT != MVT::i64)
1306 return;
1308 // NOTE: We'll exclude negative FIs here, which come from argument
1309 // lowering, because there are no known test cases triggering this problem
1310 // using packed structures (or similar). We can remove this exclusion if
1311 // we find such a test case. The reason why this is so test-case driven is
1312 // because this entire 'fixup' is only to prevent crashes (from the
1313 // register scavenger) on not-really-valid inputs. For example, if we have:
1314 // %a = alloca i1
1315 // %b = bitcast i1* %a to i64*
1316 // store i64* a, i64 b
1317 // then the store should really be marked as 'align 1', but is not. If it
1318 // were marked as 'align 1' then the indexed form would have been
1319 // instruction-selected initially, and the problem this 'fixup' is preventing
1320 // won't happen regardless.
1321 if (FrameIdx < 0)
1322 return;
1324 MachineFunction &MF = DAG.getMachineFunction();
1325 MachineFrameInfo *MFI = MF.getFrameInfo();
1327 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1328 if (Align >= 4)
1329 return;
1331 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1332 FuncInfo->setHasNonRISpills();
1333 }
1335 /// Returns true if the address N can be represented by a base register plus
1336 /// a signed 16-bit displacement [r+imm], and if it is not better
1337 /// represented as reg+reg. If Aligned is true, only accept displacements
1338 /// suitable for STD and friends, i.e. multiples of 4.
1339 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1340 SDValue &Base,
1341 SelectionDAG &DAG,
1342 bool Aligned) const {
1343 // FIXME dl should come from parent load or store, not from address
1344 SDLoc dl(N);
1345 // If this can be more profitably realized as r+r, fail.
1346 if (SelectAddressRegReg(N, Disp, Base, DAG))
1347 return false;
1349 if (N.getOpcode() == ISD::ADD) {
1350 short imm = 0;
1351 if (isIntS16Immediate(N.getOperand(1), imm) &&
1352 (!Aligned || (imm & 3) == 0)) {
1353 Disp = DAG.getTargetConstant(imm, N.getValueType());
1354 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1355 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1356 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1357 } else {
1358 Base = N.getOperand(0);
1359 }
1360 return true; // [r+i]
1361 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1362 // Match LOAD (ADD (X, Lo(G))).
1363 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1364 && "Cannot handle constant offsets yet!");
1365 Disp = N.getOperand(1).getOperand(0); // The global address.
1366 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1367 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1368 Disp.getOpcode() == ISD::TargetConstantPool ||
1369 Disp.getOpcode() == ISD::TargetJumpTable);
1370 Base = N.getOperand(0);
1371 return true; // [&g+r]
1372 }
1373 } else if (N.getOpcode() == ISD::OR) {
1374 short imm = 0;
1375 if (isIntS16Immediate(N.getOperand(1), imm) &&
1376 (!Aligned || (imm & 3) == 0)) {
1377 // If this is an or of disjoint bitfields, we can codegen this as an add
1378 // (for better address arithmetic) if the LHS and RHS of the OR are
1379 // provably disjoint.
1380 APInt LHSKnownZero, LHSKnownOne;
1381 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1383 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1384 // If all of the bits are known zero on the LHS or RHS, the add won't
1385 // carry.
1386 if (FrameIndexSDNode *FI =
1387 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1388 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1389 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1390 } else {
1391 Base = N.getOperand(0);
1392 }
1393 Disp = DAG.getTargetConstant(imm, N.getValueType());
1394 return true;
1395 }
1396 }
1397 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1398 // Loading from a constant address.
1400 // If this address fits entirely in a 16-bit sext immediate field, codegen
1401 // this as "d, 0"
1402 short Imm;
1403 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1404 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1405 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1406 CN->getValueType(0));
1407 return true;
1408 }
1410 // Handle 32-bit sext immediates with LIS + addr mode.
1411 if ((CN->getValueType(0) == MVT::i32 ||
1412 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1413 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1414 int Addr = (int)CN->getZExtValue();
1416 // Otherwise, break this down into an LIS + disp.
1417 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1419 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1420 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1421 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1422 return true;
1423 }
1424 }
1426 Disp = DAG.getTargetConstant(0, getPointerTy());
1427 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1428 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1429 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1430 } else
1431 Base = N;
1432 return true; // [r+0]
1433 }
1435 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1436 /// represented as an indexed [r+r] operation.
1437 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1438 SDValue &Index,
1439 SelectionDAG &DAG) const {
1440 // Check to see if we can easily represent this as an [r+r] address. This
1441 // will fail if it thinks that the address is more profitably represented as
1442 // reg+imm, e.g. where imm = 0.
1443 if (SelectAddressRegReg(N, Base, Index, DAG))
1444 return true;
1446 // If the operand is an addition, always emit this as [r+r], since this is
1447 // better (for code size, and execution, as the memop does the add for free)
1448 // than emitting an explicit add.
1449 if (N.getOpcode() == ISD::ADD) {
1450 Base = N.getOperand(0);
1451 Index = N.getOperand(1);
1452 return true;
1453 }
1455 // Otherwise, do it the hard way, using R0 as the base register.
1456 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1457 N.getValueType());
1458 Index = N;
1459 return true;
1460 }
1462 /// getPreIndexedAddressParts - returns true by value, base pointer and
1463 /// offset pointer and addressing mode by reference if the node's address
1464 /// can be legally represented as pre-indexed load / store address.
1465 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1466 SDValue &Offset,
1467 ISD::MemIndexedMode &AM,
1468 SelectionDAG &DAG) const {
1469 if (DisablePPCPreinc) return false;
1471 bool isLoad = true;
1472 SDValue Ptr;
1473 EVT VT;
1474 unsigned Alignment;
1475 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1476 Ptr = LD->getBasePtr();
1477 VT = LD->getMemoryVT();
1478 Alignment = LD->getAlignment();
1479 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1480 Ptr = ST->getBasePtr();
1481 VT = ST->getMemoryVT();
1482 Alignment = ST->getAlignment();
1483 isLoad = false;
1484 } else
1485 return false;
1487 // PowerPC doesn't have preinc load/store instructions for vectors.
1488 if (VT.isVector())
1489 return false;
1491 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1493 // Common code will reject creating a pre-inc form if the base pointer
1494 // is a frame index, or if N is a store and the base pointer is either
1495 // the same as or a predecessor of the value being stored. Check for
1496 // those situations here, and try with swapped Base/Offset instead.
1497 bool Swap = false;
1499 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1500 Swap = true;
1501 else if (!isLoad) {
1502 SDValue Val = cast<StoreSDNode>(N)->getValue();
1503 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1504 Swap = true;
1505 }
1507 if (Swap)
1508 std::swap(Base, Offset);
1510 AM = ISD::PRE_INC;
1511 return true;
1512 }
1514 // LDU/STU can only handle immediates that are a multiple of 4.
1515 if (VT != MVT::i64) {
1516 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1517 return false;
1518 } else {
1519 // LDU/STU need an address with at least 4-byte alignment.
1520 if (Alignment < 4)
1521 return false;
1523 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1524 return false;
1525 }
1527 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1528 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1529 // sext i32 to i64 when addr mode is r+i.
1530 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1531 LD->getExtensionType() == ISD::SEXTLOAD &&
1532 isa<ConstantSDNode>(Offset))
1533 return false;
1534 }
1536 AM = ISD::PRE_INC;
1537 return true;
1538 }
1540 //===----------------------------------------------------------------------===//
1541 // LowerOperation implementation
1542 //===----------------------------------------------------------------------===//
1544 /// GetLabelAccessInfo - Return true if we should reference labels using a
1545 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1546 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1547 unsigned &LoOpFlags,
1548 const GlobalValue *GV = nullptr) {
1549 HiOpFlags = PPCII::MO_HA;
1550 LoOpFlags = PPCII::MO_LO;
1552 // Don't use the pic base if not in PIC relocation model.
1553 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1555 if (isPIC) {
1556 HiOpFlags |= PPCII::MO_PIC_FLAG;
1557 LoOpFlags |= PPCII::MO_PIC_FLAG;
1558 }
1560 // If this is a reference to a global value that requires a non-lazy-ptr, make
1561 // sure that instruction lowering adds it.
1562 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1563 HiOpFlags |= PPCII::MO_NLP_FLAG;
1564 LoOpFlags |= PPCII::MO_NLP_FLAG;
1566 if (GV->hasHiddenVisibility()) {
1567 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1568 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1569 }
1570 }
1572 return isPIC;
1573 }
1575 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1576 SelectionDAG &DAG) {
1577 EVT PtrVT = HiPart.getValueType();
1578 SDValue Zero = DAG.getConstant(0, PtrVT);
1579 SDLoc DL(HiPart);
1581 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1582 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1584 // With PIC, the first instruction is actually "GR+hi(&G)".
1585 if (isPIC)
1586 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1587 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1589 // Generate non-pic code that has direct accesses to the constant pool.
1590 // The address of the global is just (hi(&g)+lo(&g)).
1591 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1592 }
1594 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1595 SelectionDAG &DAG) const {
1596 EVT PtrVT = Op.getValueType();
1597 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1598 const Constant *C = CP->getConstVal();
1600 // 64-bit SVR4 ABI code is always position-independent.
1601 // The actual address of the GlobalValue is stored in the TOC.
1602 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1603 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1604 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1605 DAG.getRegister(PPC::X2, MVT::i64));
1606 }
1608 unsigned MOHiFlag, MOLoFlag;
1609 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1611 if (isPIC && Subtarget.isSVR4ABI()) {
1612 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1613 PPCII::MO_PIC_FLAG);
1614 SDLoc DL(CP);
1615 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1616 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1617 }
1619 SDValue CPIHi =
1620 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1621 SDValue CPILo =
1622 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1623 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1624 }
1626 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1627 EVT PtrVT = Op.getValueType();
1628 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1630 // 64-bit SVR4 ABI code is always position-independent.
1631 // The actual address of the GlobalValue is stored in the TOC.
1632 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1633 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1634 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1635 DAG.getRegister(PPC::X2, MVT::i64));
1636 }
1638 unsigned MOHiFlag, MOLoFlag;
1639 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1641 if (isPIC && Subtarget.isSVR4ABI()) {
1642 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1643 PPCII::MO_PIC_FLAG);
1644 SDLoc DL(GA);
1645 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1646 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1647 }
1649 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1650 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1651 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1652 }
1654 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1655 SelectionDAG &DAG) const {
1656 EVT PtrVT = Op.getValueType();
1657 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1658 const BlockAddress *BA = BASDN->getBlockAddress();
1660 // 64-bit SVR4 ABI code is always position-independent.
1661 // The actual BlockAddress is stored in the TOC.
1662 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1663 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1664 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1665 DAG.getRegister(PPC::X2, MVT::i64));
1666 }
1668 unsigned MOHiFlag, MOLoFlag;
1669 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1670 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1671 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1672 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1673 }
1675 // Generate a call to __tls_get_addr for the given GOT entry Op.
1676 std::pair<SDValue,SDValue>
1677 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1678 SelectionDAG &DAG) const {
1680 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1681 TargetLowering::ArgListTy Args;
1682 TargetLowering::ArgListEntry Entry;
1683 Entry.Node = Op;
1684 Entry.Ty = IntPtrTy;
1685 Args.push_back(Entry);
1687 TargetLowering::CallLoweringInfo CLI(DAG);
1688 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1689 .setCallee(CallingConv::C, IntPtrTy,
1690 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1691 std::move(Args), 0);
1693 return LowerCallTo(CLI);
1694 }
1696 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1697 SelectionDAG &DAG) const {
1699 // FIXME: TLS addresses currently use medium model code sequences,
1700 // which is the most useful form. Eventually support for small and
1701 // large models could be added if users need it, at the cost of
1702 // additional complexity.
1703 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1704 SDLoc dl(GA);
1705 const GlobalValue *GV = GA->getGlobal();
1706 EVT PtrVT = getPointerTy();
1707 bool is64bit = Subtarget.isPPC64();
1708 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1709 PICLevel::Level picLevel = M->getPICLevel();
1711 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1713 if (Model == TLSModel::LocalExec) {
1714 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1715 PPCII::MO_TPREL_HA);
1716 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1717 PPCII::MO_TPREL_LO);
1718 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1719 is64bit ? MVT::i64 : MVT::i32);
1720 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1721 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1722 }
1724 if (Model == TLSModel::InitialExec) {
1725 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1726 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1727 PPCII::MO_TLS);
1728 SDValue GOTPtr;
1729 if (is64bit) {
1730 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1731 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1732 PtrVT, GOTReg, TGA);
1733 } else
1734 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1735 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1736 PtrVT, TGA, GOTPtr);
1737 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1738 }
1740 if (Model == TLSModel::GeneralDynamic) {
1741 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1742 PPCII::MO_TLSGD);
1743 SDValue GOTPtr;
1744 if (is64bit) {
1745 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1746 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1747 GOTReg, TGA);
1748 } else {
1749 if (picLevel == PICLevel::Small)
1750 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1751 else
1752 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1753 }
1754 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1755 GOTPtr, TGA);
1756 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1757 return CallResult.first;
1758 }
1760 if (Model == TLSModel::LocalDynamic) {
1761 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1762 PPCII::MO_TLSLD);
1763 SDValue GOTPtr;
1764 if (is64bit) {
1765 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1766 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1767 GOTReg, TGA);
1768 } else {
1769 if (picLevel == PICLevel::Small)
1770 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1771 else
1772 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1773 }
1774 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1775 GOTPtr, TGA);
1776 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1777 SDValue TLSAddr = CallResult.first;
1778 SDValue Chain = CallResult.second;
1779 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1780 Chain, TLSAddr, TGA);
1781 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1782 }
1784 llvm_unreachable("Unknown TLS model!");
1785 }
1787 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1788 SelectionDAG &DAG) const {
1789 EVT PtrVT = Op.getValueType();
1790 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1791 SDLoc DL(GSDN);
1792 const GlobalValue *GV = GSDN->getGlobal();
1794 // 64-bit SVR4 ABI code is always position-independent.
1795 // The actual address of the GlobalValue is stored in the TOC.
1796 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1797 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1798 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1799 DAG.getRegister(PPC::X2, MVT::i64));
1800 }
1802 unsigned MOHiFlag, MOLoFlag;
1803 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1805 if (isPIC && Subtarget.isSVR4ABI()) {
1806 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1807 GSDN->getOffset(),
1808 PPCII::MO_PIC_FLAG);
1809 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1810 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1811 }
1813 SDValue GAHi =
1814 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1815 SDValue GALo =
1816 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1818 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1820 // If the global reference is actually to a non-lazy-pointer, we have to do an
1821 // extra load to get the address of the global.
1822 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1823 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1824 false, false, false, 0);
1825 return Ptr;
1826 }
1828 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1829 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1830 SDLoc dl(Op);
1832 if (Op.getValueType() == MVT::v2i64) {
1833 // When the operands themselves are v2i64 values, we need to do something
1834 // special because VSX has no underlying comparison operations for these.
1835 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1836 // Equality can be handled by casting to the legal type for Altivec
1837 // comparisons, everything else needs to be expanded.
1838 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1839 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1840 DAG.getSetCC(dl, MVT::v4i32,
1841 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1842 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1843 CC));
1844 }
1846 return SDValue();
1847 }
1849 // We handle most of these in the usual way.
1850 return Op;
1851 }
1853 // If we're comparing for equality to zero, expose the fact that this is
1854 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1855 // fold the new nodes.
1856 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1857 if (C->isNullValue() && CC == ISD::SETEQ) {
1858 EVT VT = Op.getOperand(0).getValueType();
1859 SDValue Zext = Op.getOperand(0);
1860 if (VT.bitsLT(MVT::i32)) {
1861 VT = MVT::i32;
1862 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1863 }
1864 unsigned Log2b = Log2_32(VT.getSizeInBits());
1865 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1866 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1867 DAG.getConstant(Log2b, MVT::i32));
1868 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1869 }
1870 // Leave comparisons against 0 and -1 alone for now, since they're usually
1871 // optimized. FIXME: revisit this when we can custom lower all setcc
1872 // optimizations.
1873 if (C->isAllOnesValue() || C->isNullValue())
1874 return SDValue();
1875 }
1877 // If we have an integer seteq/setne, turn it into a compare against zero
1878 // by xor'ing the rhs with the lhs, which is faster than setting a
1879 // condition register, reading it back out, and masking the correct bit. The
1880 // normal approach here uses sub to do this instead of xor. Using xor exposes
1881 // the result to other bit-twiddling opportunities.
1882 EVT LHSVT = Op.getOperand(0).getValueType();
1883 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1884 EVT VT = Op.getValueType();
1885 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1886 Op.getOperand(1));
1887 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1888 }
1889 return SDValue();
1890 }
1892 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1893 const PPCSubtarget &Subtarget) const {
1894 SDNode *Node = Op.getNode();
1895 EVT VT = Node->getValueType(0);
1896 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1897 SDValue InChain = Node->getOperand(0);
1898 SDValue VAListPtr = Node->getOperand(1);
1899 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1900 SDLoc dl(Node);
1902 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1904 // gpr_index
1905 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1906 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1907 false, false, false, 0);
1908 InChain = GprIndex.getValue(1);
1910 if (VT == MVT::i64) {
1911 // Check if GprIndex is even
1912 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1913 DAG.getConstant(1, MVT::i32));
1914 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1915 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1916 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1917 DAG.getConstant(1, MVT::i32));
1918 // Align GprIndex to be even if it isn't
1919 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1920 GprIndex);
1921 }
1923 // fpr index is 1 byte after gpr
1924 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1925 DAG.getConstant(1, MVT::i32));
1927 // fpr
1928 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1929 FprPtr, MachinePointerInfo(SV), MVT::i8,
1930 false, false, false, 0);
1931 InChain = FprIndex.getValue(1);
1933 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1934 DAG.getConstant(8, MVT::i32));
1936 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1937 DAG.getConstant(4, MVT::i32));
1939 // areas
1940 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1941 MachinePointerInfo(), false, false,
1942 false, 0);
1943 InChain = OverflowArea.getValue(1);
1945 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1946 MachinePointerInfo(), false, false,
1947 false, 0);
1948 InChain = RegSaveArea.getValue(1);
1950 // select overflow_area if index > 8
1951 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1952 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1954 // adjustment constant gpr_index * 4/8
1955 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1956 VT.isInteger() ? GprIndex : FprIndex,
1957 DAG.getConstant(VT.isInteger() ? 4 : 8,
1958 MVT::i32));
1960 // OurReg = RegSaveArea + RegConstant
1961 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1962 RegConstant);
1964 // Floating types are 32 bytes into RegSaveArea
1965 if (VT.isFloatingPoint())
1966 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1967 DAG.getConstant(32, MVT::i32));
1969 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1970 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1971 VT.isInteger() ? GprIndex : FprIndex,
1972 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1973 MVT::i32));
1975 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1976 VT.isInteger() ? VAListPtr : FprPtr,
1977 MachinePointerInfo(SV),
1978 MVT::i8, false, false, 0);
1980 // determine if we should load from reg_save_area or overflow_area
1981 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1983 // increase overflow_area by 4/8 if gpr/fpr > 8
1984 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1985 DAG.getConstant(VT.isInteger() ? 4 : 8,
1986 MVT::i32));
1988 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1989 OverflowAreaPlusN);
1991 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1992 OverflowAreaPtr,
1993 MachinePointerInfo(),
1994 MVT::i32, false, false, 0);
1996 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1997 false, false, false, 0);
1998 }
2000 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2001 const PPCSubtarget &Subtarget) const {
2002 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2004 // We have to copy the entire va_list struct:
2005 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2006 return DAG.getMemcpy(Op.getOperand(0), Op,
2007 Op.getOperand(1), Op.getOperand(2),
2008 DAG.getConstant(12, MVT::i32), 8, false, true,
2009 MachinePointerInfo(), MachinePointerInfo());
2010 }
2012 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2013 SelectionDAG &DAG) const {
2014 return Op.getOperand(0);
2015 }
2017 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2018 SelectionDAG &DAG) const {
2019 SDValue Chain = Op.getOperand(0);
2020 SDValue Trmp = Op.getOperand(1); // trampoline
2021 SDValue FPtr = Op.getOperand(2); // nested function
2022 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2023 SDLoc dl(Op);
2025 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2026 bool isPPC64 = (PtrVT == MVT::i64);
2027 Type *IntPtrTy =
2028 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2029 *DAG.getContext());
2031 TargetLowering::ArgListTy Args;
2032 TargetLowering::ArgListEntry Entry;
2034 Entry.Ty = IntPtrTy;
2035 Entry.Node = Trmp; Args.push_back(Entry);
2037 // TrampSize == (isPPC64 ? 48 : 40);
2038 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2039 isPPC64 ? MVT::i64 : MVT::i32);
2040 Args.push_back(Entry);
2042 Entry.Node = FPtr; Args.push_back(Entry);
2043 Entry.Node = Nest; Args.push_back(Entry);
2045 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2046 TargetLowering::CallLoweringInfo CLI(DAG);
2047 CLI.setDebugLoc(dl).setChain(Chain)
2048 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2049 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2050 std::move(Args), 0);
2052 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2053 return CallResult.second;
2054 }
2056 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2057 const PPCSubtarget &Subtarget) const {
2058 MachineFunction &MF = DAG.getMachineFunction();
2059 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2061 SDLoc dl(Op);
2063 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2064 // vastart just stores the address of the VarArgsFrameIndex slot into the
2065 // memory location argument.
2066 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2067 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2068 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2069 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2070 MachinePointerInfo(SV),
2071 false, false, 0);
2072 }
2074 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2075 // We suppose the given va_list is already allocated.
2076 //
2077 // typedef struct {
2078 // char gpr; /* index into the array of 8 GPRs
2079 // * stored in the register save area
2080 // * gpr=0 corresponds to r3,
2081 // * gpr=1 to r4, etc.
2082 // */
2083 // char fpr; /* index into the array of 8 FPRs
2084 // * stored in the register save area
2085 // * fpr=0 corresponds to f1,
2086 // * fpr=1 to f2, etc.
2087 // */
2088 // char *overflow_arg_area;
2089 // /* location on stack that holds
2090 // * the next overflow argument
2091 // */
2092 // char *reg_save_area;
2093 // /* where r3:r10 and f1:f8 (if saved)
2094 // * are stored
2095 // */
2096 // } va_list[1];
2099 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2100 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2103 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2105 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2106 PtrVT);
2107 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2108 PtrVT);
2110 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2111 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2113 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2114 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2116 uint64_t FPROffset = 1;
2117 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2119 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2121 // Store first byte : number of int regs
2122 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2123 Op.getOperand(1),
2124 MachinePointerInfo(SV),
2125 MVT::i8, false, false, 0);
2126 uint64_t nextOffset = FPROffset;
2127 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2128 ConstFPROffset);
2130 // Store second byte : number of float regs
2131 SDValue secondStore =
2132 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2133 MachinePointerInfo(SV, nextOffset), MVT::i8,
2134 false, false, 0);
2135 nextOffset += StackOffset;
2136 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2138 // Store second word : arguments given on stack
2139 SDValue thirdStore =
2140 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2141 MachinePointerInfo(SV, nextOffset),
2142 false, false, 0);
2143 nextOffset += FrameOffset;
2144 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2146 // Store third word : arguments given in registers
2147 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2148 MachinePointerInfo(SV, nextOffset),
2149 false, false, 0);
2151 }
2153 #include "PPCGenCallingConv.inc"
2155 // Function whose sole purpose is to kill compiler warnings
2156 // stemming from unused functions included from PPCGenCallingConv.inc.
2157 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2158 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2159 }
2161 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2162 CCValAssign::LocInfo &LocInfo,
2163 ISD::ArgFlagsTy &ArgFlags,
2164 CCState &State) {
2165 return true;
2166 }
2168 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2169 MVT &LocVT,
2170 CCValAssign::LocInfo &LocInfo,
2171 ISD::ArgFlagsTy &ArgFlags,
2172 CCState &State) {
2173 static const MCPhysReg ArgRegs[] = {
2174 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2175 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2176 };
2177 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2179 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2181 // Skip one register if the first unallocated register has an even register
2182 // number and there are still argument registers available which have not been
2183 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2184 // need to skip a register if RegNum is odd.
2185 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2186 State.AllocateReg(ArgRegs[RegNum]);
2187 }
2189 // Always return false here, as this function only makes sure that the first
2190 // unallocated register has an odd register number and does not actually
2191 // allocate a register for the current argument.
2192 return false;
2193 }
2195 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2196 MVT &LocVT,
2197 CCValAssign::LocInfo &LocInfo,
2198 ISD::ArgFlagsTy &ArgFlags,
2199 CCState &State) {
2200 static const MCPhysReg ArgRegs[] = {
2201 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2202 PPC::F8
2203 };
2205 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2207 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2209 // If there is only one Floating-point register left we need to put both f64
2210 // values of a split ppc_fp128 value on the stack.
2211 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2212 State.AllocateReg(ArgRegs[RegNum]);
2213 }
2215 // Always return false here, as this function only makes sure that the two f64
2216 // values a ppc_fp128 value is split into are both passed in registers or both
2217 // passed on the stack and does not actually allocate a register for the
2218 // current argument.
2219 return false;
2220 }
2222 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2223 /// on Darwin.
2224 static const MCPhysReg *GetFPR() {
2225 static const MCPhysReg FPR[] = {
2226 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2227 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2228 };
2230 return FPR;
2231 }
2233 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2234 /// the stack.
2235 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2236 unsigned PtrByteSize) {
2237 unsigned ArgSize = ArgVT.getStoreSize();
2238 if (Flags.isByVal())
2239 ArgSize = Flags.getByValSize();
2241 // Round up to multiples of the pointer size, except for array members,
2242 // which are always packed.
2243 if (!Flags.isInConsecutiveRegs())
2244 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2246 return ArgSize;
2247 }
2249 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2250 /// on the stack.
2251 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2252 ISD::ArgFlagsTy Flags,
2253 unsigned PtrByteSize) {
2254 unsigned Align = PtrByteSize;
2256 // Altivec parameters are padded to a 16 byte boundary.
2257 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2258 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2259 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2260 Align = 16;
2262 // ByVal parameters are aligned as requested.
2263 if (Flags.isByVal()) {
2264 unsigned BVAlign = Flags.getByValAlign();
2265 if (BVAlign > PtrByteSize) {
2266 if (BVAlign % PtrByteSize != 0)
2267 llvm_unreachable(
2268 "ByVal alignment is not a multiple of the pointer size");
2270 Align = BVAlign;
2271 }
2272 }
2274 // Array members are always packed to their original alignment.
2275 if (Flags.isInConsecutiveRegs()) {
2276 // If the array member was split into multiple registers, the first
2277 // needs to be aligned to the size of the full type. (Except for
2278 // ppcf128, which is only aligned as its f64 components.)
2279 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2280 Align = OrigVT.getStoreSize();
2281 else
2282 Align = ArgVT.getStoreSize();
2283 }
2285 return Align;
2286 }
2288 /// CalculateStackSlotUsed - Return whether this argument will use its
2289 /// stack slot (instead of being passed in registers). ArgOffset,
2290 /// AvailableFPRs, and AvailableVRs must hold the current argument
2291 /// position, and will be updated to account for this argument.
2292 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2293 ISD::ArgFlagsTy Flags,
2294 unsigned PtrByteSize,
2295 unsigned LinkageSize,
2296 unsigned ParamAreaSize,
2297 unsigned &ArgOffset,
2298 unsigned &AvailableFPRs,
2299 unsigned &AvailableVRs) {
2300 bool UseMemory = false;
2302 // Respect alignment of argument on the stack.
2303 unsigned Align =
2304 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2305 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2306 // If there's no space left in the argument save area, we must
2307 // use memory (this check also catches zero-sized arguments).
2308 if (ArgOffset >= LinkageSize + ParamAreaSize)
2309 UseMemory = true;
2311 // Allocate argument on the stack.
2312 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2313 if (Flags.isInConsecutiveRegsLast())
2314 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2315 // If we overran the argument save area, we must use memory
2316 // (this check catches arguments passed partially in memory)
2317 if (ArgOffset > LinkageSize + ParamAreaSize)
2318 UseMemory = true;
2320 // However, if the argument is actually passed in an FPR or a VR,
2321 // we don't use memory after all.
2322 if (!Flags.isByVal()) {
2323 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2324 if (AvailableFPRs > 0) {
2325 --AvailableFPRs;
2326 return false;
2327 }
2328 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2329 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2330 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2331 if (AvailableVRs > 0) {
2332 --AvailableVRs;
2333 return false;
2334 }
2335 }
2337 return UseMemory;
2338 }
2340 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2341 /// ensure minimum alignment required for target.
2342 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2343 unsigned NumBytes) {
2344 unsigned TargetAlign =
2345 Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2346 unsigned AlignMask = TargetAlign - 1;
2347 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2348 return NumBytes;
2349 }
2351 SDValue
2352 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2353 CallingConv::ID CallConv, bool isVarArg,
2354 const SmallVectorImpl<ISD::InputArg>
2355 &Ins,
2356 SDLoc dl, SelectionDAG &DAG,
2357 SmallVectorImpl<SDValue> &InVals)
2358 const {
2359 if (Subtarget.isSVR4ABI()) {
2360 if (Subtarget.isPPC64())
2361 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2362 dl, DAG, InVals);
2363 else
2364 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2365 dl, DAG, InVals);
2366 } else {
2367 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2368 dl, DAG, InVals);
2369 }
2370 }
2372 SDValue
2373 PPCTargetLowering::LowerFormalArguments_32SVR4(
2374 SDValue Chain,
2375 CallingConv::ID CallConv, bool isVarArg,
2376 const SmallVectorImpl<ISD::InputArg>
2377 &Ins,
2378 SDLoc dl, SelectionDAG &DAG,
2379 SmallVectorImpl<SDValue> &InVals) const {
2381 // 32-bit SVR4 ABI Stack Frame Layout:
2382 // +-----------------------------------+
2383 // +--> | Back chain |
2384 // | +-----------------------------------+
2385 // | | Floating-point register save area |
2386 // | +-----------------------------------+
2387 // | | General register save area |
2388 // | +-----------------------------------+
2389 // | | CR save word |
2390 // | +-----------------------------------+
2391 // | | VRSAVE save word |
2392 // | +-----------------------------------+
2393 // | | Alignment padding |
2394 // | +-----------------------------------+
2395 // | | Vector register save area |
2396 // | +-----------------------------------+
2397 // | | Local variable space |
2398 // | +-----------------------------------+
2399 // | | Parameter list area |
2400 // | +-----------------------------------+
2401 // | | LR save word |
2402 // | +-----------------------------------+
2403 // SP--> +--- | Back chain |
2404 // +-----------------------------------+
2405 //
2406 // Specifications:
2407 // System V Application Binary Interface PowerPC Processor Supplement
2408 // AltiVec Technology Programming Interface Manual
2410 MachineFunction &MF = DAG.getMachineFunction();
2411 MachineFrameInfo *MFI = MF.getFrameInfo();
2412 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2414 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2415 // Potential tail calls could cause overwriting of argument stack slots.
2416 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2417 (CallConv == CallingConv::Fast));
2418 unsigned PtrByteSize = 4;
2420 // Assign locations to all of the incoming arguments.
2421 SmallVector<CCValAssign, 16> ArgLocs;
2422 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2423 *DAG.getContext());
2425 // Reserve space for the linkage area on the stack.
2426 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2427 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2429 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2431 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2432 CCValAssign &VA = ArgLocs[i];
2434 // Arguments stored in registers.
2435 if (VA.isRegLoc()) {
2436 const TargetRegisterClass *RC;
2437 EVT ValVT = VA.getValVT();
2439 switch (ValVT.getSimpleVT().SimpleTy) {
2440 default:
2441 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2442 case MVT::i1:
2443 case MVT::i32:
2444 RC = &PPC::GPRCRegClass;
2445 break;
2446 case MVT::f32:
2447 RC = &PPC::F4RCRegClass;
2448 break;
2449 case MVT::f64:
2450 if (Subtarget.hasVSX())
2451 RC = &PPC::VSFRCRegClass;
2452 else
2453 RC = &PPC::F8RCRegClass;
2454 break;
2455 case MVT::v16i8:
2456 case MVT::v8i16:
2457 case MVT::v4i32:
2458 case MVT::v4f32:
2459 RC = &PPC::VRRCRegClass;
2460 break;
2461 case MVT::v2f64:
2462 case MVT::v2i64:
2463 RC = &PPC::VSHRCRegClass;
2464 break;
2465 }
2467 // Transform the arguments stored in physical registers into virtual ones.
2468 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2469 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2470 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2472 if (ValVT == MVT::i1)
2473 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2475 InVals.push_back(ArgValue);
2476 } else {
2477 // Argument stored in memory.
2478 assert(VA.isMemLoc());
2480 unsigned ArgSize = VA.getLocVT().getStoreSize();
2481 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2482 isImmutable);
2484 // Create load nodes to retrieve arguments from the stack.
2485 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2486 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2487 MachinePointerInfo(),
2488 false, false, false, 0));
2489 }
2490 }
2492 // Assign locations to all of the incoming aggregate by value arguments.
2493 // Aggregates passed by value are stored in the local variable space of the
2494 // caller's stack frame, right above the parameter list area.
2495 SmallVector<CCValAssign, 16> ByValArgLocs;
2496 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2497 ByValArgLocs, *DAG.getContext());
2499 // Reserve stack space for the allocations in CCInfo.
2500 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2502 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2504 // Area that is at least reserved in the caller of this function.
2505 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2506 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2508 // Set the size that is at least reserved in caller of this function. Tail
2509 // call optimized function's reserved stack space needs to be aligned so that
2510 // taking the difference between two stack areas will result in an aligned
2511 // stack.
2512 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2513 FuncInfo->setMinReservedArea(MinReservedArea);
2515 SmallVector<SDValue, 8> MemOps;
2517 // If the function takes variable number of arguments, make a frame index for
2518 // the start of the first vararg value... for expansion of llvm.va_start.
2519 if (isVarArg) {
2520 static const MCPhysReg GPArgRegs[] = {
2521 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2522 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2523 };
2524 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2526 static const MCPhysReg FPArgRegs[] = {
2527 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2528 PPC::F8
2529 };
2530 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2531 if (DisablePPCFloatInVariadic)
2532 NumFPArgRegs = 0;
2534 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2535 NumGPArgRegs));
2536 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2537 NumFPArgRegs));
2539 // Make room for NumGPArgRegs and NumFPArgRegs.
2540 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2541 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2543 FuncInfo->setVarArgsStackOffset(
2544 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2545 CCInfo.getNextStackOffset(), true));
2547 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2548 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2550 // The fixed integer arguments of a variadic function are stored to the
2551 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2552 // the result of va_next.
2553 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2554 // Get an existing live-in vreg, or add a new one.
2555 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2556 if (!VReg)
2557 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2559 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2560 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2561 MachinePointerInfo(), false, false, 0);
2562 MemOps.push_back(Store);
2563 // Increment the address by four for the next argument to store
2564 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2565 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2566 }
2568 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2569 // is set.
2570 // The double arguments are stored to the VarArgsFrameIndex
2571 // on the stack.
2572 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2573 // Get an existing live-in vreg, or add a new one.
2574 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2575 if (!VReg)
2576 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2578 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2579 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2580 MachinePointerInfo(), false, false, 0);
2581 MemOps.push_back(Store);
2582 // Increment the address by eight for the next argument to store
2583 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2584 PtrVT);
2585 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2586 }
2587 }
2589 if (!MemOps.empty())
2590 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2592 return Chain;
2593 }
2595 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2596 // value to MVT::i64 and then truncate to the correct register size.
2597 SDValue
2598 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2599 SelectionDAG &DAG, SDValue ArgVal,
2600 SDLoc dl) const {
2601 if (Flags.isSExt())
2602 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2603 DAG.getValueType(ObjectVT));
2604 else if (Flags.isZExt())
2605 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2606 DAG.getValueType(ObjectVT));
2608 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2609 }
2611 SDValue
2612 PPCTargetLowering::LowerFormalArguments_64SVR4(
2613 SDValue Chain,
2614 CallingConv::ID CallConv, bool isVarArg,
2615 const SmallVectorImpl<ISD::InputArg>
2616 &Ins,
2617 SDLoc dl, SelectionDAG &DAG,
2618 SmallVectorImpl<SDValue> &InVals) const {
2619 // TODO: add description of PPC stack frame format, or at least some docs.
2620 //
2621 bool isELFv2ABI = Subtarget.isELFv2ABI();
2622 bool isLittleEndian = Subtarget.isLittleEndian();
2623 MachineFunction &MF = DAG.getMachineFunction();
2624 MachineFrameInfo *MFI = MF.getFrameInfo();
2625 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2627 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2628 // Potential tail calls could cause overwriting of argument stack slots.
2629 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2630 (CallConv == CallingConv::Fast));
2631 unsigned PtrByteSize = 8;
2633 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2634 isELFv2ABI);
2636 static const MCPhysReg GPR[] = {
2637 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2638 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2639 };
2641 static const MCPhysReg *FPR = GetFPR();
2643 static const MCPhysReg VR[] = {
2644 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2645 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2646 };
2647 static const MCPhysReg VSRH[] = {
2648 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2649 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2650 };
2652 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2653 const unsigned Num_FPR_Regs = 13;
2654 const unsigned Num_VR_Regs = array_lengthof(VR);
2656 // Do a first pass over the arguments to determine whether the ABI
2657 // guarantees that our caller has allocated the parameter save area
2658 // on its stack frame. In the ELFv1 ABI, this is always the case;
2659 // in the ELFv2 ABI, it is true if this is a vararg function or if
2660 // any parameter is located in a stack slot.
2662 bool HasParameterArea = !isELFv2ABI || isVarArg;
2663 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2664 unsigned NumBytes = LinkageSize;
2665 unsigned AvailableFPRs = Num_FPR_Regs;
2666 unsigned AvailableVRs = Num_VR_Regs;
2667 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2668 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2669 PtrByteSize, LinkageSize, ParamAreaSize,
2670 NumBytes, AvailableFPRs, AvailableVRs))
2671 HasParameterArea = true;
2673 // Add DAG nodes to load the arguments or copy them out of registers. On
2674 // entry to a function on PPC, the arguments start after the linkage area,
2675 // although the first ones are often in registers.
2677 unsigned ArgOffset = LinkageSize;
2678 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2679 SmallVector<SDValue, 8> MemOps;
2680 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2681 unsigned CurArgIdx = 0;
2682 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2683 SDValue ArgVal;
2684 bool needsLoad = false;
2685 EVT ObjectVT = Ins[ArgNo].VT;
2686 EVT OrigVT = Ins[ArgNo].ArgVT;
2687 unsigned ObjSize = ObjectVT.getStoreSize();
2688 unsigned ArgSize = ObjSize;
2689 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2690 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2691 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2693 /* Respect alignment of argument on the stack. */
2694 unsigned Align =
2695 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2696 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2697 unsigned CurArgOffset = ArgOffset;
2699 /* Compute GPR index associated with argument offset. */
2700 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2701 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2703 // FIXME the codegen can be much improved in some cases.
2704 // We do not have to keep everything in memory.
2705 if (Flags.isByVal()) {
2706 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2707 ObjSize = Flags.getByValSize();
2708 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2709 // Empty aggregate parameters do not take up registers. Examples:
2710 // struct { } a;
2711 // union { } b;
2712 // int c[0];
2713 // etc. However, we have to provide a place-holder in InVals, so
2714 // pretend we have an 8-byte item at the current address for that
2715 // purpose.
2716 if (!ObjSize) {
2717 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2718 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2719 InVals.push_back(FIN);
2720 continue;
2721 }
2723 // Create a stack object covering all stack doublewords occupied
2724 // by the argument. If the argument is (fully or partially) on
2725 // the stack, or if the argument is fully in registers but the
2726 // caller has allocated the parameter save anyway, we can refer
2727 // directly to the caller's stack frame. Otherwise, create a
2728 // local copy in our own frame.
2729 int FI;
2730 if (HasParameterArea ||
2731 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2732 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2733 else
2734 FI = MFI->CreateStackObject(ArgSize, Align, false);
2735 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2737 // Handle aggregates smaller than 8 bytes.
2738 if (ObjSize < PtrByteSize) {
2739 // The value of the object is its address, which differs from the
2740 // address of the enclosing doubleword on big-endian systems.
2741 SDValue Arg = FIN;
2742 if (!isLittleEndian) {
2743 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2744 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2745 }
2746 InVals.push_back(Arg);
2748 if (GPR_idx != Num_GPR_Regs) {
2749 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2750 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2751 SDValue Store;
2753 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2754 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2755 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2756 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2757 MachinePointerInfo(FuncArg),
2758 ObjType, false, false, 0);
2759 } else {
2760 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2761 // store the whole register as-is to the parameter save area
2762 // slot.
2763 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2764 MachinePointerInfo(FuncArg),
2765 false, false, 0);
2766 }
2768 MemOps.push_back(Store);
2769 }
2770 // Whether we copied from a register or not, advance the offset
2771 // into the parameter save area by a full doubleword.
2772 ArgOffset += PtrByteSize;
2773 continue;
2774 }
2776 // The value of the object is its address, which is the address of
2777 // its first stack doubleword.
2778 InVals.push_back(FIN);
2780 // Store whatever pieces of the object are in registers to memory.
2781 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2782 if (GPR_idx == Num_GPR_Regs)
2783 break;
2785 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2786 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2787 SDValue Addr = FIN;
2788 if (j) {
2789 SDValue Off = DAG.getConstant(j, PtrVT);
2790 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2791 }
2792 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2793 MachinePointerInfo(FuncArg, j),
2794 false, false, 0);
2795 MemOps.push_back(Store);
2796 ++GPR_idx;
2797 }
2798 ArgOffset += ArgSize;
2799 continue;
2800 }
2802 switch (ObjectVT.getSimpleVT().SimpleTy) {
2803 default: llvm_unreachable("Unhandled argument type!");
2804 case MVT::i1:
2805 case MVT::i32:
2806 case MVT::i64:
2807 // These can be scalar arguments or elements of an integer array type
2808 // passed directly. Clang may use those instead of "byval" aggregate
2809 // types to avoid forcing arguments to memory unnecessarily.
2810 if (GPR_idx != Num_GPR_Regs) {
2811 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2812 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2814 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2815 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2816 // value to MVT::i64 and then truncate to the correct register size.
2817 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2818 } else {
2819 needsLoad = true;
2820 ArgSize = PtrByteSize;
2821 }
2822 ArgOffset += 8;
2823 break;
2825 case MVT::f32:
2826 case MVT::f64:
2827 // These can be scalar arguments or elements of a float array type
2828 // passed directly. The latter are used to implement ELFv2 homogenous
2829 // float aggregates.
2830 if (FPR_idx != Num_FPR_Regs) {
2831 unsigned VReg;
2833 if (ObjectVT == MVT::f32)
2834 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2835 else
2836 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2837 &PPC::VSFRCRegClass :
2838 &PPC::F8RCRegClass);
2840 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2841 ++FPR_idx;
2842 } else if (GPR_idx != Num_GPR_Regs) {
2843 // This can only ever happen in the presence of f32 array types,
2844 // since otherwise we never run out of FPRs before running out
2845 // of GPRs.
2846 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2847 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2849 if (ObjectVT == MVT::f32) {
2850 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2851 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2852 DAG.getConstant(32, MVT::i32));
2853 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2854 }
2856 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2857 } else {
2858 needsLoad = true;
2859 }
2861 // When passing an array of floats, the array occupies consecutive
2862 // space in the argument area; only round up to the next doubleword
2863 // at the end of the array. Otherwise, each float takes 8 bytes.
2864 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2865 ArgOffset += ArgSize;
2866 if (Flags.isInConsecutiveRegsLast())
2867 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2868 break;
2869 case MVT::v4f32:
2870 case MVT::v4i32:
2871 case MVT::v8i16:
2872 case MVT::v16i8:
2873 case MVT::v2f64:
2874 case MVT::v2i64:
2875 // These can be scalar arguments or elements of a vector array type
2876 // passed directly. The latter are used to implement ELFv2 homogenous
2877 // vector aggregates.
2878 if (VR_idx != Num_VR_Regs) {
2879 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2880 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2881 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2882 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2883 ++VR_idx;
2884 } else {
2885 needsLoad = true;
2886 }
2887 ArgOffset += 16;
2888 break;
2889 }
2891 // We need to load the argument to a virtual register if we determined
2892 // above that we ran out of physical registers of the appropriate type.
2893 if (needsLoad) {
2894 if (ObjSize < ArgSize && !isLittleEndian)
2895 CurArgOffset += ArgSize - ObjSize;
2896 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2897 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2898 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2899 false, false, false, 0);
2900 }
2902 InVals.push_back(ArgVal);
2903 }
2905 // Area that is at least reserved in the caller of this function.
2906 unsigned MinReservedArea;
2907 if (HasParameterArea)
2908 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2909 else
2910 MinReservedArea = LinkageSize;
2912 // Set the size that is at least reserved in caller of this function. Tail
2913 // call optimized functions' reserved stack space needs to be aligned so that
2914 // taking the difference between two stack areas will result in an aligned
2915 // stack.
2916 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2917 FuncInfo->setMinReservedArea(MinReservedArea);
2919 // If the function takes variable number of arguments, make a frame index for
2920 // the start of the first vararg value... for expansion of llvm.va_start.
2921 if (isVarArg) {
2922 int Depth = ArgOffset;
2924 FuncInfo->setVarArgsFrameIndex(
2925 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2926 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2928 // If this function is vararg, store any remaining integer argument regs
2929 // to their spots on the stack so that they may be loaded by deferencing the
2930 // result of va_next.
2931 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2932 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2933 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2934 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2935 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2936 MachinePointerInfo(), false, false, 0);
2937 MemOps.push_back(Store);
2938 // Increment the address by four for the next argument to store
2939 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2940 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2941 }
2942 }
2944 if (!MemOps.empty())
2945 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2947 return Chain;
2948 }
2950 SDValue
2951 PPCTargetLowering::LowerFormalArguments_Darwin(
2952 SDValue Chain,
2953 CallingConv::ID CallConv, bool isVarArg,
2954 const SmallVectorImpl<ISD::InputArg>
2955 &Ins,
2956 SDLoc dl, SelectionDAG &DAG,
2957 SmallVectorImpl<SDValue> &InVals) const {
2958 // TODO: add description of PPC stack frame format, or at least some docs.
2959 //
2960 MachineFunction &MF = DAG.getMachineFunction();
2961 MachineFrameInfo *MFI = MF.getFrameInfo();
2962 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2964 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2965 bool isPPC64 = PtrVT == MVT::i64;
2966 // Potential tail calls could cause overwriting of argument stack slots.
2967 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2968 (CallConv == CallingConv::Fast));
2969 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2971 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2972 false);
2973 unsigned ArgOffset = LinkageSize;
2974 // Area that is at least reserved in caller of this function.
2975 unsigned MinReservedArea = ArgOffset;
2977 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2978 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2979 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2980 };
2981 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2982 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2983 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2984 };
2986 static const MCPhysReg *FPR = GetFPR();
2988 static const MCPhysReg VR[] = {
2989 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2990 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2991 };
2993 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2994 const unsigned Num_FPR_Regs = 13;
2995 const unsigned Num_VR_Regs = array_lengthof( VR);
2997 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2999 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3001 // In 32-bit non-varargs functions, the stack space for vectors is after the
3002 // stack space for non-vectors. We do not use this space unless we have
3003 // too many vectors to fit in registers, something that only occurs in
3004 // constructed examples:), but we have to walk the arglist to figure
3005 // that out...for the pathological case, compute VecArgOffset as the
3006 // start of the vector parameter area. Computing VecArgOffset is the
3007 // entire point of the following loop.
3008 unsigned VecArgOffset = ArgOffset;
3009 if (!isVarArg && !isPPC64) {
3010 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3011 ++ArgNo) {
3012 EVT ObjectVT = Ins[ArgNo].VT;
3013 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3015 if (Flags.isByVal()) {
3016 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3017 unsigned ObjSize = Flags.getByValSize();
3018 unsigned ArgSize =
3019 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3020 VecArgOffset += ArgSize;
3021 continue;
3022 }
3024 switch(ObjectVT.getSimpleVT().SimpleTy) {
3025 default: llvm_unreachable("Unhandled argument type!");
3026 case MVT::i1:
3027 case MVT::i32:
3028 case MVT::f32:
3029 VecArgOffset += 4;
3030 break;
3031 case MVT::i64: // PPC64
3032 case MVT::f64:
3033 // FIXME: We are guaranteed to be !isPPC64 at this point.
3034 // Does MVT::i64 apply?
3035 VecArgOffset += 8;
3036 break;
3037 case MVT::v4f32:
3038 case MVT::v4i32:
3039 case MVT::v8i16:
3040 case MVT::v16i8:
3041 // Nothing to do, we're only looking at Nonvector args here.
3042 break;
3043 }
3044 }
3045 }
3046 // We've found where the vector parameter area in memory is. Skip the
3047 // first 12 parameters; these don't use that memory.
3048 VecArgOffset = ((VecArgOffset+15)/16)*16;
3049 VecArgOffset += 12*16;
3051 // Add DAG nodes to load the arguments or copy them out of registers. On
3052 // entry to a function on PPC, the arguments start after the linkage area,
3053 // although the first ones are often in registers.
3055 SmallVector<SDValue, 8> MemOps;
3056 unsigned nAltivecParamsAtEnd = 0;
3057 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3058 unsigned CurArgIdx = 0;
3059 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3060 SDValue ArgVal;
3061 bool needsLoad = false;
3062 EVT ObjectVT = Ins[ArgNo].VT;
3063 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3064 unsigned ArgSize = ObjSize;
3065 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3066 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3067 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3069 unsigned CurArgOffset = ArgOffset;
3071 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3072 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3073 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3074 if (isVarArg || isPPC64) {
3075 MinReservedArea = ((MinReservedArea+15)/16)*16;
3076 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3077 Flags,
3078 PtrByteSize);
3079 } else nAltivecParamsAtEnd++;
3080 } else
3081 // Calculate min reserved area.
3082 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3083 Flags,
3084 PtrByteSize);
3086 // FIXME the codegen can be much improved in some cases.
3087 // We do not have to keep everything in memory.
3088 if (Flags.isByVal()) {
3089 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3090 ObjSize = Flags.getByValSize();
3091 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3092 // Objects of size 1 and 2 are right justified, everything else is
3093 // left justified. This means the memory address is adjusted forwards.
3094 if (ObjSize==1 || ObjSize==2) {
3095 CurArgOffset = CurArgOffset + (4 - ObjSize);
3096 }
3097 // The value of the object is its address.
3098 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3099 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3100 InVals.push_back(FIN);
3101 if (ObjSize==1 || ObjSize==2) {
3102 if (GPR_idx != Num_GPR_Regs) {
3103 unsigned VReg;
3104 if (isPPC64)
3105 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3106 else
3107 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3108 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3109 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3110 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3111 MachinePointerInfo(FuncArg),
3112 ObjType, false, false, 0);
3113 MemOps.push_back(Store);
3114 ++GPR_idx;
3115 }
3117 ArgOffset += PtrByteSize;
3119 continue;
3120 }
3121 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3122 // Store whatever pieces of the object are in registers
3123 // to memory. ArgOffset will be the address of the beginning
3124 // of the object.
3125 if (GPR_idx != Num_GPR_Regs) {
3126 unsigned VReg;
3127 if (isPPC64)
3128 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3129 else
3130 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3131 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3132 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3133 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3134 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3135 MachinePointerInfo(FuncArg, j),
3136 false, false, 0);
3137 MemOps.push_back(Store);
3138 ++GPR_idx;
3139 ArgOffset += PtrByteSize;
3140 } else {
3141 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3142 break;
3143 }
3144 }
3145 continue;
3146 }
3148 switch (ObjectVT.getSimpleVT().SimpleTy) {
3149 default: llvm_unreachable("Unhandled argument type!");
3150 case MVT::i1:
3151 case MVT::i32:
3152 if (!isPPC64) {
3153 if (GPR_idx != Num_GPR_Regs) {
3154 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3155 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3157 if (ObjectVT == MVT::i1)
3158 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3160 ++GPR_idx;
3161 } else {
3162 needsLoad = true;
3163 ArgSize = PtrByteSize;
3164 }
3165 // All int arguments reserve stack space in the Darwin ABI.
3166 ArgOffset += PtrByteSize;
3167 break;
3168 }
3169 // FALLTHROUGH
3170 case MVT::i64: // PPC64
3171 if (GPR_idx != Num_GPR_Regs) {
3172 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3173 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3175 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3176 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3177 // value to MVT::i64 and then truncate to the correct register size.
3178 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3180 ++GPR_idx;
3181 } else {
3182 needsLoad = true;
3183 ArgSize = PtrByteSize;
3184 }
3185 // All int arguments reserve stack space in the Darwin ABI.
3186 ArgOffset += 8;
3187 break;
3189 case MVT::f32:
3190 case MVT::f64:
3191 // Every 4 bytes of argument space consumes one of the GPRs available for
3192 // argument passing.
3193 if (GPR_idx != Num_GPR_Regs) {
3194 ++GPR_idx;
3195 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3196 ++GPR_idx;
3197 }
3198 if (FPR_idx != Num_FPR_Regs) {
3199 unsigned VReg;
3201 if (ObjectVT == MVT::f32)
3202 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3203 else
3204 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3206 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3207 ++FPR_idx;
3208 } else {
3209 needsLoad = true;
3210 }
3212 // All FP arguments reserve stack space in the Darwin ABI.
3213 ArgOffset += isPPC64 ? 8 : ObjSize;
3214 break;
3215 case MVT::v4f32:
3216 case MVT::v4i32:
3217 case MVT::v8i16:
3218 case MVT::v16i8:
3219 // Note that vector arguments in registers don't reserve stack space,
3220 // except in varargs functions.
3221 if (VR_idx != Num_VR_Regs) {
3222 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3223 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3224 if (isVarArg) {
3225 while ((ArgOffset % 16) != 0) {
3226 ArgOffset += PtrByteSize;
3227 if (GPR_idx != Num_GPR_Regs)
3228 GPR_idx++;
3229 }
3230 ArgOffset += 16;
3231 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3232 }
3233 ++VR_idx;
3234 } else {
3235 if (!isVarArg && !isPPC64) {
3236 // Vectors go after all the nonvectors.
3237 CurArgOffset = VecArgOffset;
3238 VecArgOffset += 16;
3239 } else {