1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
45 // FIXME: Remove this once soft-float is supported.
46 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
47 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
49 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
50 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
52 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
53 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
55 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
56 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
58 // FIXME: Remove this once the bug has been fixed!
59 extern cl::opt<bool> ANDIGlueBug;
61 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
62 const PPCSubtarget &STI)
63 : TargetLowering(TM), Subtarget(STI) {
64 // Use _setjmp/_longjmp instead of setjmp/longjmp.
65 setUseUnderscoreSetJmp(true);
66 setUseUnderscoreLongJmp(true);
68 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
69 // arguments are at least 4/8 bytes aligned.
70 bool isPPC64 = Subtarget.isPPC64();
71 setMinStackArgumentAlignment(isPPC64 ? 8:4);
73 // Set up the register classes.
74 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
75 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
76 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
78 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
79 for (MVT VT : MVT::integer_valuetypes()) {
80 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
81 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
84 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
86 // PowerPC has pre-inc load and store's.
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
102 if (Subtarget.useCRBits()) {
103 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
105 if (isPPC64 || Subtarget.hasFPCVT()) {
106 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
107 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
108 isPPC64 ? MVT::i64 : MVT::i32);
109 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
110 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
111 isPPC64 ? MVT::i64 : MVT::i32);
113 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
114 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
117 // PowerPC does not support direct load / store of condition registers
118 setOperationAction(ISD::LOAD, MVT::i1, Custom);
119 setOperationAction(ISD::STORE, MVT::i1, Custom);
121 // FIXME: Remove this once the ANDI glue bug is fixed:
123 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
125 for (MVT VT : MVT::integer_valuetypes()) {
126 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
128 setTruncStoreAction(VT, MVT::i1, Expand);
131 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
134 // This is used in the ppcf128->int sequence. Note it has different semantics
135 // from FP_ROUND: that rounds to nearest, this rounds to zero.
136 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
138 // We do not currently implement these libm ops for PowerPC.
139 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
144 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
146 // PowerPC has no SREM/UREM instructions
147 setOperationAction(ISD::SREM, MVT::i32, Expand);
148 setOperationAction(ISD::UREM, MVT::i32, Expand);
149 setOperationAction(ISD::SREM, MVT::i64, Expand);
150 setOperationAction(ISD::UREM, MVT::i64, Expand);
152 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
153 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
157 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
159 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
160 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
162 // We don't support sin/cos/sqrt/fmod/pow
163 setOperationAction(ISD::FSIN , MVT::f64, Expand);
164 setOperationAction(ISD::FCOS , MVT::f64, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
166 setOperationAction(ISD::FREM , MVT::f64, Expand);
167 setOperationAction(ISD::FPOW , MVT::f64, Expand);
168 setOperationAction(ISD::FMA , MVT::f64, Legal);
169 setOperationAction(ISD::FSIN , MVT::f32, Expand);
170 setOperationAction(ISD::FCOS , MVT::f32, Expand);
171 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
172 setOperationAction(ISD::FREM , MVT::f32, Expand);
173 setOperationAction(ISD::FPOW , MVT::f32, Expand);
174 setOperationAction(ISD::FMA , MVT::f32, Legal);
176 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
178 // If we're enabling GP optimizations, use hardware square root
179 if (!Subtarget.hasFSQRT() &&
180 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
182 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
184 if (!Subtarget.hasFSQRT() &&
185 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
186 Subtarget.hasFRES()))
187 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
189 if (Subtarget.hasFCPSGN()) {
190 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
191 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
197 if (Subtarget.hasFPRND()) {
198 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
199 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
200 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201 setOperationAction(ISD::FROUND, MVT::f64, Legal);
203 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
204 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
205 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
206 setOperationAction(ISD::FROUND, MVT::f32, Legal);
209 // PowerPC does not have BSWAP, CTPOP or CTTZ
210 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
212 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
214 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
216 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
217 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
219 if (Subtarget.hasPOPCNTD()) {
220 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
221 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
223 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
224 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
227 // PowerPC does not have ROTR
228 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
229 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
231 if (!Subtarget.useCRBits()) {
232 // PowerPC does not have Select
233 setOperationAction(ISD::SELECT, MVT::i32, Expand);
234 setOperationAction(ISD::SELECT, MVT::i64, Expand);
235 setOperationAction(ISD::SELECT, MVT::f32, Expand);
236 setOperationAction(ISD::SELECT, MVT::f64, Expand);
239 // PowerPC wants to turn select_cc of FP into fsel when possible.
240 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
243 // PowerPC wants to optimize integer setcc a bit
244 if (!Subtarget.useCRBits())
245 setOperationAction(ISD::SETCC, MVT::i32, Custom);
247 // PowerPC does not have BRCOND which requires SetCC
248 if (!Subtarget.useCRBits())
249 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
251 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
253 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
254 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
256 // PowerPC does not have [U|S]INT_TO_FP
257 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
258 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
262 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
263 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
265 // We cannot sextinreg(i1). Expand to shifts.
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
268 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
269 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
270 // support continuation, user-level threading, and etc.. As a result, no
271 // other SjLj exception interfaces are implemented and please don't build
272 // your own exception handling based on them.
273 // LLVM/Clang supports zero-cost DWARF exception handling.
274 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
275 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
277 // We want to legalize GlobalAddress and ConstantPool nodes into the
278 // appropriate instructions to materialize the address.
279 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
280 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
281 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
282 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
283 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
284 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
287 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
288 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
291 setOperationAction(ISD::TRAP, MVT::Other, Legal);
293 // TRAMPOLINE is custom lowered.
294 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
295 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
297 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298 setOperationAction(ISD::VASTART , MVT::Other, Custom);
300 if (Subtarget.isSVR4ABI()) {
302 // VAARG always uses double-word chunks, so promote anything smaller.
303 setOperationAction(ISD::VAARG, MVT::i1, Promote);
304 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
305 setOperationAction(ISD::VAARG, MVT::i8, Promote);
306 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
307 setOperationAction(ISD::VAARG, MVT::i16, Promote);
308 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
309 setOperationAction(ISD::VAARG, MVT::i32, Promote);
310 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
311 setOperationAction(ISD::VAARG, MVT::Other, Expand);
313 // VAARG is custom lowered with the 32-bit SVR4 ABI.
314 setOperationAction(ISD::VAARG, MVT::Other, Custom);
315 setOperationAction(ISD::VAARG, MVT::i64, Custom);
318 setOperationAction(ISD::VAARG, MVT::Other, Expand);
320 if (Subtarget.isSVR4ABI() && !isPPC64)
321 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
322 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
324 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
326 // Use the default implementation.
327 setOperationAction(ISD::VAEND , MVT::Other, Expand);
328 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
329 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
331 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
333 // We want to custom lower some of our intrinsics.
334 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
336 // To handle counter-based loop conditions.
337 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
339 // Comparisons that require checking two conditions.
340 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
341 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
347 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
349 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
351 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
353 if (Subtarget.has64BitSupport()) {
354 // They also have instructions for converting between i64 and fp.
355 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
356 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
357 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
358 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
359 // This is just the low 32 bits of a (signed) fp->i64 conversion.
360 // We cannot do this with Promote because i64 is not a legal type.
361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
363 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
364 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
366 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
367 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
370 // With the instructions enabled under FPCVT, we can do everything.
371 if (Subtarget.hasFPCVT()) {
372 if (Subtarget.has64BitSupport()) {
373 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
374 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
375 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
376 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
379 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
380 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
385 if (Subtarget.use64BitRegs()) {
386 // 64-bit PowerPC implementations can support i64 types directly
387 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
388 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
389 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
390 // 64-bit PowerPC wants to expand i128 shifts itself.
391 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
393 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
395 // 32-bit PowerPC wants to expand i64 shifts itself.
396 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
398 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
401 if (Subtarget.hasAltivec()) {
402 // First set operation action for all vector types to expand. Then we
403 // will selectively turn on ones that can be effectively codegen'd.
404 for (MVT VT : MVT::vector_valuetypes()) {
405 // add/sub are legal for all supported vector VT's.
406 // This check is temporary until support for quadword add/sub is added
407 if (VT.SimpleTy != MVT::v1i128) {
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
412 setOperationAction(ISD::ADD , VT, Expand);
413 setOperationAction(ISD::SUB , VT, Expand);
416 // Vector instructions introduced in P8
417 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
418 setOperationAction(ISD::CTPOP, VT, Legal);
419 setOperationAction(ISD::CTLZ, VT, Legal);
422 setOperationAction(ISD::CTPOP, VT, Expand);
423 setOperationAction(ISD::CTLZ, VT, Expand);
426 // We promote all shuffles to v16i8.
427 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
428 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
430 // We promote all non-typed operations to v4i32.
431 setOperationAction(ISD::AND , VT, Promote);
432 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
433 setOperationAction(ISD::OR , VT, Promote);
434 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
435 setOperationAction(ISD::XOR , VT, Promote);
436 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
437 setOperationAction(ISD::LOAD , VT, Promote);
438 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
439 setOperationAction(ISD::SELECT, VT, Promote);
440 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
441 setOperationAction(ISD::STORE, VT, Promote);
442 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
444 // No other operations are legal.
445 setOperationAction(ISD::MUL , VT, Expand);
446 setOperationAction(ISD::SDIV, VT, Expand);
447 setOperationAction(ISD::SREM, VT, Expand);
448 setOperationAction(ISD::UDIV, VT, Expand);
449 setOperationAction(ISD::UREM, VT, Expand);
450 setOperationAction(ISD::FDIV, VT, Expand);
451 setOperationAction(ISD::FREM, VT, Expand);
452 setOperationAction(ISD::FNEG, VT, Expand);
453 setOperationAction(ISD::FSQRT, VT, Expand);
454 setOperationAction(ISD::FLOG, VT, Expand);
455 setOperationAction(ISD::FLOG10, VT, Expand);
456 setOperationAction(ISD::FLOG2, VT, Expand);
457 setOperationAction(ISD::FEXP, VT, Expand);
458 setOperationAction(ISD::FEXP2, VT, Expand);
459 setOperationAction(ISD::FSIN, VT, Expand);
460 setOperationAction(ISD::FCOS, VT, Expand);
461 setOperationAction(ISD::FABS, VT, Expand);
462 setOperationAction(ISD::FPOWI, VT, Expand);
463 setOperationAction(ISD::FFLOOR, VT, Expand);
464 setOperationAction(ISD::FCEIL, VT, Expand);
465 setOperationAction(ISD::FTRUNC, VT, Expand);
466 setOperationAction(ISD::FRINT, VT, Expand);
467 setOperationAction(ISD::FNEARBYINT, VT, Expand);
468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
469 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
470 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
471 setOperationAction(ISD::MULHU, VT, Expand);
472 setOperationAction(ISD::MULHS, VT, Expand);
473 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
474 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
475 setOperationAction(ISD::UDIVREM, VT, Expand);
476 setOperationAction(ISD::SDIVREM, VT, Expand);
477 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
478 setOperationAction(ISD::FPOW, VT, Expand);
479 setOperationAction(ISD::BSWAP, VT, Expand);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
481 setOperationAction(ISD::CTTZ, VT, Expand);
482 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
483 setOperationAction(ISD::VSELECT, VT, Expand);
484 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
486 for (MVT InnerVT : MVT::vector_valuetypes()) {
487 setTruncStoreAction(VT, InnerVT, Expand);
488 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
489 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
490 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
494 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
495 // with merges, splats, etc.
496 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
498 setOperationAction(ISD::AND , MVT::v4i32, Legal);
499 setOperationAction(ISD::OR , MVT::v4i32, Legal);
500 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
501 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
502 setOperationAction(ISD::SELECT, MVT::v4i32,
503 Subtarget.useCRBits() ? Legal : Expand);
504 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
505 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
506 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
507 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
508 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
509 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
510 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
511 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
512 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
514 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
515 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
516 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
517 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
519 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
520 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
522 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
523 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
524 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
528 if (Subtarget.hasP8Altivec())
529 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
531 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
533 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
534 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
536 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
537 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
539 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
540 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
542 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
544 // Altivec does not contain unordered floating-point compare instructions
545 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
546 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
547 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
548 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
550 if (Subtarget.hasVSX()) {
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
552 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
554 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
555 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
556 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
557 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
558 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
560 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
562 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
563 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
565 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
566 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
568 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
569 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
570 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
571 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
572 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
574 // Share the Altivec comparison restrictions.
575 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
576 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
577 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
578 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
580 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
581 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
583 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
585 if (Subtarget.hasP8Vector())
586 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
588 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
590 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
591 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
593 if (Subtarget.hasP8Altivec()) {
594 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
595 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
596 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
598 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
601 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
602 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
603 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
605 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
607 // VSX v2i64 only supports non-arithmetic operations.
608 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
609 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
612 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
613 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
614 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
615 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
617 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
619 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
620 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
621 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
622 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
624 // Vector operation legalization checks the result type of
625 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
626 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
627 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
628 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
629 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
631 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
634 if (Subtarget.hasP8Altivec()) {
635 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
636 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
640 if (Subtarget.hasQPX()) {
641 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
642 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
643 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
644 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
646 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
647 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
649 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
650 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
652 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
653 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
655 if (!Subtarget.useCRBits())
656 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
657 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
659 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
660 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
661 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
662 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
663 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
664 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
665 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
667 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
668 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
670 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
671 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
672 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
674 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
675 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
676 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
677 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
678 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
679 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
680 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
681 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
682 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
683 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
684 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
686 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
687 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
689 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
690 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
692 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
694 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
695 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
696 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
697 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
699 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
700 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
702 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
703 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
705 if (!Subtarget.useCRBits())
706 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
707 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
709 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
710 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
711 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
712 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
713 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
714 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
715 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
717 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
718 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
720 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
721 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
722 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
723 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
724 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
725 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
726 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
727 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
728 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
729 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
730 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
732 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
733 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
735 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
736 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
738 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
740 setOperationAction(ISD::AND , MVT::v4i1, Legal);
741 setOperationAction(ISD::OR , MVT::v4i1, Legal);
742 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
744 if (!Subtarget.useCRBits())
745 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
746 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
748 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
749 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
751 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
752 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
753 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
754 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
755 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
756 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
757 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
759 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
760 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
762 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
764 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
765 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
766 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
767 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
769 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
770 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
771 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
772 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
774 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
775 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
777 // These need to set FE_INEXACT, and so cannot be vectorized here.
778 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
779 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
781 if (TM.Options.UnsafeFPMath) {
782 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
783 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
785 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
786 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
788 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
789 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
791 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
792 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
796 if (Subtarget.has64BitSupport())
797 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
799 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
802 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
803 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
806 setBooleanContents(ZeroOrOneBooleanContent);
808 if (Subtarget.hasAltivec()) {
809 // Altivec instructions set fields to all zeros or all ones.
810 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
814 // These libcalls are not available in 32-bit.
815 setLibcallName(RTLIB::SHL_I128, nullptr);
816 setLibcallName(RTLIB::SRL_I128, nullptr);
817 setLibcallName(RTLIB::SRA_I128, nullptr);
821 setStackPointerRegisterToSaveRestore(PPC::X1);
822 setExceptionPointerRegister(PPC::X3);
823 setExceptionSelectorRegister(PPC::X4);
825 setStackPointerRegisterToSaveRestore(PPC::R1);
826 setExceptionPointerRegister(PPC::R3);
827 setExceptionSelectorRegister(PPC::R4);
830 // We have target-specific dag combine patterns for the following nodes:
831 setTargetDAGCombine(ISD::SINT_TO_FP);
832 if (Subtarget.hasFPCVT())
833 setTargetDAGCombine(ISD::UINT_TO_FP);
834 setTargetDAGCombine(ISD::LOAD);
835 setTargetDAGCombine(ISD::STORE);
836 setTargetDAGCombine(ISD::BR_CC);
837 if (Subtarget.useCRBits())
838 setTargetDAGCombine(ISD::BRCOND);
839 setTargetDAGCombine(ISD::BSWAP);
840 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
841 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
842 setTargetDAGCombine(ISD::INTRINSIC_VOID);
844 setTargetDAGCombine(ISD::SIGN_EXTEND);
845 setTargetDAGCombine(ISD::ZERO_EXTEND);
846 setTargetDAGCombine(ISD::ANY_EXTEND);
848 if (Subtarget.useCRBits()) {
849 setTargetDAGCombine(ISD::TRUNCATE);
850 setTargetDAGCombine(ISD::SETCC);
851 setTargetDAGCombine(ISD::SELECT_CC);
854 // Use reciprocal estimates.
855 if (TM.Options.UnsafeFPMath) {
856 setTargetDAGCombine(ISD::FDIV);
857 setTargetDAGCombine(ISD::FSQRT);
860 // Darwin long double math library functions have $LDBL128 appended.
861 if (Subtarget.isDarwin()) {
862 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
863 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
864 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
865 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
866 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
867 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
868 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
869 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
870 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
871 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
874 // With 32 condition bits, we don't need to sink (and duplicate) compares
875 // aggressively in CodeGenPrep.
876 if (Subtarget.useCRBits()) {
877 setHasMultipleConditionRegisters();
878 setJumpIsExpensive();
881 setMinFunctionAlignment(2);
882 if (Subtarget.isDarwin())
883 setPrefFunctionAlignment(4);
885 switch (Subtarget.getDarwinDirective()) {
889 case PPC::DIR_E500mc:
898 setPrefFunctionAlignment(4);
899 setPrefLoopAlignment(4);
903 setInsertFencesForAtomic(true);
905 if (Subtarget.enableMachineScheduler())
906 setSchedulingPreference(Sched::Source);
908 setSchedulingPreference(Sched::Hybrid);
910 computeRegisterProperties(STI.getRegisterInfo());
912 // The Freescale cores do better with aggressive inlining of memcpy and
913 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
914 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
915 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
916 MaxStoresPerMemset = 32;
917 MaxStoresPerMemsetOptSize = 16;
918 MaxStoresPerMemcpy = 32;
919 MaxStoresPerMemcpyOptSize = 8;
920 MaxStoresPerMemmove = 32;
921 MaxStoresPerMemmoveOptSize = 8;
922 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
923 // The A2 also benefits from (very) aggressive inlining of memcpy and
924 // friends. The overhead of a the function call, even when warm, can be
925 // over one hundred cycles.
926 MaxStoresPerMemset = 128;
927 MaxStoresPerMemcpy = 128;
928 MaxStoresPerMemmove = 128;
932 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
933 /// the desired ByVal argument alignment.
934 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
935 unsigned MaxMaxAlign) {
936 if (MaxAlign == MaxMaxAlign)
938 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
939 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
941 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
943 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
944 unsigned EltAlign = 0;
945 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
946 if (EltAlign > MaxAlign)
948 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
949 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
950 unsigned EltAlign = 0;
951 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
952 if (EltAlign > MaxAlign)
954 if (MaxAlign == MaxMaxAlign)
960 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
961 /// function arguments in the caller parameter area.
962 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
963 // Darwin passes everything on 4 byte boundary.
964 if (Subtarget.isDarwin())
967 // 16byte and wider vectors are passed on 16byte boundary.
968 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
969 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
970 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
971 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
975 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
976 switch ((PPCISD::NodeType)Opcode) {
977 case PPCISD::FIRST_NUMBER: break;
978 case PPCISD::FSEL: return "PPCISD::FSEL";
979 case PPCISD::FCFID: return "PPCISD::FCFID";
980 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
981 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
982 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
983 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
984 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
985 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
986 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
987 case PPCISD::FRE: return "PPCISD::FRE";
988 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
989 case PPCISD::STFIWX: return "PPCISD::STFIWX";
990 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
991 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
992 case PPCISD::VPERM: return "PPCISD::VPERM";
993 case PPCISD::CMPB: return "PPCISD::CMPB";
994 case PPCISD::Hi: return "PPCISD::Hi";
995 case PPCISD::Lo: return "PPCISD::Lo";
996 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
997 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
998 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
999 case PPCISD::SRL: return "PPCISD::SRL";
1000 case PPCISD::SRA: return "PPCISD::SRA";
1001 case PPCISD::SHL: return "PPCISD::SHL";
1002 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1003 case PPCISD::CALL: return "PPCISD::CALL";
1004 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1005 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1006 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1007 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1008 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1009 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1010 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1011 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1012 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1013 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1014 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1015 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1016 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1017 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1018 case PPCISD::VCMP: return "PPCISD::VCMP";
1019 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1020 case PPCISD::LBRX: return "PPCISD::LBRX";
1021 case PPCISD::STBRX: return "PPCISD::STBRX";
1022 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1023 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1024 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1025 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1026 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1027 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1028 case PPCISD::BDZ: return "PPCISD::BDZ";
1029 case PPCISD::MFFS: return "PPCISD::MFFS";
1030 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1031 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1032 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1033 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1034 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1035 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1036 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1037 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1038 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1039 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1040 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1041 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1042 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1043 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1044 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1045 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1046 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1047 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1048 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1049 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1050 case PPCISD::SC: return "PPCISD::SC";
1051 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1052 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1053 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1054 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1055 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1056 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1057 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1062 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1064 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1066 if (Subtarget.hasQPX())
1067 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1069 return VT.changeVectorElementTypeToInteger();
1072 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1073 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1077 //===----------------------------------------------------------------------===//
1078 // Node matching predicates, for use by the tblgen matching code.
1079 //===----------------------------------------------------------------------===//
1081 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1082 static bool isFloatingPointZero(SDValue Op) {
1083 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1084 return CFP->getValueAPF().isZero();
1085 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1086 // Maybe this has already been legalized into the constant pool?
1087 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1088 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1089 return CFP->getValueAPF().isZero();
1094 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1095 /// true if Op is undef or if it matches the specified value.
1096 static bool isConstantOrUndef(int Op, int Val) {
1097 return Op < 0 || Op == Val;
1100 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1101 /// VPKUHUM instruction.
1102 /// The ShuffleKind distinguishes between big-endian operations with
1103 /// two different inputs (0), either-endian operations with two identical
1104 /// inputs (1), and little-endian operantion with two different inputs (2).
1105 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1106 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1107 SelectionDAG &DAG) {
1108 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1109 if (ShuffleKind == 0) {
1112 for (unsigned i = 0; i != 16; ++i)
1113 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1115 } else if (ShuffleKind == 2) {
1118 for (unsigned i = 0; i != 16; ++i)
1119 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1121 } else if (ShuffleKind == 1) {
1122 unsigned j = IsLE ? 0 : 1;
1123 for (unsigned i = 0; i != 8; ++i)
1124 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1125 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1131 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1132 /// VPKUWUM instruction.
1133 /// The ShuffleKind distinguishes between big-endian operations with
1134 /// two different inputs (0), either-endian operations with two identical
1135 /// inputs (1), and little-endian operantion with two different inputs (2).
1136 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1137 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1138 SelectionDAG &DAG) {
1139 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1140 if (ShuffleKind == 0) {
1143 for (unsigned i = 0; i != 16; i += 2)
1144 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1145 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1147 } else if (ShuffleKind == 2) {
1150 for (unsigned i = 0; i != 16; i += 2)
1151 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1152 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1154 } else if (ShuffleKind == 1) {
1155 unsigned j = IsLE ? 0 : 2;
1156 for (unsigned i = 0; i != 8; i += 2)
1157 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1158 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1159 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1160 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1166 /// isVMerge - Common function, used to match vmrg* shuffles.
1168 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1169 unsigned LHSStart, unsigned RHSStart) {
1170 if (N->getValueType(0) != MVT::v16i8)
1172 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1173 "Unsupported merge size!");
1175 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1176 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1177 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1178 LHSStart+j+i*UnitSize) ||
1179 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1180 RHSStart+j+i*UnitSize))
1186 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1187 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1188 /// The ShuffleKind distinguishes between big-endian merges with two
1189 /// different inputs (0), either-endian merges with two identical inputs (1),
1190 /// and little-endian merges with two different inputs (2). For the latter,
1191 /// the input operands are swapped (see PPCInstrAltivec.td).
1192 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1193 unsigned ShuffleKind, SelectionDAG &DAG) {
1194 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1195 if (ShuffleKind == 1) // unary
1196 return isVMerge(N, UnitSize, 0, 0);
1197 else if (ShuffleKind == 2) // swapped
1198 return isVMerge(N, UnitSize, 0, 16);
1202 if (ShuffleKind == 1) // unary
1203 return isVMerge(N, UnitSize, 8, 8);
1204 else if (ShuffleKind == 0) // normal
1205 return isVMerge(N, UnitSize, 8, 24);
1211 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1212 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1213 /// The ShuffleKind distinguishes between big-endian merges with two
1214 /// different inputs (0), either-endian merges with two identical inputs (1),
1215 /// and little-endian merges with two different inputs (2). For the latter,
1216 /// the input operands are swapped (see PPCInstrAltivec.td).
1217 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1218 unsigned ShuffleKind, SelectionDAG &DAG) {
1219 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1220 if (ShuffleKind == 1) // unary
1221 return isVMerge(N, UnitSize, 8, 8);
1222 else if (ShuffleKind == 2) // swapped
1223 return isVMerge(N, UnitSize, 8, 24);
1227 if (ShuffleKind == 1) // unary
1228 return isVMerge(N, UnitSize, 0, 0);
1229 else if (ShuffleKind == 0) // normal
1230 return isVMerge(N, UnitSize, 0, 16);
1237 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1238 /// amount, otherwise return -1.
1239 /// The ShuffleKind distinguishes between big-endian operations with two
1240 /// different inputs (0), either-endian operations with two identical inputs
1241 /// (1), and little-endian operations with two different inputs (2). For the
1242 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1243 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1244 SelectionDAG &DAG) {
1245 if (N->getValueType(0) != MVT::v16i8)
1248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1250 // Find the first non-undef value in the shuffle mask.
1252 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1255 if (i == 16) return -1; // all undef.
1257 // Otherwise, check to see if the rest of the elements are consecutively
1258 // numbered from this value.
1259 unsigned ShiftAmt = SVOp->getMaskElt(i);
1260 if (ShiftAmt < i) return -1;
1263 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1265 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1266 // Check the rest of the elements to see if they are consecutive.
1267 for (++i; i != 16; ++i)
1268 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1270 } else if (ShuffleKind == 1) {
1271 // Check the rest of the elements to see if they are consecutive.
1272 for (++i; i != 16; ++i)
1273 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1278 if (ShuffleKind == 2 && isLE)
1279 ShiftAmt = 16 - ShiftAmt;
1284 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1285 /// specifies a splat of a single element that is suitable for input to
1286 /// VSPLTB/VSPLTH/VSPLTW.
1287 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1288 assert(N->getValueType(0) == MVT::v16i8 &&
1289 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1291 // This is a splat operation if each element of the permute is the same, and
1292 // if the value doesn't reference the second vector.
1293 unsigned ElementBase = N->getMaskElt(0);
1295 // FIXME: Handle UNDEF elements too!
1296 if (ElementBase >= 16)
1299 // Check that the indices are consecutive, in the case of a multi-byte element
1300 // splatted with a v16i8 mask.
1301 for (unsigned i = 1; i != EltSize; ++i)
1302 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1305 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1306 if (N->getMaskElt(i) < 0) continue;
1307 for (unsigned j = 0; j != EltSize; ++j)
1308 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1314 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1315 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1316 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1317 SelectionDAG &DAG) {
1318 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1319 assert(isSplatShuffleMask(SVOp, EltSize));
1320 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1321 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1323 return SVOp->getMaskElt(0) / EltSize;
1326 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1327 /// by using a vspltis[bhw] instruction of the specified element size, return
1328 /// the constant being splatted. The ByteSize field indicates the number of
1329 /// bytes of each element [124] -> [bhw].
1330 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1331 SDValue OpVal(nullptr, 0);
1333 // If ByteSize of the splat is bigger than the element size of the
1334 // build_vector, then we have a case where we are checking for a splat where
1335 // multiple elements of the buildvector are folded together into a single
1336 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1337 unsigned EltSize = 16/N->getNumOperands();
1338 if (EltSize < ByteSize) {
1339 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1340 SDValue UniquedVals[4];
1341 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1343 // See if all of the elements in the buildvector agree across.
1344 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1345 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1346 // If the element isn't a constant, bail fully out.
1347 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1350 if (!UniquedVals[i&(Multiple-1)].getNode())
1351 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1352 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1353 return SDValue(); // no match.
1356 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1357 // either constant or undef values that are identical for each chunk. See
1358 // if these chunks can form into a larger vspltis*.
1360 // Check to see if all of the leading entries are either 0 or -1. If
1361 // neither, then this won't fit into the immediate field.
1362 bool LeadingZero = true;
1363 bool LeadingOnes = true;
1364 for (unsigned i = 0; i != Multiple-1; ++i) {
1365 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1367 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1368 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1370 // Finally, check the least significant entry.
1372 if (!UniquedVals[Multiple-1].getNode())
1373 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1374 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1375 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1376 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1379 if (!UniquedVals[Multiple-1].getNode())
1380 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1381 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1382 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1383 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1389 // Check to see if this buildvec has a single non-undef value in its elements.
1390 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1391 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1392 if (!OpVal.getNode())
1393 OpVal = N->getOperand(i);
1394 else if (OpVal != N->getOperand(i))
1398 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1400 unsigned ValSizeInBytes = EltSize;
1402 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1403 Value = CN->getZExtValue();
1404 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1405 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1406 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1409 // If the splat value is larger than the element value, then we can never do
1410 // this splat. The only case that we could fit the replicated bits into our
1411 // immediate field for would be zero, and we prefer to use vxor for it.
1412 if (ValSizeInBytes < ByteSize) return SDValue();
1414 // If the element value is larger than the splat value, check if it consists
1415 // of a repeated bit pattern of size ByteSize.
1416 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1419 // Properly sign extend the value.
1420 int MaskVal = SignExtend32(Value, ByteSize * 8);
1422 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1423 if (MaskVal == 0) return SDValue();
1425 // Finally, if this value fits in a 5 bit sext field, return it
1426 if (SignExtend32<5>(MaskVal) == MaskVal)
1427 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1431 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1432 /// amount, otherwise return -1.
1433 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1434 EVT VT = N->getValueType(0);
1435 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1438 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1440 // Find the first non-undef value in the shuffle mask.
1442 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1445 if (i == 4) return -1; // all undef.
1447 // Otherwise, check to see if the rest of the elements are consecutively
1448 // numbered from this value.
1449 unsigned ShiftAmt = SVOp->getMaskElt(i);
1450 if (ShiftAmt < i) return -1;
1453 // Check the rest of the elements to see if they are consecutive.
1454 for (++i; i != 4; ++i)
1455 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1461 //===----------------------------------------------------------------------===//
1462 // Addressing Mode Selection
1463 //===----------------------------------------------------------------------===//
1465 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1466 /// or 64-bit immediate, and if the value can be accurately represented as a
1467 /// sign extension from a 16-bit value. If so, this returns true and the
1469 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1470 if (!isa<ConstantSDNode>(N))
1473 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1474 if (N->getValueType(0) == MVT::i32)
1475 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1477 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1479 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1480 return isIntS16Immediate(Op.getNode(), Imm);
1484 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1485 /// can be represented as an indexed [r+r] operation. Returns false if it
1486 /// can be more efficiently represented with [r+imm].
1487 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1489 SelectionDAG &DAG) const {
1491 if (N.getOpcode() == ISD::ADD) {
1492 if (isIntS16Immediate(N.getOperand(1), imm))
1493 return false; // r+i
1494 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1495 return false; // r+i
1497 Base = N.getOperand(0);
1498 Index = N.getOperand(1);
1500 } else if (N.getOpcode() == ISD::OR) {
1501 if (isIntS16Immediate(N.getOperand(1), imm))
1502 return false; // r+i can fold it if we can.
1504 // If this is an or of disjoint bitfields, we can codegen this as an add
1505 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1507 APInt LHSKnownZero, LHSKnownOne;
1508 APInt RHSKnownZero, RHSKnownOne;
1509 DAG.computeKnownBits(N.getOperand(0),
1510 LHSKnownZero, LHSKnownOne);
1512 if (LHSKnownZero.getBoolValue()) {
1513 DAG.computeKnownBits(N.getOperand(1),
1514 RHSKnownZero, RHSKnownOne);
1515 // If all of the bits are known zero on the LHS or RHS, the add won't
1517 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1518 Base = N.getOperand(0);
1519 Index = N.getOperand(1);
1528 // If we happen to be doing an i64 load or store into a stack slot that has
1529 // less than a 4-byte alignment, then the frame-index elimination may need to
1530 // use an indexed load or store instruction (because the offset may not be a
1531 // multiple of 4). The extra register needed to hold the offset comes from the
1532 // register scavenger, and it is possible that the scavenger will need to use
1533 // an emergency spill slot. As a result, we need to make sure that a spill slot
1534 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1536 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1537 // FIXME: This does not handle the LWA case.
1541 // NOTE: We'll exclude negative FIs here, which come from argument
1542 // lowering, because there are no known test cases triggering this problem
1543 // using packed structures (or similar). We can remove this exclusion if
1544 // we find such a test case. The reason why this is so test-case driven is
1545 // because this entire 'fixup' is only to prevent crashes (from the
1546 // register scavenger) on not-really-valid inputs. For example, if we have:
1548 // %b = bitcast i1* %a to i64*
1549 // store i64* a, i64 b
1550 // then the store should really be marked as 'align 1', but is not. If it
1551 // were marked as 'align 1' then the indexed form would have been
1552 // instruction-selected initially, and the problem this 'fixup' is preventing
1553 // won't happen regardless.
1557 MachineFunction &MF = DAG.getMachineFunction();
1558 MachineFrameInfo *MFI = MF.getFrameInfo();
1560 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1564 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1565 FuncInfo->setHasNonRISpills();
1568 /// Returns true if the address N can be represented by a base register plus
1569 /// a signed 16-bit displacement [r+imm], and if it is not better
1570 /// represented as reg+reg. If Aligned is true, only accept displacements
1571 /// suitable for STD and friends, i.e. multiples of 4.
1572 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1575 bool Aligned) const {
1576 // FIXME dl should come from parent load or store, not from address
1578 // If this can be more profitably realized as r+r, fail.
1579 if (SelectAddressRegReg(N, Disp, Base, DAG))
1582 if (N.getOpcode() == ISD::ADD) {
1584 if (isIntS16Immediate(N.getOperand(1), imm) &&
1585 (!Aligned || (imm & 3) == 0)) {
1586 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1587 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1588 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1589 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1591 Base = N.getOperand(0);
1593 return true; // [r+i]
1594 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1595 // Match LOAD (ADD (X, Lo(G))).
1596 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1597 && "Cannot handle constant offsets yet!");
1598 Disp = N.getOperand(1).getOperand(0); // The global address.
1599 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1600 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1601 Disp.getOpcode() == ISD::TargetConstantPool ||
1602 Disp.getOpcode() == ISD::TargetJumpTable);
1603 Base = N.getOperand(0);
1604 return true; // [&g+r]
1606 } else if (N.getOpcode() == ISD::OR) {
1608 if (isIntS16Immediate(N.getOperand(1), imm) &&
1609 (!Aligned || (imm & 3) == 0)) {
1610 // If this is an or of disjoint bitfields, we can codegen this as an add
1611 // (for better address arithmetic) if the LHS and RHS of the OR are
1612 // provably disjoint.
1613 APInt LHSKnownZero, LHSKnownOne;
1614 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1616 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1617 // If all of the bits are known zero on the LHS or RHS, the add won't
1619 if (FrameIndexSDNode *FI =
1620 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1621 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1622 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1624 Base = N.getOperand(0);
1626 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1630 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1631 // Loading from a constant address.
1633 // If this address fits entirely in a 16-bit sext immediate field, codegen
1636 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1637 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1638 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1639 CN->getValueType(0));
1643 // Handle 32-bit sext immediates with LIS + addr mode.
1644 if ((CN->getValueType(0) == MVT::i32 ||
1645 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1646 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1647 int Addr = (int)CN->getZExtValue();
1649 // Otherwise, break this down into an LIS + disp.
1650 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1652 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1654 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1655 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1660 Disp = DAG.getTargetConstant(0, dl, getPointerTy());
1661 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1662 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1663 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1666 return true; // [r+0]
1669 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1670 /// represented as an indexed [r+r] operation.
1671 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1673 SelectionDAG &DAG) const {
1674 // Check to see if we can easily represent this as an [r+r] address. This
1675 // will fail if it thinks that the address is more profitably represented as
1676 // reg+imm, e.g. where imm = 0.
1677 if (SelectAddressRegReg(N, Base, Index, DAG))
1680 // If the operand is an addition, always emit this as [r+r], since this is
1681 // better (for code size, and execution, as the memop does the add for free)
1682 // than emitting an explicit add.
1683 if (N.getOpcode() == ISD::ADD) {
1684 Base = N.getOperand(0);
1685 Index = N.getOperand(1);
1689 // Otherwise, do it the hard way, using R0 as the base register.
1690 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1696 /// getPreIndexedAddressParts - returns true by value, base pointer and
1697 /// offset pointer and addressing mode by reference if the node's address
1698 /// can be legally represented as pre-indexed load / store address.
1699 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1701 ISD::MemIndexedMode &AM,
1702 SelectionDAG &DAG) const {
1703 if (DisablePPCPreinc) return false;
1709 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1710 Ptr = LD->getBasePtr();
1711 VT = LD->getMemoryVT();
1712 Alignment = LD->getAlignment();
1713 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1714 Ptr = ST->getBasePtr();
1715 VT = ST->getMemoryVT();
1716 Alignment = ST->getAlignment();
1721 // PowerPC doesn't have preinc load/store instructions for vectors (except
1722 // for QPX, which does have preinc r+r forms).
1723 if (VT.isVector()) {
1724 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1726 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1732 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1734 // Common code will reject creating a pre-inc form if the base pointer
1735 // is a frame index, or if N is a store and the base pointer is either
1736 // the same as or a predecessor of the value being stored. Check for
1737 // those situations here, and try with swapped Base/Offset instead.
1740 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1743 SDValue Val = cast<StoreSDNode>(N)->getValue();
1744 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1749 std::swap(Base, Offset);
1755 // LDU/STU can only handle immediates that are a multiple of 4.
1756 if (VT != MVT::i64) {
1757 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1760 // LDU/STU need an address with at least 4-byte alignment.
1764 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1768 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1769 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1770 // sext i32 to i64 when addr mode is r+i.
1771 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1772 LD->getExtensionType() == ISD::SEXTLOAD &&
1773 isa<ConstantSDNode>(Offset))
1781 //===----------------------------------------------------------------------===//
1782 // LowerOperation implementation
1783 //===----------------------------------------------------------------------===//
1785 /// GetLabelAccessInfo - Return true if we should reference labels using a
1786 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1787 static bool GetLabelAccessInfo(const TargetMachine &TM,
1788 const PPCSubtarget &Subtarget,
1789 unsigned &HiOpFlags, unsigned &LoOpFlags,
1790 const GlobalValue *GV = nullptr) {
1791 HiOpFlags = PPCII::MO_HA;
1792 LoOpFlags = PPCII::MO_LO;
1794 // Don't use the pic base if not in PIC relocation model.
1795 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1798 HiOpFlags |= PPCII::MO_PIC_FLAG;
1799 LoOpFlags |= PPCII::MO_PIC_FLAG;
1802 // If this is a reference to a global value that requires a non-lazy-ptr, make
1803 // sure that instruction lowering adds it.
1804 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1805 HiOpFlags |= PPCII::MO_NLP_FLAG;
1806 LoOpFlags |= PPCII::MO_NLP_FLAG;
1808 if (GV->hasHiddenVisibility()) {
1809 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1810 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1817 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1818 SelectionDAG &DAG) {
1820 EVT PtrVT = HiPart.getValueType();
1821 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1823 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1824 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1826 // With PIC, the first instruction is actually "GR+hi(&G)".
1828 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1829 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1831 // Generate non-pic code that has direct accesses to the constant pool.
1832 // The address of the global is just (hi(&g)+lo(&g)).
1833 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1836 static void setUsesTOCBasePtr(MachineFunction &MF) {
1837 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1838 FuncInfo->setUsesTOCBasePtr();
1841 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1842 setUsesTOCBasePtr(DAG.getMachineFunction());
1845 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1847 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1848 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1849 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1851 SDValue Ops[] = { GA, Reg };
1852 return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1853 DAG.getVTList(VT, MVT::Other), Ops, VT,
1854 MachinePointerInfo::getGOT(), 0, false, true,
1858 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1859 SelectionDAG &DAG) const {
1860 EVT PtrVT = Op.getValueType();
1861 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1862 const Constant *C = CP->getConstVal();
1864 // 64-bit SVR4 ABI code is always position-independent.
1865 // The actual address of the GlobalValue is stored in the TOC.
1866 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1867 setUsesTOCBasePtr(DAG);
1868 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1869 return getTOCEntry(DAG, SDLoc(CP), true, GA);
1872 unsigned MOHiFlag, MOLoFlag;
1874 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1876 if (isPIC && Subtarget.isSVR4ABI()) {
1877 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1878 PPCII::MO_PIC_FLAG);
1879 return getTOCEntry(DAG, SDLoc(CP), false, GA);
1883 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1885 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1886 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1889 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1890 EVT PtrVT = Op.getValueType();
1891 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1893 // 64-bit SVR4 ABI code is always position-independent.
1894 // The actual address of the GlobalValue is stored in the TOC.
1895 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1896 setUsesTOCBasePtr(DAG);
1897 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1898 return getTOCEntry(DAG, SDLoc(JT), true, GA);
1901 unsigned MOHiFlag, MOLoFlag;
1903 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1905 if (isPIC && Subtarget.isSVR4ABI()) {
1906 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1907 PPCII::MO_PIC_FLAG);
1908 return getTOCEntry(DAG, SDLoc(GA), false, GA);
1911 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1912 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1913 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1916 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1917 SelectionDAG &DAG) const {
1918 EVT PtrVT = Op.getValueType();
1919 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1920 const BlockAddress *BA = BASDN->getBlockAddress();
1922 // 64-bit SVR4 ABI code is always position-independent.
1923 // The actual BlockAddress is stored in the TOC.
1924 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1925 setUsesTOCBasePtr(DAG);
1926 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1927 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1930 unsigned MOHiFlag, MOLoFlag;
1932 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1933 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1934 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1935 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1938 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1939 SelectionDAG &DAG) const {
1941 // FIXME: TLS addresses currently use medium model code sequences,
1942 // which is the most useful form. Eventually support for small and
1943 // large models could be added if users need it, at the cost of
1944 // additional complexity.
1945 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1947 const GlobalValue *GV = GA->getGlobal();
1948 EVT PtrVT = getPointerTy();
1949 bool is64bit = Subtarget.isPPC64();
1950 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1951 PICLevel::Level picLevel = M->getPICLevel();
1953 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1955 if (Model == TLSModel::LocalExec) {
1956 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1957 PPCII::MO_TPREL_HA);
1958 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1959 PPCII::MO_TPREL_LO);
1960 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1961 is64bit ? MVT::i64 : MVT::i32);
1962 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1963 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1966 if (Model == TLSModel::InitialExec) {
1967 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1968 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1972 setUsesTOCBasePtr(DAG);
1973 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1974 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1975 PtrVT, GOTReg, TGA);
1977 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1978 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1979 PtrVT, TGA, GOTPtr);
1980 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1983 if (Model == TLSModel::GeneralDynamic) {
1984 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1987 setUsesTOCBasePtr(DAG);
1988 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1989 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1992 if (picLevel == PICLevel::Small)
1993 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1995 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1997 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2001 if (Model == TLSModel::LocalDynamic) {
2002 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2005 setUsesTOCBasePtr(DAG);
2006 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2007 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2010 if (picLevel == PICLevel::Small)
2011 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2013 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2015 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2016 PtrVT, GOTPtr, TGA, TGA);
2017 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2018 PtrVT, TLSAddr, TGA);
2019 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2022 llvm_unreachable("Unknown TLS model!");
2025 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2026 SelectionDAG &DAG) const {
2027 EVT PtrVT = Op.getValueType();
2028 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2030 const GlobalValue *GV = GSDN->getGlobal();
2032 // 64-bit SVR4 ABI code is always position-independent.
2033 // The actual address of the GlobalValue is stored in the TOC.
2034 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2035 setUsesTOCBasePtr(DAG);
2036 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2037 return getTOCEntry(DAG, DL, true, GA);
2040 unsigned MOHiFlag, MOLoFlag;
2042 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2044 if (isPIC && Subtarget.isSVR4ABI()) {
2045 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2047 PPCII::MO_PIC_FLAG);
2048 return getTOCEntry(DAG, DL, false, GA);
2052 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2054 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2056 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2058 // If the global reference is actually to a non-lazy-pointer, we have to do an
2059 // extra load to get the address of the global.
2060 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2061 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2062 false, false, false, 0);
2066 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2067 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2070 if (Op.getValueType() == MVT::v2i64) {
2071 // When the operands themselves are v2i64 values, we need to do something
2072 // special because VSX has no underlying comparison operations for these.
2073 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2074 // Equality can be handled by casting to the legal type for Altivec
2075 // comparisons, everything else needs to be expanded.
2076 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2077 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2078 DAG.getSetCC(dl, MVT::v4i32,
2079 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2080 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2087 // We handle most of these in the usual way.
2091 // If we're comparing for equality to zero, expose the fact that this is
2092 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2093 // fold the new nodes.
2094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2095 if (C->isNullValue() && CC == ISD::SETEQ) {
2096 EVT VT = Op.getOperand(0).getValueType();
2097 SDValue Zext = Op.getOperand(0);
2098 if (VT.bitsLT(MVT::i32)) {
2100 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2102 unsigned Log2b = Log2_32(VT.getSizeInBits());
2103 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2104 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2105 DAG.getConstant(Log2b, dl, MVT::i32));
2106 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2108 // Leave comparisons against 0 and -1 alone for now, since they're usually
2109 // optimized. FIXME: revisit this when we can custom lower all setcc
2111 if (C->isAllOnesValue() || C->isNullValue())
2115 // If we have an integer seteq/setne, turn it into a compare against zero
2116 // by xor'ing the rhs with the lhs, which is faster than setting a
2117 // condition register, reading it back out, and masking the correct bit. The
2118 // normal approach here uses sub to do this instead of xor. Using xor exposes
2119 // the result to other bit-twiddling opportunities.
2120 EVT LHSVT = Op.getOperand(0).getValueType();
2121 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2122 EVT VT = Op.getValueType();
2123 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2125 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2130 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2131 const PPCSubtarget &Subtarget) const {
2132 SDNode *Node = Op.getNode();
2133 EVT VT = Node->getValueType(0);
2134 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2135 SDValue InChain = Node->getOperand(0);
2136 SDValue VAListPtr = Node->getOperand(1);
2137 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2140 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2143 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2144 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2145 false, false, false, 0);
2146 InChain = GprIndex.getValue(1);
2148 if (VT == MVT::i64) {
2149 // Check if GprIndex is even
2150 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2151 DAG.getConstant(1, dl, MVT::i32));
2152 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2153 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2154 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2155 DAG.getConstant(1, dl, MVT::i32));
2156 // Align GprIndex to be even if it isn't
2157 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2161 // fpr index is 1 byte after gpr
2162 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2163 DAG.getConstant(1, dl, MVT::i32));
2166 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2167 FprPtr, MachinePointerInfo(SV), MVT::i8,
2168 false, false, false, 0);
2169 InChain = FprIndex.getValue(1);
2171 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2172 DAG.getConstant(8, dl, MVT::i32));
2174 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2175 DAG.getConstant(4, dl, MVT::i32));
2178 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2179 MachinePointerInfo(), false, false,
2181 InChain = OverflowArea.getValue(1);
2183 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2184 MachinePointerInfo(), false, false,
2186 InChain = RegSaveArea.getValue(1);
2188 // select overflow_area if index > 8
2189 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2190 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2192 // adjustment constant gpr_index * 4/8
2193 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2194 VT.isInteger() ? GprIndex : FprIndex,
2195 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2198 // OurReg = RegSaveArea + RegConstant
2199 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2202 // Floating types are 32 bytes into RegSaveArea
2203 if (VT.isFloatingPoint())
2204 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2205 DAG.getConstant(32, dl, MVT::i32));
2207 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2208 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2209 VT.isInteger() ? GprIndex : FprIndex,
2210 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2213 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2214 VT.isInteger() ? VAListPtr : FprPtr,
2215 MachinePointerInfo(SV),
2216 MVT::i8, false, false, 0);
2218 // determine if we should load from reg_save_area or overflow_area
2219 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2221 // increase overflow_area by 4/8 if gpr/fpr > 8
2222 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2223 DAG.getConstant(VT.isInteger() ? 4 : 8,
2226 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2229 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2231 MachinePointerInfo(),
2232 MVT::i32, false, false, 0);
2234 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2235 false, false, false, 0);
2238 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2239 const PPCSubtarget &Subtarget) const {
2240 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2242 // We have to copy the entire va_list struct:
2243 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2244 return DAG.getMemcpy(Op.getOperand(0), Op,
2245 Op.getOperand(1), Op.getOperand(2),
2246 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2247 false, MachinePointerInfo(), MachinePointerInfo());
2250 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2251 SelectionDAG &DAG) const {
2252 return Op.getOperand(0);
2255 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2256 SelectionDAG &DAG) const {
2257 SDValue Chain = Op.getOperand(0);
2258 SDValue Trmp = Op.getOperand(1); // trampoline
2259 SDValue FPtr = Op.getOperand(2); // nested function
2260 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2263 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2264 bool isPPC64 = (PtrVT == MVT::i64);
2266 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2269 TargetLowering::ArgListTy Args;
2270 TargetLowering::ArgListEntry Entry;
2272 Entry.Ty = IntPtrTy;
2273 Entry.Node = Trmp; Args.push_back(Entry);
2275 // TrampSize == (isPPC64 ? 48 : 40);
2276 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2277 isPPC64 ? MVT::i64 : MVT::i32);
2278 Args.push_back(Entry);
2280 Entry.Node = FPtr; Args.push_back(Entry);
2281 Entry.Node = Nest; Args.push_back(Entry);
2283 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2284 TargetLowering::CallLoweringInfo CLI(DAG);
2285 CLI.setDebugLoc(dl).setChain(Chain)
2286 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2287 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2288 std::move(Args), 0);
2290 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2291 return CallResult.second;
2294 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2295 const PPCSubtarget &Subtarget) const {
2296 MachineFunction &MF = DAG.getMachineFunction();
2297 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2301 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2302 // vastart just stores the address of the VarArgsFrameIndex slot into the
2303 // memory location argument.
2304 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2305 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2306 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2307 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2308 MachinePointerInfo(SV),
2312 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2313 // We suppose the given va_list is already allocated.
2316 // char gpr; /* index into the array of 8 GPRs
2317 // * stored in the register save area
2318 // * gpr=0 corresponds to r3,
2319 // * gpr=1 to r4, etc.
2321 // char fpr; /* index into the array of 8 FPRs
2322 // * stored in the register save area
2323 // * fpr=0 corresponds to f1,
2324 // * fpr=1 to f2, etc.
2326 // char *overflow_arg_area;
2327 // /* location on stack that holds
2328 // * the next overflow argument
2330 // char *reg_save_area;
2331 // /* where r3:r10 and f1:f8 (if saved)
2337 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2338 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2341 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2343 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2345 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2348 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2349 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2351 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2352 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2354 uint64_t FPROffset = 1;
2355 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2357 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2359 // Store first byte : number of int regs
2360 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2362 MachinePointerInfo(SV),
2363 MVT::i8, false, false, 0);
2364 uint64_t nextOffset = FPROffset;
2365 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2368 // Store second byte : number of float regs
2369 SDValue secondStore =
2370 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2371 MachinePointerInfo(SV, nextOffset), MVT::i8,
2373 nextOffset += StackOffset;
2374 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2376 // Store second word : arguments given on stack
2377 SDValue thirdStore =
2378 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2379 MachinePointerInfo(SV, nextOffset),
2381 nextOffset += FrameOffset;
2382 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2384 // Store third word : arguments given in registers
2385 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2386 MachinePointerInfo(SV, nextOffset),
2391 #include "PPCGenCallingConv.inc"
2393 // Function whose sole purpose is to kill compiler warnings
2394 // stemming from unused functions included from PPCGenCallingConv.inc.
2395 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2396 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2399 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2400 CCValAssign::LocInfo &LocInfo,
2401 ISD::ArgFlagsTy &ArgFlags,
2406 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2408 CCValAssign::LocInfo &LocInfo,
2409 ISD::ArgFlagsTy &ArgFlags,
2411 static const MCPhysReg ArgRegs[] = {
2412 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2413 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2415 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2417 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2419 // Skip one register if the first unallocated register has an even register
2420 // number and there are still argument registers available which have not been
2421 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2422 // need to skip a register if RegNum is odd.
2423 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2424 State.AllocateReg(ArgRegs[RegNum]);
2427 // Always return false here, as this function only makes sure that the first
2428 // unallocated register has an odd register number and does not actually
2429 // allocate a register for the current argument.
2433 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2435 CCValAssign::LocInfo &LocInfo,
2436 ISD::ArgFlagsTy &ArgFlags,
2438 static const MCPhysReg ArgRegs[] = {
2439 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2443 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2445 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2447 // If there is only one Floating-point register left we need to put both f64
2448 // values of a split ppc_fp128 value on the stack.
2449 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2450 State.AllocateReg(ArgRegs[RegNum]);
2453 // Always return false here, as this function only makes sure that the two f64
2454 // values a ppc_fp128 value is split into are both passed in registers or both
2455 // passed on the stack and does not actually allocate a register for the
2456 // current argument.
2460 /// FPR - The set of FP registers that should be allocated for arguments,
2462 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2463 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2464 PPC::F11, PPC::F12, PPC::F13};
2466 /// QFPR - The set of QPX registers that should be allocated for arguments.
2467 static const MCPhysReg QFPR[] = {
2468 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2469 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2471 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2473 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2474 unsigned PtrByteSize) {
2475 unsigned ArgSize = ArgVT.getStoreSize();
2476 if (Flags.isByVal())
2477 ArgSize = Flags.getByValSize();
2479 // Round up to multiples of the pointer size, except for array members,
2480 // which are always packed.
2481 if (!Flags.isInConsecutiveRegs())
2482 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2487 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2489 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2490 ISD::ArgFlagsTy Flags,
2491 unsigned PtrByteSize) {
2492 unsigned Align = PtrByteSize;
2494 // Altivec parameters are padded to a 16 byte boundary.
2495 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2496 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2497 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2498 ArgVT == MVT::v1i128)
2500 // QPX vector types stored in double-precision are padded to a 32 byte
2502 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2505 // ByVal parameters are aligned as requested.
2506 if (Flags.isByVal()) {
2507 unsigned BVAlign = Flags.getByValAlign();
2508 if (BVAlign > PtrByteSize) {
2509 if (BVAlign % PtrByteSize != 0)
2511 "ByVal alignment is not a multiple of the pointer size");
2517 // Array members are always packed to their original alignment.
2518 if (Flags.isInConsecutiveRegs()) {
2519 // If the array member was split into multiple registers, the first
2520 // needs to be aligned to the size of the full type. (Except for
2521 // ppcf128, which is only aligned as its f64 components.)
2522 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2523 Align = OrigVT.getStoreSize();
2525 Align = ArgVT.getStoreSize();
2531 /// CalculateStackSlotUsed - Return whether this argument will use its
2532 /// stack slot (instead of being passed in registers). ArgOffset,
2533 /// AvailableFPRs, and AvailableVRs must hold the current argument
2534 /// position, and will be updated to account for this argument.
2535 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2536 ISD::ArgFlagsTy Flags,
2537 unsigned PtrByteSize,
2538 unsigned LinkageSize,
2539 unsigned ParamAreaSize,
2540 unsigned &ArgOffset,
2541 unsigned &AvailableFPRs,
2542 unsigned &AvailableVRs, bool HasQPX) {
2543 bool UseMemory = false;
2545 // Respect alignment of argument on the stack.
2547 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2548 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2549 // If there's no space left in the argument save area, we must
2550 // use memory (this check also catches zero-sized arguments).
2551 if (ArgOffset >= LinkageSize + ParamAreaSize)
2554 // Allocate argument on the stack.
2555 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2556 if (Flags.isInConsecutiveRegsLast())
2557 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2558 // If we overran the argument save area, we must use memory
2559 // (this check catches arguments passed partially in memory)
2560 if (ArgOffset > LinkageSize + ParamAreaSize)
2563 // However, if the argument is actually passed in an FPR or a VR,
2564 // we don't use memory after all.
2565 if (!Flags.isByVal()) {
2566 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2567 // QPX registers overlap with the scalar FP registers.
2568 (HasQPX && (ArgVT == MVT::v4f32 ||
2569 ArgVT == MVT::v4f64 ||
2570 ArgVT == MVT::v4i1)))
2571 if (AvailableFPRs > 0) {
2575 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2576 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2577 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2578 ArgVT == MVT::v1i128)
2579 if (AvailableVRs > 0) {
2588 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2589 /// ensure minimum alignment required for target.
2590 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2591 unsigned NumBytes) {
2592 unsigned TargetAlign = Lowering->getStackAlignment();
2593 unsigned AlignMask = TargetAlign - 1;
2594 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2599 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2600 CallingConv::ID CallConv, bool isVarArg,
2601 const SmallVectorImpl<ISD::InputArg>
2603 SDLoc dl, SelectionDAG &DAG,
2604 SmallVectorImpl<SDValue> &InVals)
2606 if (Subtarget.isSVR4ABI()) {
2607 if (Subtarget.isPPC64())
2608 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2611 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2614 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2620 PPCTargetLowering::LowerFormalArguments_32SVR4(
2622 CallingConv::ID CallConv, bool isVarArg,
2623 const SmallVectorImpl<ISD::InputArg>
2625 SDLoc dl, SelectionDAG &DAG,
2626 SmallVectorImpl<SDValue> &InVals) const {
2628 // 32-bit SVR4 ABI Stack Frame Layout:
2629 // +-----------------------------------+
2630 // +--> | Back chain |
2631 // | +-----------------------------------+
2632 // | | Floating-point register save area |
2633 // | +-----------------------------------+
2634 // | | General register save area |
2635 // | +-----------------------------------+
2636 // | | CR save word |
2637 // | +-----------------------------------+
2638 // | | VRSAVE save word |
2639 // | +-----------------------------------+
2640 // | | Alignment padding |
2641 // | +-----------------------------------+
2642 // | | Vector register save area |
2643 // | +-----------------------------------+
2644 // | | Local variable space |
2645 // | +-----------------------------------+
2646 // | | Parameter list area |
2647 // | +-----------------------------------+
2648 // | | LR save word |
2649 // | +-----------------------------------+
2650 // SP--> +--- | Back chain |
2651 // +-----------------------------------+
2654 // System V Application Binary Interface PowerPC Processor Supplement
2655 // AltiVec Technology Programming Interface Manual
2657 MachineFunction &MF = DAG.getMachineFunction();
2658 MachineFrameInfo *MFI = MF.getFrameInfo();
2659 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2661 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2662 // Potential tail calls could cause overwriting of argument stack slots.
2663 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2664 (CallConv == CallingConv::Fast));
2665 unsigned PtrByteSize = 4;
2667 // Assign locations to all of the incoming arguments.
2668 SmallVector<CCValAssign, 16> ArgLocs;
2669 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2672 // Reserve space for the linkage area on the stack.
2673 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2674 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2676 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2678 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2679 CCValAssign &VA = ArgLocs[i];
2681 // Arguments stored in registers.
2682 if (VA.isRegLoc()) {
2683 const TargetRegisterClass *RC;
2684 EVT ValVT = VA.getValVT();
2686 switch (ValVT.getSimpleVT().SimpleTy) {
2688 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2691 RC = &PPC::GPRCRegClass;
2694 if (Subtarget.hasP8Vector())
2695 RC = &PPC::VSSRCRegClass;
2697 RC = &PPC::F4RCRegClass;
2700 if (Subtarget.hasVSX())
2701 RC = &PPC::VSFRCRegClass;
2703 RC = &PPC::F8RCRegClass;
2708 RC = &PPC::VRRCRegClass;
2711 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2715 RC = &PPC::VSHRCRegClass;
2718 RC = &PPC::QFRCRegClass;
2721 RC = &PPC::QBRCRegClass;
2725 // Transform the arguments stored in physical registers into virtual ones.
2726 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2727 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2728 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2730 if (ValVT == MVT::i1)
2731 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2733 InVals.push_back(ArgValue);
2735 // Argument stored in memory.
2736 assert(VA.isMemLoc());
2738 unsigned ArgSize = VA.getLocVT().getStoreSize();
2739 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2742 // Create load nodes to retrieve arguments from the stack.
2743 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2744 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2745 MachinePointerInfo(),
2746 false, false, false, 0));
2750 // Assign locations to all of the incoming aggregate by value arguments.
2751 // Aggregates passed by value are stored in the local variable space of the
2752 // caller's stack frame, right above the parameter list area.
2753 SmallVector<CCValAssign, 16> ByValArgLocs;
2754 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2755 ByValArgLocs, *DAG.getContext());
2757 // Reserve stack space for the allocations in CCInfo.
2758 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2760 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2762 // Area that is at least reserved in the caller of this function.
2763 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2764 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2766 // Set the size that is at least reserved in caller of this function. Tail
2767 // call optimized function's reserved stack space needs to be aligned so that
2768 // taking the difference between two stack areas will result in an aligned
2771 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2772 FuncInfo->setMinReservedArea(MinReservedArea);
2774 SmallVector<SDValue, 8> MemOps;
2776 // If the function takes variable number of arguments, make a frame index for
2777 // the start of the first vararg value... for expansion of llvm.va_start.
2779 static const MCPhysReg GPArgRegs[] = {
2780 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2781 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2783 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2785 static const MCPhysReg FPArgRegs[] = {
2786 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2789 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2790 if (DisablePPCFloatInVariadic)
2793 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2794 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2796 // Make room for NumGPArgRegs and NumFPArgRegs.
2797 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2798 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2800 FuncInfo->setVarArgsStackOffset(
2801 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2802 CCInfo.getNextStackOffset(), true));
2804 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2805 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2807 // The fixed integer arguments of a variadic function are stored to the
2808 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2809 // the result of va_next.
2810 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2811 // Get an existing live-in vreg, or add a new one.
2812 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2814 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2816 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2817 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2818 MachinePointerInfo(), false, false, 0);
2819 MemOps.push_back(Store);
2820 // Increment the address by four for the next argument to store
2821 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2822 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2825 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2827 // The double arguments are stored to the VarArgsFrameIndex
2829 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2830 // Get an existing live-in vreg, or add a new one.
2831 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2833 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2835 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2836 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2837 MachinePointerInfo(), false, false, 0);
2838 MemOps.push_back(Store);
2839 // Increment the address by eight for the next argument to store
2840 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2842 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2846 if (!MemOps.empty())
2847 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2852 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2853 // value to MVT::i64 and then truncate to the correct register size.
2855 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2856 SelectionDAG &DAG, SDValue ArgVal,
2859 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2860 DAG.getValueType(ObjectVT));
2861 else if (Flags.isZExt())
2862 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2863 DAG.getValueType(ObjectVT));
2865 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2869 PPCTargetLowering::LowerFormalArguments_64SVR4(
2871 CallingConv::ID CallConv, bool isVarArg,
2872 const SmallVectorImpl<ISD::InputArg>
2874 SDLoc dl, SelectionDAG &DAG,
2875 SmallVectorImpl<SDValue> &InVals) const {
2876 // TODO: add description of PPC stack frame format, or at least some docs.
2878 bool isELFv2ABI = Subtarget.isELFv2ABI();
2879 bool isLittleEndian = Subtarget.isLittleEndian();
2880 MachineFunction &MF = DAG.getMachineFunction();
2881 MachineFrameInfo *MFI = MF.getFrameInfo();
2882 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2884 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2885 "fastcc not supported on varargs functions");
2887 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2888 // Potential tail calls could cause overwriting of argument stack slots.
2889 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2890 (CallConv == CallingConv::Fast));
2891 unsigned PtrByteSize = 8;
2892 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2894 static const MCPhysReg GPR[] = {
2895 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2896 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2898 static const MCPhysReg VR[] = {
2899 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2900 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2902 static const MCPhysReg VSRH[] = {
2903 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2904 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2907 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2908 const unsigned Num_FPR_Regs = 13;
2909 const unsigned Num_VR_Regs = array_lengthof(VR);
2910 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2912 // Do a first pass over the arguments to determine whether the ABI
2913 // guarantees that our caller has allocated the parameter save area
2914 // on its stack frame. In the ELFv1 ABI, this is always the case;
2915 // in the ELFv2 ABI, it is true if this is a vararg function or if
2916 // any parameter is located in a stack slot.
2918 bool HasParameterArea = !isELFv2ABI || isVarArg;
2919 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2920 unsigned NumBytes = LinkageSize;
2921 unsigned AvailableFPRs = Num_FPR_Regs;
2922 unsigned AvailableVRs = Num_VR_Regs;
2923 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2924 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2925 PtrByteSize, LinkageSize, ParamAreaSize,
2926 NumBytes, AvailableFPRs, AvailableVRs,
2927 Subtarget.hasQPX()))
2928 HasParameterArea = true;
2930 // Add DAG nodes to load the arguments or copy them out of registers. On
2931 // entry to a function on PPC, the arguments start after the linkage area,
2932 // although the first ones are often in registers.
2934 unsigned ArgOffset = LinkageSize;
2935 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2936 unsigned &QFPR_idx = FPR_idx;
2937 SmallVector<SDValue, 8> MemOps;
2938 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2939 unsigned CurArgIdx = 0;
2940 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2942 bool needsLoad = false;
2943 EVT ObjectVT = Ins[ArgNo].VT;
2944 EVT OrigVT = Ins[ArgNo].ArgVT;
2945 unsigned ObjSize = ObjectVT.getStoreSize();
2946 unsigned ArgSize = ObjSize;
2947 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2948 if (Ins[ArgNo].isOrigArg()) {
2949 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2950 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2952 // We re-align the argument offset for each argument, except when using the
2953 // fast calling convention, when we need to make sure we do that only when
2954 // we'll actually use a stack slot.
2955 unsigned CurArgOffset, Align;
2956 auto ComputeArgOffset = [&]() {
2957 /* Respect alignment of argument on the stack. */
2958 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2959 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2960 CurArgOffset = ArgOffset;
2963 if (CallConv != CallingConv::Fast) {
2966 /* Compute GPR index associated with argument offset. */
2967 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2968 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2971 // FIXME the codegen can be much improved in some cases.
2972 // We do not have to keep everything in memory.
2973 if (Flags.isByVal()) {
2974 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2976 if (CallConv == CallingConv::Fast)
2979 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2980 ObjSize = Flags.getByValSize();
2981 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2982 // Empty aggregate parameters do not take up registers. Examples:
2986 // etc. However, we have to provide a place-holder in InVals, so
2987 // pretend we have an 8-byte item at the current address for that
2990 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2991 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2992 InVals.push_back(FIN);
2996 // Create a stack object covering all stack doublewords occupied
2997 // by the argument. If the argument is (fully or partially) on
2998 // the stack, or if the argument is fully in registers but the
2999 // caller has allocated the parameter save anyway, we can refer
3000 // directly to the caller's stack frame. Otherwise, create a
3001 // local copy in our own frame.
3003 if (HasParameterArea ||
3004 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3005 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3007 FI = MFI->CreateStackObject(ArgSize, Align, false);
3008 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3010 // Handle aggregates smaller than 8 bytes.
3011 if (ObjSize < PtrByteSize) {
3012 // The value of the object is its address, which differs from the
3013 // address of the enclosing doubleword on big-endian systems.
3015 if (!isLittleEndian) {
3016 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3017 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3019 InVals.push_back(Arg);
3021 if (GPR_idx != Num_GPR_Regs) {
3022 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3023 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3026 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3027 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3028 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3029 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3030 MachinePointerInfo(FuncArg),
3031 ObjType, false, false, 0);
3033 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3034 // store the whole register as-is to the parameter save area
3036 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3037 MachinePointerInfo(FuncArg),
3041 MemOps.push_back(Store);
3043 // Whether we copied from a register or not, advance the offset
3044 // into the parameter save area by a full doubleword.
3045 ArgOffset += PtrByteSize;
3049 // The value of the object is its address, which is the address of
3050 // its first stack doubleword.
3051 InVals.push_back(FIN);
3053 // Store whatever pieces of the object are in registers to memory.
3054 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3055 if (GPR_idx == Num_GPR_Regs)
3058 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3059 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3062 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3063 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3065 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3066 MachinePointerInfo(FuncArg, j),
3068 MemOps.push_back(Store);
3071 ArgOffset += ArgSize;
3075 switch (ObjectVT.getSimpleVT().SimpleTy) {
3076 default: llvm_unreachable("Unhandled argument type!");
3080 // These can be scalar arguments or elements of an integer array type
3081 // passed directly. Clang may use those instead of "byval" aggregate
3082 // types to avoid forcing arguments to memory unnecessarily.
3083 if (GPR_idx != Num_GPR_Regs) {
3084 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3085 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3087 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3088 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3089 // value to MVT::i64 and then truncate to the correct register size.
3090 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3092 if (CallConv == CallingConv::Fast)
3096 ArgSize = PtrByteSize;
3098 if (CallConv != CallingConv::Fast || needsLoad)
3104 // These can be scalar arguments or elements of a float array type
3105 // passed directly. The latter are used to implement ELFv2 homogenous
3106 // float aggregates.
3107 if (FPR_idx != Num_FPR_Regs) {
3110 if (ObjectVT == MVT::f32)
3111 VReg = MF.addLiveIn(FPR[FPR_idx],
3112 Subtarget.hasP8Vector()
3113 ? &PPC::VSSRCRegClass
3114 : &PPC::F4RCRegClass);
3116 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3117 ? &PPC::VSFRCRegClass
3118 : &PPC::F8RCRegClass);
3120 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3122 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3123 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3124 // once we support fp <-> gpr moves.
3126 // This can only ever happen in the presence of f32 array types,
3127 // since otherwise we never run out of FPRs before running out
3129 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3130 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3132 if (ObjectVT == MVT::f32) {
3133 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3134 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3135 DAG.getConstant(32, dl, MVT::i32));
3136 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3139 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3141 if (CallConv == CallingConv::Fast)
3147 // When passing an array of floats, the array occupies consecutive
3148 // space in the argument area; only round up to the next doubleword
3149 // at the end of the array. Otherwise, each float takes 8 bytes.
3150 if (CallConv != CallingConv::Fast || needsLoad) {
3151 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3152 ArgOffset += ArgSize;
3153 if (Flags.isInConsecutiveRegsLast())
3154 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3164 if (!Subtarget.hasQPX()) {
3165 // These can be scalar arguments or elements of a vector array type
3166 // passed directly. The latter are used to implement ELFv2 homogenous
3167 // vector aggregates.
3168 if (VR_idx != Num_VR_Regs) {
3169 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3170 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3171 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3172 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3175 if (CallConv == CallingConv::Fast)
3180 if (CallConv != CallingConv::Fast || needsLoad)
3185 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3186 "Invalid QPX parameter type");
3191 // QPX vectors are treated like their scalar floating-point subregisters
3192 // (except that they're larger).
3193 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3194 if (QFPR_idx != Num_QFPR_Regs) {
3195 const TargetRegisterClass *RC;
3196 switch (ObjectVT.getSimpleVT().SimpleTy) {
3197 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3198 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3199 default: RC = &PPC::QBRCRegClass; break;
3202 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3203 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3206 if (CallConv == CallingConv::Fast)
3210 if (CallConv != CallingConv::Fast || needsLoad)
3215 // We need to load the argument to a virtual register if we determined
3216 // above that we ran out of physical registers of the appropriate type.
3218 if (ObjSize < ArgSize && !isLittleEndian)
3219 CurArgOffset += ArgSize - ObjSize;
3220 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3221 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3222 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3223 false, false, false, 0);
3226 InVals.push_back(ArgVal);
3229 // Area that is at least reserved in the caller of this function.
3230 unsigned MinReservedArea;
3231 if (HasParameterArea)
3232 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3234 MinReservedArea = LinkageSize;
3236 // Set the size that is at least reserved in caller of this function. Tail
3237 // call optimized functions' reserved stack space needs to be aligned so that
3238 // taking the difference between two stack areas will result in an aligned
3241 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3242 FuncInfo->setMinReservedArea(MinReservedArea);
3244 // If the function takes variable number of arguments, make a frame index for
3245 // the start of the first vararg value... for expansion of llvm.va_start.
3247 int Depth = ArgOffset;
3249 FuncInfo->setVarArgsFrameIndex(
3250 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3251 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3253 // If this function is vararg, store any remaining integer argument regs
3254 // to their spots on the stack so that they may be loaded by deferencing the
3255 // result of va_next.
3256 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3257 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3258 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3259 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3260 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3261 MachinePointerInfo(), false, false, 0);
3262 MemOps.push_back(Store);
3263 // Increment the address by four for the next argument to store
3264 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3265 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3269 if (!MemOps.empty())
3270 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3276 PPCTargetLowering::LowerFormalArguments_Darwin(
3278 CallingConv::ID CallConv, bool isVarArg,
3279 const SmallVectorImpl<ISD::InputArg>
3281 SDLoc dl, SelectionDAG &DAG,
3282 SmallVectorImpl<SDValue> &InVals) const {
3283 // TODO: add description of PPC stack frame format, or at least some docs.
3285 MachineFunction &MF = DAG.getMachineFunction();
3286 MachineFrameInfo *MFI = MF.getFrameInfo();
3287 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3289 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3290 bool isPPC64 = PtrVT == MVT::i64;
3291 // Potential tail calls could cause overwriting of argument stack slots.
3292 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3293 (CallConv == CallingConv::Fast));
3294 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3295 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3296 unsigned ArgOffset = LinkageSize;
3297 // Area that is at least reserved in caller of this function.
3298 unsigned MinReservedArea = ArgOffset;
3300 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3301 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3302 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3304 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3305 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3306 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3308 static const MCPhysReg VR[] = {
3309 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3310 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3313 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3314 const unsigned Num_FPR_Regs = 13;
3315 const unsigned Num_VR_Regs = array_lengthof( VR);
3317 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3319 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3321 // In 32-bit non-varargs functions, the stack space for vectors is after the
3322 // stack space for non-vectors. We do not use this space unless we have
3323 // too many vectors to fit in registers, something that only occurs in
3324 // constructed examples:), but we have to walk the arglist to figure
3325 // that out...for the pathological case, compute VecArgOffset as the
3326 // start of the vector parameter area. Computing VecArgOffset is the
3327 // entire point of the following loop.
3328 unsigned VecArgOffset = ArgOffset;
3329 if (!isVarArg && !isPPC64) {
3330 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3332 EVT ObjectVT = Ins[ArgNo].VT;
3333 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3335 if (Flags.isByVal()) {
3336 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3337 unsigned ObjSize = Flags.getByValSize();
3339 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3340 VecArgOffset += ArgSize;
3344 switch(ObjectVT.getSimpleVT().SimpleTy) {
3345 default: llvm_unreachable("Unhandled argument type!");
3351 case MVT::i64: // PPC64
3353 // FIXME: We are guaranteed to be !isPPC64 at this point.
3354 // Does MVT::i64 apply?
3361 // Nothing to do, we're only looking at Nonvector args here.
3366 // We've found where the vector parameter area in memory is. Skip the
3367 // first 12 parameters; these don't use that memory.
3368 VecArgOffset = ((VecArgOffset+15)/16)*16;
3369 VecArgOffset += 12*16;
3371 // Add DAG nodes to load the arguments or copy them out of registers. On
3372 // entry to a function on PPC, the arguments start after the linkage area,
3373 // although the first ones are often in registers.
3375 SmallVector<SDValue, 8> MemOps;
3376 unsigned nAltivecParamsAtEnd = 0;
3377 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3378 unsigned CurArgIdx = 0;
3379 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3381 bool needsLoad = false;
3382 EVT ObjectVT = Ins[ArgNo].VT;
3383 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3384 unsigned ArgSize = ObjSize;
3385 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3386 if (Ins[ArgNo].isOrigArg()) {
3387 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3388 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3390 unsigned CurArgOffset = ArgOffset;
3392 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3393 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3394 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3395 if (isVarArg || isPPC64) {
3396 MinReservedArea = ((MinReservedArea+15)/16)*16;
3397 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3400 } else nAltivecParamsAtEnd++;
3402 // Calculate min reserved area.
3403 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3407 // FIXME the codegen can be much improved in some cases.
3408 // We do not have to keep everything in memory.
3409 if (Flags.isByVal()) {
3410 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3412 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3413 ObjSize = Flags.getByValSize();
3414 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3415 // Objects of size 1 and 2 are right justified, everything else is
3416 // left justified. This means the memory address is adjusted forwards.
3417 if (ObjSize==1 || ObjSize==2) {
3418 CurArgOffset = CurArgOffset + (4 - ObjSize);
3420 // The value of the object is its address.
3421 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3422 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3423 InVals.push_back(FIN);
3424 if (ObjSize==1 || ObjSize==2) {
3425 if (GPR_idx != Num_GPR_Regs) {
3428 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3430 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3431 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3432 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3433 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3434 MachinePointerInfo(FuncArg),
3435 ObjType, false, false, 0);
3436 MemOps.push_back(Store);
3440 ArgOffset += PtrByteSize;
3444 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3445 // Store whatever pieces of the object are in registers
3446 // to memory. ArgOffset will be the address of the beginning
3448 if (GPR_idx != Num_GPR_Regs) {
3451 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3453 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3454 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3455 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3456 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3457 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3458 MachinePointerInfo(FuncArg, j),
3460 MemOps.push_back(Store);
3462 ArgOffset += PtrByteSize;
3464 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3471 switch (ObjectVT.getSimpleVT().SimpleTy) {
3472 default: llvm_unreachable("Unhandled argument type!");
3476 if (GPR_idx != Num_GPR_Regs) {
3477 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3478 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3480 if (ObjectVT == MVT::i1)
3481 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3486 ArgSize = PtrByteSize;
3488 // All int arguments reserve stack space in the Darwin ABI.
3489 ArgOffset += PtrByteSize;
3493 case MVT::i64: // PPC64
3494 if (GPR_idx != Num_GPR_Regs) {
3495 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3496 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3498 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3499 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3500 // value to MVT::i64 and then truncate to the correct register size.
3501 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3506 ArgSize = PtrByteSize;
3508 // All int arguments reserve stack space in the Darwin ABI.
3514 // Every 4 bytes of argument space consumes one of the GPRs available for
3515 // argument passing.
3516 if (GPR_idx != Num_GPR_Regs) {
3518 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3521 if (FPR_idx != Num_FPR_Regs) {
3524 if (ObjectVT == MVT::f32)
3525 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3527 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3529 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3535 // All FP arguments reserve stack space in the Darwin ABI.
3536 ArgOffset += isPPC64 ? 8 : ObjSize;
3542 // Note that vector arguments in registers don't reserve stack space,
3543 // except in varargs functions.
3544 if (VR_idx != Num_VR_Regs) {
3545 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3546 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3548 while ((ArgOffset % 16) != 0) {
3549 ArgOffset += PtrByteSize;
3550 if (GPR_idx != Num_GPR_Regs)
3554 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3558 if (!isVarArg && !isPPC64) {
3559 // Vectors go after all the nonvectors.
3560 CurArgOffset = VecArgOffset;
3563 // Vectors are aligned.
3564 ArgOffset = ((ArgOffset+15)/16)*16;
3565 CurArgOffset = ArgOffset;
3573 // We need to load the argument to a virtual register if we determined above
3574 // that we ran out of physical registers of the appropriate type.
3576 int FI = MFI->CreateFixedObject(ObjSize,
3577 CurArgOffset + (ArgSize - ObjSize),
3579 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3580 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3581 false, false, false, 0);
3584 InVals.push_back(ArgVal);
3587 // Allow for Altivec parameters at the end, if needed.
3588 if (nAltivecParamsAtEnd) {
3589 MinReservedArea = ((MinReservedArea+15)/16)*16;
3590 MinReservedArea += 16*nAltivecParamsAtEnd;
3593 // Area that is at least reserved in the caller of this function.
3594 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3596 // Set the size that is at least reserved in caller of this function. Tail
3597 // call optimized functions' reserved stack space needs to be aligned so that
3598 // taking the difference between two stack areas will result in an aligned
3601 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3602 FuncInfo->setMinReservedArea(MinReservedArea);
3604 // If the function takes variable number of arguments, make a frame index for
3605 // the start of the first vararg value... for expansion of llvm.va_start.
3607 int Depth = ArgOffset;
3609 FuncInfo->setVarArgsFrameIndex(
3610 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3612 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3614 // If this function is vararg, store any remaining integer argument regs
3615 // to their spots on the stack so that they may be loaded by deferencing the
3616 // result of va_next.
3617 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3621 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3623 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3625 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3626 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3627 MachinePointerInfo(), false, false, 0);
3628 MemOps.push_back(Store);
3629 // Increment the address by four for the next argument to store
3630 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3631 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3635 if (!MemOps.empty())
3636 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3641 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3642 /// adjusted to accommodate the arguments for the tailcall.
3643 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3644 unsigned ParamSize) {
3646 if (!isTailCall) return 0;
3648 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3649 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3650 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3651 // Remember only if the new adjustement is bigger.
3652 if (SPDiff < FI->getTailCallSPDelta())
3653 FI->setTailCallSPDelta(SPDiff);
3658 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3659 /// for tail call optimization. Targets which want to do tail call
3660 /// optimization should implement this function.
3662 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3663 CallingConv::ID CalleeCC,
3665 const SmallVectorImpl<ISD::InputArg> &Ins,
3666 SelectionDAG& DAG) const {
3667 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3670 // Variable argument functions are not supported.
3674 MachineFunction &MF = DAG.getMachineFunction();
3675 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3676 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3677 // Functions containing by val parameters are not supported.
3678 for (unsigned i = 0; i != Ins.size(); i++) {
3679 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3680 if (Flags.isByVal()) return false;
3683 // Non-PIC/GOT tail calls are supported.
3684 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3687 // At the moment we can only do local tail calls (in same module, hidden
3688 // or protected) if we are generating PIC.
3689 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3690 return G->getGlobal()->hasHiddenVisibility()
3691 || G->getGlobal()->hasProtectedVisibility();
3697 /// isCallCompatibleAddress - Return the immediate to use if the specified
3698 /// 32-bit value is representable in the immediate field of a BxA instruction.
3699 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3701 if (!C) return nullptr;
3703 int Addr = C->getZExtValue();
3704 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3705 SignExtend32<26>(Addr) != Addr)
3706 return nullptr; // Top 6 bits have to be sext of immediate.
3708 return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3709 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3714 struct TailCallArgumentInfo {
3719 TailCallArgumentInfo() : FrameIdx(0) {}
3724 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3726 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3728 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3729 SmallVectorImpl<SDValue> &MemOpChains,
3731 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3732 SDValue Arg = TailCallArgs[i].Arg;
3733 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3734 int FI = TailCallArgs[i].FrameIdx;
3735 // Store relative to framepointer.
3736 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3737 MachinePointerInfo::getFixedStack(FI),
3742 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3743 /// the appropriate stack slot for the tail call optimized function call.
3744 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3745 MachineFunction &MF,
3754 // Calculate the new stack slot for the return address.
3755 int SlotSize = isPPC64 ? 8 : 4;
3756 const PPCFrameLowering *FL =
3757 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3758 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3759 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3760 NewRetAddrLoc, true);
3761 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3762 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3763 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3764 MachinePointerInfo::getFixedStack(NewRetAddr),
3767 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3768 // slot as the FP is never overwritten.
3770 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3771 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3773 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3774 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3775 MachinePointerInfo::getFixedStack(NewFPIdx),
3782 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3783 /// the position of the argument.
3785 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3786 SDValue Arg, int SPDiff, unsigned ArgOffset,
3787 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3788 int Offset = ArgOffset + SPDiff;
3789 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3790 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3791 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3792 SDValue FIN = DAG.getFrameIndex(FI, VT);
3793 TailCallArgumentInfo Info;
3795 Info.FrameIdxOp = FIN;
3797 TailCallArguments.push_back(Info);
3800 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3801 /// stack slot. Returns the chain as result and the loaded frame pointers in
3802 /// LROpOut/FPOpout. Used when tail calling.
3803 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3811 // Load the LR and FP stack slot for later adjusting.
3812 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3813 LROpOut = getReturnAddrFrameIndex(DAG);
3814 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3815 false, false, false, 0);
3816 Chain = SDValue(LROpOut.getNode(), 1);
3818 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3819 // slot as the FP is never overwritten.
3821 FPOpOut = getFramePointerFrameIndex(DAG);
3822 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3823 false, false, false, 0);
3824 Chain = SDValue(FPOpOut.getNode(), 1);
3830 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3831 /// by "Src" to address "Dst" of size "Size". Alignment information is
3832 /// specified by the specific parameter attribute. The copy will be passed as
3833 /// a byval function parameter.
3834 /// Sometimes what we are copying is the end of a larger object, the part that
3835 /// does not fit in registers.
3837 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3838 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3840 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3841 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3842 false, false, false, MachinePointerInfo(),
3843 MachinePointerInfo());
3846 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3849 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3850 SDValue Arg, SDValue PtrOff, int SPDiff,
3851 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3852 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3853 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3855 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3860 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3862 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3863 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3864 DAG.getConstant(ArgOffset, dl, PtrVT));
3866 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3867 MachinePointerInfo(), false, false, 0));
3868 // Calculate and remember argument location.
3869 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3874 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3875 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3876 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3877 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3878 MachineFunction &MF = DAG.getMachineFunction();
3880 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3881 // might overwrite each other in case of tail call optimization.
3882 SmallVector<SDValue, 8> MemOpChains2;
3883 // Do not flag preceding copytoreg stuff together with the following stuff.
3885 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3887 if (!MemOpChains2.empty())
3888 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3890 // Store the return address to the appropriate stack slot.
3891 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3892 isPPC64, isDarwinABI, dl);
3894 // Emit callseq_end just before tailcall node.
3895 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
3896 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3897 InFlag = Chain.getValue(1);
3900 // Is this global address that of a function that can be called by name? (as
3901 // opposed to something that must hold a descriptor for an indirect call).
3902 static bool isFunctionGlobalAddress(SDValue Callee) {
3903 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3904 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3905 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3908 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3915 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3916 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3917 bool isTailCall, bool IsPatchPoint,
3918 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3919 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3920 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3922 bool isPPC64 = Subtarget.isPPC64();
3923 bool isSVR4ABI = Subtarget.isSVR4ABI();
3924 bool isELFv2ABI = Subtarget.isELFv2ABI();
3926 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3927 NodeTys.push_back(MVT::Other); // Returns a chain
3928 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3930 unsigned CallOpc = PPCISD::CALL;
3932 bool needIndirectCall = true;
3933 if (!isSVR4ABI || !isPPC64)
3934 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3935 // If this is an absolute destination address, use the munged value.
3936 Callee = SDValue(Dest, 0);
3937 needIndirectCall = false;
3940 if (isFunctionGlobalAddress(Callee)) {
3941 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3942 // A call to a TLS address is actually an indirect call to a
3943 // thread-specific pointer.
3944 unsigned OpFlags = 0;
3945 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3946 (Subtarget.getTargetTriple().isMacOSX() &&
3947 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3948 (G->getGlobal()->isDeclaration() ||
3949 G->getGlobal()->isWeakForLinker())) ||
3950 (Subtarget.isTargetELF() && !isPPC64 &&
3951 !G->getGlobal()->hasLocalLinkage() &&
3952 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3953 // PC-relative references to external symbols should go through $stub,
3954 // unless we're building with the leopard linker or later, which
3955 // automatically synthesizes these stubs.
3956 OpFlags = PPCII::MO_PLT_OR_STUB;
3959 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3960 // every direct call is) turn it into a TargetGlobalAddress /
3961 // TargetExternalSymbol node so that legalize doesn't hack it.
3962 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3963 Callee.getValueType(), 0, OpFlags);
3964 needIndirectCall = false;
3967 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3968 unsigned char OpFlags = 0;
3970 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3971 (Subtarget.getTargetTriple().isMacOSX() &&
3972 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3973 (Subtarget.isTargetELF() && !isPPC64 &&
3974 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3975 // PC-relative references to external symbols should go through $stub,
3976 // unless we're building with the leopard linker or later, which
3977 // automatically synthesizes these stubs.
3978 OpFlags = PPCII::MO_PLT_OR_STUB;
3981 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3983 needIndirectCall = false;
3987 // We'll form an invalid direct call when lowering a patchpoint; the full
3988 // sequence for an indirect call is complicated, and many of the
3989 // instructions introduced might have side effects (and, thus, can't be
3990 // removed later). The call itself will be removed as soon as the
3991 // argument/return lowering is complete, so the fact that it has the wrong
3992 // kind of operands should not really matter.
3993 needIndirectCall = false;
3996 if (needIndirectCall) {
3997 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3998 // to do the call, we can't use PPCISD::CALL.
3999 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4001 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4002 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4003 // entry point, but to the function descriptor (the function entry point
4004 // address is part of the function descriptor though).
4005 // The function descriptor is a three doubleword structure with the
4006 // following fields: function entry point, TOC base address and
4007 // environment pointer.
4008 // Thus for a call through a function pointer, the following actions need
4010 // 1. Save the TOC of the caller in the TOC save area of its stack
4011 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4012 // 2. Load the address of the function entry point from the function
4014 // 3. Load the TOC of the callee from the function descriptor into r2.
4015 // 4. Load the environment pointer from the function descriptor into
4017 // 5. Branch to the function entry point address.
4018 // 6. On return of the callee, the TOC of the caller needs to be
4019 // restored (this is done in FinishCall()).
4021 // The loads are scheduled at the beginning of the call sequence, and the
4022 // register copies are flagged together to ensure that no other
4023 // operations can be scheduled in between. E.g. without flagging the
4024 // copies together, a TOC access in the caller could be scheduled between
4025 // the assignment of the callee TOC and the branch to the callee, which
4026 // results in the TOC access going through the TOC of the callee instead
4027 // of going through the TOC of the caller, which leads to incorrect code.
4029 // Load the address of the function entry point from the function
4031 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4032 if (LDChain.getValueType() == MVT::Glue)
4033 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4035 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4037 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4038 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4039 false, false, LoadsInv, 8);
4041 // Load environment pointer into r11.
4042 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4043 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4044 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4045 MPI.getWithOffset(16), false, false,
4048 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4049 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4050 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4051 MPI.getWithOffset(8), false, false,
4054 setUsesTOCBasePtr(DAG);
4055 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4057 Chain = TOCVal.getValue(0);
4058 InFlag = TOCVal.getValue(1);
4060 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4063 Chain = EnvVal.getValue(0);
4064 InFlag = EnvVal.getValue(1);
4066 MTCTROps[0] = Chain;
4067 MTCTROps[1] = LoadFuncPtr;
4068 MTCTROps[2] = InFlag;
4071 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4072 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4073 InFlag = Chain.getValue(1);
4076 NodeTys.push_back(MVT::Other);
4077 NodeTys.push_back(MVT::Glue);
4078 Ops.push_back(Chain);
4079 CallOpc = PPCISD::BCTRL;
4080 Callee.setNode(nullptr);
4081 // Add use of X11 (holding environment pointer)
4082 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4083 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4084 // Add CTR register as callee so a bctr can be emitted later.
4086 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4089 // If this is a direct call, pass the chain and the callee.
4090 if (Callee.getNode()) {
4091 Ops.push_back(Chain);
4092 Ops.push_back(Callee);
4094 // If this is a tail call add stack pointer delta.
4096 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4098 // Add argument registers to the end of the list so that they are known live
4100 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4101 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4102 RegsToPass[i].second.getValueType()));
4104 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4106 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4107 setUsesTOCBasePtr(DAG);
4108 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4115 bool isLocalCall(const SDValue &Callee)
4117 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4118 return !G->getGlobal()->isDeclaration() &&
4119 !G->getGlobal()->isWeakForLinker();
4124 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4125 CallingConv::ID CallConv, bool isVarArg,
4126 const SmallVectorImpl<ISD::InputArg> &Ins,
4127 SDLoc dl, SelectionDAG &DAG,
4128 SmallVectorImpl<SDValue> &InVals) const {
4130 SmallVector<CCValAssign, 16> RVLocs;
4131 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4133 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4135 // Copy all of the result registers out of their specified physreg.
4136 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4137 CCValAssign &VA = RVLocs[i];
4138 assert(VA.isRegLoc() && "Can only return in registers!");
4140 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4141 VA.getLocReg(), VA.getLocVT(), InFlag);
4142 Chain = Val.getValue(1);
4143 InFlag = Val.getValue(2);
4145 switch (VA.getLocInfo()) {
4146 default: llvm_unreachable("Unknown loc info!");
4147 case CCValAssign::Full: break;
4148 case CCValAssign::AExt:
4149 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4151 case CCValAssign::ZExt:
4152 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4153 DAG.getValueType(VA.getValVT()));
4154 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4156 case CCValAssign::SExt:
4157 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4158 DAG.getValueType(VA.getValVT()));
4159 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4163 InVals.push_back(Val);
4170 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4171 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4173 SmallVector<std::pair<unsigned, SDValue>, 8>
4175 SDValue InFlag, SDValue Chain,
4176 SDValue CallSeqStart, SDValue &Callee,
4177 int SPDiff, unsigned NumBytes,
4178 const SmallVectorImpl<ISD::InputArg> &Ins,
4179 SmallVectorImpl<SDValue> &InVals,
4180 ImmutableCallSite *CS) const {
4182 std::vector<EVT> NodeTys;
4183 SmallVector<SDValue, 8> Ops;
4184 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4185 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4186 Ops, NodeTys, CS, Subtarget);
4188 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4189 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4190 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4192 // When performing tail call optimization the callee pops its arguments off
4193 // the stack. Account for this here so these bytes can be pushed back on in
4194 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4195 int BytesCalleePops =
4196 (CallConv == CallingConv::Fast &&
4197 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4199 // Add a register mask operand representing the call-preserved registers.
4200 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4201 const uint32_t *Mask =
4202 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4203 assert(Mask && "Missing call preserved mask for calling convention");
4204 Ops.push_back(DAG.getRegisterMask(Mask));
4206 if (InFlag.getNode())
4207 Ops.push_back(InFlag);
4211 assert(((Callee.getOpcode() == ISD::Register &&
4212 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4213 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4214 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4215 isa<ConstantSDNode>(Callee)) &&
4216 "Expecting an global address, external symbol, absolute value or register");
4218 MF.getFrameInfo()->setHasTailCall();
4219 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4222 // Add a NOP immediately after the branch instruction when using the 64-bit
4223 // SVR4 ABI. At link time, if caller and callee are in a different module and
4224 // thus have a different TOC, the call will be replaced with a call to a stub
4225 // function which saves the current TOC, loads the TOC of the callee and
4226 // branches to the callee. The NOP will be replaced with a load instruction
4227 // which restores the TOC of the caller from the TOC save slot of the current
4228 // stack frame. If caller and callee belong to the same module (and have the
4229 // same TOC), the NOP will remain unchanged.
4231 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4233 if (CallOpc == PPCISD::BCTRL) {
4234 // This is a call through a function pointer.
4235 // Restore the caller TOC from the save area into R2.
4236 // See PrepareCall() for more information about calls through function
4237 // pointers in the 64-bit SVR4 ABI.
4238 // We are using a target-specific load with r2 hard coded, because the
4239 // result of a target-independent load would never go directly into r2,
4240 // since r2 is a reserved register (which prevents the register allocator
4241 // from allocating it), resulting in an additional register being
4242 // allocated and an unnecessary move instruction being generated.
4243 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4245 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4246 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4247 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4248 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4249 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4251 // The address needs to go after the chain input but before the flag (or
4252 // any other variadic arguments).
4253 Ops.insert(std::next(Ops.begin()), AddTOC);
4254 } else if ((CallOpc == PPCISD::CALL) &&
4255 (!isLocalCall(Callee) ||
4256 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4257 // Otherwise insert NOP for non-local calls.
4258 CallOpc = PPCISD::CALL_NOP;
4261 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4262 InFlag = Chain.getValue(1);
4264 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4265 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4268 InFlag = Chain.getValue(1);
4270 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4271 Ins, dl, DAG, InVals);
4275 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4276 SmallVectorImpl<SDValue> &InVals) const {
4277 SelectionDAG &DAG = CLI.DAG;
4279 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4280 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4281 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4282 SDValue Chain = CLI.Chain;
4283 SDValue Callee = CLI.Callee;
4284 bool &isTailCall = CLI.IsTailCall;
4285 CallingConv::ID CallConv = CLI.CallConv;
4286 bool isVarArg = CLI.IsVarArg;
4287 bool IsPatchPoint = CLI.IsPatchPoint;
4288 ImmutableCallSite *CS = CLI.CS;
4291 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4294 if (!isTailCall && CS && CS->isMustTailCall())
4295 report_fatal_error("failed to perform tail call elimination on a call "
4296 "site marked musttail");
4298 if (Subtarget.isSVR4ABI()) {
4299 if (Subtarget.isPPC64())
4300 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4301 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4302 dl, DAG, InVals, CS);
4304 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4305 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4306 dl, DAG, InVals, CS);
4309 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4310 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4311 dl, DAG, InVals, CS);
4315 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4316 CallingConv::ID CallConv, bool isVarArg,
4317 bool isTailCall, bool IsPatchPoint,
4318 const SmallVectorImpl<ISD::OutputArg> &Outs,
4319 const SmallVectorImpl<SDValue> &OutVals,
4320 const SmallVectorImpl<ISD::InputArg> &Ins,
4321 SDLoc dl, SelectionDAG &DAG,
4322 SmallVectorImpl<SDValue> &InVals,
4323 ImmutableCallSite *CS) const {
4324 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4325 // of the 32-bit SVR4 ABI stack frame layout.
4327 assert((CallConv == CallingConv::C ||
4328 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4330 unsigned PtrByteSize = 4;
4332 MachineFunction &MF = DAG.getMachineFunction();
4334 // Mark this function as potentially containing a function that contains a
4335 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4336 // and restoring the callers stack pointer in this functions epilog. This is
4337 // done because by tail calling the called function might overwrite the value
4338 // in this function's (MF) stack pointer stack slot 0(SP).
4339 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4340 CallConv == CallingConv::Fast)
4341 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4343 // Count how many bytes are to be pushed on the stack, including the linkage
4344 // area, parameter list area and the part of the local variable space which
4345 // contains copies of aggregates which are passed by value.
4347 // Assign locations to all of the outgoing arguments.
4348 SmallVector<CCValAssign, 16> ArgLocs;
4349 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4352 // Reserve space for the linkage area on the stack.
4353 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4357 // Handle fixed and variable vector arguments differently.
4358 // Fixed vector arguments go into registers as long as registers are
4359 // available. Variable vector arguments always go into memory.
4360 unsigned NumArgs = Outs.size();
4362 for (unsigned i = 0; i != NumArgs; ++i) {
4363 MVT ArgVT = Outs[i].VT;
4364 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4367 if (Outs[i].IsFixed) {
4368 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4371 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4377 errs() << "Call operand #" << i << " has unhandled type "
4378 << EVT(ArgVT).getEVTString() << "\n";
4380 llvm_unreachable(nullptr);
4384 // All arguments are treated the same.
4385 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4388 // Assign locations to all of the outgoing aggregate by value arguments.
4389 SmallVector<CCValAssign, 16> ByValArgLocs;
4390 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4391 ByValArgLocs, *DAG.getContext());
4393 // Reserve stack space for the allocations in CCInfo.
4394 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4396 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4398 // Size of the linkage area, parameter list area and the part of the local
4399 // space variable where copies of aggregates which are passed by value are
4401 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4403 // Calculate by how many bytes the stack has to be adjusted in case of tail
4404 // call optimization.
4405 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4407 // Adjust the stack pointer for the new arguments...
4408 // These operations are automatically eliminated by the prolog/epilog pass
4409 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4411 SDValue CallSeqStart = Chain;
4413 // Load the return address and frame pointer so it can be moved somewhere else
4416 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4419 // Set up a copy of the stack pointer for use loading and storing any
4420 // arguments that may not fit in the registers available for argument
4422 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4424 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4425 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4426 SmallVector<SDValue, 8> MemOpChains;
4428 bool seenFloatArg = false;
4429 // Walk the register/memloc assignments, inserting copies/loads.
4430 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4433 CCValAssign &VA = ArgLocs[i];
4434 SDValue Arg = OutVals[i];
4435 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4437 if (Flags.isByVal()) {
4438 // Argument is an aggregate which is passed by value, thus we need to
4439 // create a copy of it in the local variable space of the current stack
4440 // frame (which is the stack frame of the caller) and pass the address of
4441 // this copy to the callee.
4442 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4443 CCValAssign &ByValVA = ByValArgLocs[j++];
4444 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4446 // Memory reserved in the local variable space of the callers stack frame.
4447 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4449 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4450 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4452 // Create a copy of the argument in the local area of the current
4454 SDValue MemcpyCall =
4455 CreateCopyOfByValArgument(Arg, PtrOff,
4456 CallSeqStart.getNode()->getOperand(0),
4459 // This must go outside the CALLSEQ_START..END.
4460 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4461 CallSeqStart.getNode()->getOperand(1),
4463 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4464 NewCallSeqStart.getNode());
4465 Chain = CallSeqStart = NewCallSeqStart;
4467 // Pass the address of the aggregate copy on the stack either in a
4468 // physical register or in the parameter list area of the current stack
4469 // frame to the callee.
4473 if (VA.isRegLoc()) {
4474 if (Arg.getValueType() == MVT::i1)
4475 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4477 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4478 // Put argument in a physical register.
4479 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4481 // Put argument in the parameter list area of the current stack frame.
4482 assert(VA.isMemLoc());
4483 unsigned LocMemOffset = VA.getLocMemOffset();
4486 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4487 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4489 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4490 MachinePointerInfo(),
4493 // Calculate and remember argument location.
4494 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4500 if (!MemOpChains.empty())
4501 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4503 // Build a sequence of copy-to-reg nodes chained together with token chain
4504 // and flag operands which copy the outgoing args into the appropriate regs.
4506 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4507 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4508 RegsToPass[i].second, InFlag);
4509 InFlag = Chain.getValue(1);
4512 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4515 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4516 SDValue Ops[] = { Chain, InFlag };
4518 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4519 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4521 InFlag = Chain.getValue(1);
4525 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4526 false, TailCallArguments);
4528 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4529 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4530 NumBytes, Ins, InVals, CS);
4533 // Copy an argument into memory, being careful to do this outside the
4534 // call sequence for the call to which the argument belongs.
4536 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4537 SDValue CallSeqStart,
4538 ISD::ArgFlagsTy Flags,
4541 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4542 CallSeqStart.getNode()->getOperand(0),
4544 // The MEMCPY must go outside the CALLSEQ_START..END.
4545 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4546 CallSeqStart.getNode()->getOperand(1),
4548 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4549 NewCallSeqStart.getNode());
4550 return NewCallSeqStart;
4554 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4555 CallingConv::ID CallConv, bool isVarArg,
4556 bool isTailCall, bool IsPatchPoint,
4557 const SmallVectorImpl<ISD::OutputArg> &Outs,
4558 const SmallVectorImpl<SDValue> &OutVals,
4559 const SmallVectorImpl<ISD::InputArg> &Ins,
4560 SDLoc dl, SelectionDAG &DAG,
4561 SmallVectorImpl<SDValue> &InVals,
4562 ImmutableCallSite *CS) const {
4564 bool isELFv2ABI = Subtarget.isELFv2ABI();
4565 bool isLittleEndian = Subtarget.isLittleEndian();
4566 unsigned NumOps = Outs.size();
4568 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4569 unsigned PtrByteSize = 8;
4571 MachineFunction &MF = DAG.getMachineFunction();
4573 // Mark this function as potentially containing a function that contains a
4574 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4575 // and restoring the callers stack pointer in this functions epilog. This is
4576 // done because by tail calling the called function might overwrite the value
4577 // in this function's (MF) stack pointer stack slot 0(SP).
4578 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4579 CallConv == CallingConv::Fast)
4580 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4582 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4583 "fastcc not supported on varargs functions");
4585 // Count how many bytes are to be pushed on the stack, including the linkage
4586 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4587 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4588 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4589 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4590 unsigned NumBytes = LinkageSize;
4591 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4592 unsigned &QFPR_idx = FPR_idx;
4594 static const MCPhysReg GPR[] = {
4595 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4596 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4598 static const MCPhysReg VR[] = {
4599 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4600 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4602 static const MCPhysReg VSRH[] = {
4603 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4604 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4607 const unsigned NumGPRs = array_lengthof(GPR);
4608 const unsigned NumFPRs = 13;
4609 const unsigned NumVRs = array_lengthof(VR);
4610 const unsigned NumQFPRs = NumFPRs;
4612 // When using the fast calling convention, we don't provide backing for
4613 // arguments that will be in registers.
4614 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4616 // Add up all the space actually used.
4617 for (unsigned i = 0; i != NumOps; ++i) {
4618 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4619 EVT ArgVT = Outs[i].VT;
4620 EVT OrigVT = Outs[i].ArgVT;
4622 if (CallConv == CallingConv::Fast) {
4623 if (Flags.isByVal())
4624 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4626 switch (ArgVT.getSimpleVT().SimpleTy) {
4627 default: llvm_unreachable("Unexpected ValueType for argument!");
4631 if (++NumGPRsUsed <= NumGPRs)
4640 if (++NumVRsUsed <= NumVRs)
4644 // When using QPX, this is handled like a FP register, otherwise, it
4645 // is an Altivec register.
4646 if (Subtarget.hasQPX()) {
4647 if (++NumFPRsUsed <= NumFPRs)
4650 if (++NumVRsUsed <= NumVRs)
4656 case MVT::v4f64: // QPX
4657 case MVT::v4i1: // QPX
4658 if (++NumFPRsUsed <= NumFPRs)
4664 /* Respect alignment of argument on the stack. */
4666 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4667 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4669 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4670 if (Flags.isInConsecutiveRegsLast())
4671 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4674 unsigned NumBytesActuallyUsed = NumBytes;
4676 // The prolog code of the callee may store up to 8 GPR argument registers to
4677 // the stack, allowing va_start to index over them in memory if its varargs.
4678 // Because we cannot tell if this is needed on the caller side, we have to
4679 // conservatively assume that it is needed. As such, make sure we have at
4680 // least enough stack space for the caller to store the 8 GPRs.
4681 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4682 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4684 // Tail call needs the stack to be aligned.
4685 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4686 CallConv == CallingConv::Fast)
4687 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4689 // Calculate by how many bytes the stack has to be adjusted in case of tail
4690 // call optimization.
4691 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4693 // To protect arguments on the stack from being clobbered in a tail call,
4694 // force all the loads to happen before doing any other lowering.
4696 Chain = DAG.getStackArgumentTokenFactor(Chain);
4698 // Adjust the stack pointer for the new arguments...
4699 // These operations are automatically eliminated by the prolog/epilog pass
4700 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4702 SDValue CallSeqStart = Chain;
4704 // Load the return address and frame pointer so it can be move somewhere else
4707 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4710 // Set up a copy of the stack pointer for use loading and storing any
4711 // arguments that may not fit in the registers available for argument
4713 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4715 // Figure out which arguments are going to go in registers, and which in
4716 // memory. Also, if this is a vararg function, floating point operations
4717 // must be stored to our stack, and loaded into integer regs as well, if
4718 // any integer regs are available for argument passing.
4719 unsigned ArgOffset = LinkageSize;
4721 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4722 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4724 SmallVector<SDValue, 8> MemOpChains;
4725 for (unsigned i = 0; i != NumOps; ++i) {
4726 SDValue Arg = OutVals[i];
4727 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4728 EVT ArgVT = Outs[i].VT;
4729 EVT OrigVT = Outs[i].ArgVT;
4731 // PtrOff will be used to store the current argument to the stack if a
4732 // register cannot be found for it.
4735 // We re-align the argument offset for each argument, except when using the
4736 // fast calling convention, when we need to make sure we do that only when
4737 // we'll actually use a stack slot.
4738 auto ComputePtrOff = [&]() {
4739 /* Respect alignment of argument on the stack. */
4741 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4742 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4744 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4746 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4749 if (CallConv != CallingConv::Fast) {
4752 /* Compute GPR index associated with argument offset. */
4753 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4754 GPR_idx = std::min(GPR_idx, NumGPRs);
4757 // Promote integers to 64-bit values.
4758 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4759 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4760 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4761 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4764 // FIXME memcpy is used way more than necessary. Correctness first.
4765 // Note: "by value" is code for passing a structure by value, not
4767 if (Flags.isByVal()) {
4768 // Note: Size includes alignment padding, so
4769 // struct x { short a; char b; }
4770 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4771 // These are the proper values we need for right-justifying the
4772 // aggregate in a parameter register.
4773 unsigned Size = Flags.getByValSize();
4775 // An empty aggregate parameter takes up no storage and no
4780 if (CallConv == CallingConv::Fast)
4783 // All aggregates smaller than 8 bytes must be passed right-justified.
4784 if (Size==1 || Size==2 || Size==4) {
4785 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4786 if (GPR_idx != NumGPRs) {
4787 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4788 MachinePointerInfo(), VT,
4789 false, false, false, 0);
4790 MemOpChains.push_back(Load.getValue(1));
4791 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4793 ArgOffset += PtrByteSize;
4798 if (GPR_idx == NumGPRs && Size < 8) {
4799 SDValue AddPtr = PtrOff;
4800 if (!isLittleEndian) {
4801 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4802 PtrOff.getValueType());
4803 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4805 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4808 ArgOffset += PtrByteSize;
4811 // Copy entire object into memory. There are cases where gcc-generated
4812 // code assumes it is there, even if it could be put entirely into
4813 // registers. (This is not what the doc says.)
4815 // FIXME: The above statement is likely due to a misunderstanding of the
4816 // documents. All arguments must be copied into the parameter area BY
4817 // THE CALLEE in the event that the callee takes the address of any
4818 // formal argument. That has not yet been implemented. However, it is
4819 // reasonable to use the stack area as a staging area for the register
4822 // Skip this for small aggregates, as we will use the same slot for a
4823 // right-justified copy, below.
4825 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4829 // When a register is available, pass a small aggregate right-justified.
4830 if (Size < 8 && GPR_idx != NumGPRs) {
4831 // The easiest way to get this right-justified in a register
4832 // is to copy the structure into the rightmost portion of a
4833 // local variable slot, then load the whole slot into the
4835 // FIXME: The memcpy seems to produce pretty awful code for
4836 // small aggregates, particularly for packed ones.
4837 // FIXME: It would be preferable to use the slot in the
4838 // parameter save area instead of a new local variable.
4839 SDValue AddPtr = PtrOff;
4840 if (!isLittleEndian) {
4841 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
4842 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4844 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4848 // Load the slot into the register.
4849 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4850 MachinePointerInfo(),
4851 false, false, false, 0);
4852 MemOpChains.push_back(Load.getValue(1));
4853 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4855 // Done with this argument.
4856 ArgOffset += PtrByteSize;
4860 // For aggregates larger than PtrByteSize, copy the pieces of the
4861 // object that fit into registers from the parameter save area.
4862 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4863 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
4864 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4865 if (GPR_idx != NumGPRs) {
4866 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4867 MachinePointerInfo(),
4868 false, false, false, 0);
4869 MemOpChains.push_back(Load.getValue(1));
4870 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4871 ArgOffset += PtrByteSize;
4873 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4880 switch (Arg.getSimpleValueType().SimpleTy) {
4881 default: llvm_unreachable("Unexpected ValueType for argument!");
4885 // These can be scalar arguments or elements of an integer array type
4886 // passed directly. Clang may use those instead of "byval" aggregate
4887 // types to avoid forcing arguments to memory unnecessarily.
4888 if (GPR_idx != NumGPRs) {
4889 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4891 if (CallConv == CallingConv::Fast)
4894 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4895 true, isTailCall, false, MemOpChains,
4896 TailCallArguments, dl);
4897 if (CallConv == CallingConv::Fast)
4898 ArgOffset += PtrByteSize;
4900 if (CallConv != CallingConv::Fast)
4901 ArgOffset += PtrByteSize;
4905 // These can be scalar arguments or elements of a float array type
4906 // passed directly. The latter are used to implement ELFv2 homogenous
4907 // float aggregates.
4909 // Named arguments go into FPRs first, and once they overflow, the
4910 // remaining arguments go into GPRs and then the parameter save area.
4911 // Unnamed arguments for vararg functions always go to GPRs and
4912 // then the parameter save area. For now, put all arguments to vararg
4913 // routines always in both locations (FPR *and* GPR or stack slot).
4914 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4915 bool NeededLoad = false;
4917 // First load the argument into the next available FPR.
4918 if (FPR_idx != NumFPRs)
4919 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4921 // Next, load the argument into GPR or stack slot if needed.
4922 if (!NeedGPROrStack)
4924 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4925 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4926 // once we support fp <-> gpr moves.
4928 // In the non-vararg case, this can only ever happen in the
4929 // presence of f32 array types, since otherwise we never run
4930 // out of FPRs before running out of GPRs.
4933 // Double values are always passed in a single GPR.
4934 if (Arg.getValueType() != MVT::f32) {
4935 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4937 // Non-array float values are extended and passed in a GPR.
4938 } else if (!Flags.isInConsecutiveRegs()) {
4939 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4940 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4942 // If we have an array of floats, we collect every odd element
4943 // together with its predecessor into one GPR.
4944 } else if (ArgOffset % PtrByteSize != 0) {
4946 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4947 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4948 if (!isLittleEndian)
4950 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4952 // The final element, if even, goes into the first half of a GPR.
4953 } else if (Flags.isInConsecutiveRegsLast()) {
4954 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4955 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4956 if (!isLittleEndian)
4957 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4958 DAG.getConstant(32, dl, MVT::i32));
4960 // Non-final even elements are skipped; they will be handled
4961 // together the with subsequent argument on the next go-around.
4965 if (ArgVal.getNode())
4966 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4968 if (CallConv == CallingConv::Fast)
4971 // Single-precision floating-point values are mapped to the
4972 // second (rightmost) word of the stack doubleword.
4973 if (Arg.getValueType() == MVT::f32 &&
4974 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4975 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
4976 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4979 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4980 true, isTailCall, false, MemOpChains,
4981 TailCallArguments, dl);
4985 // When passing an array of floats, the array occupies consecutive
4986 // space in the argument area; only round up to the next doubleword
4987 // at the end of the array. Otherwise, each float takes 8 bytes.
4988 if (CallConv != CallingConv::Fast || NeededLoad) {
4989 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4990 Flags.isInConsecutiveRegs()) ? 4 : 8;
4991 if (Flags.isInConsecutiveRegsLast())
4992 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5003 if (!Subtarget.hasQPX()) {
5004 // These can be scalar arguments or elements of a vector array type
5005 // passed directly. The latter are used to implement ELFv2 homogenous
5006 // vector aggregates.
5008 // For a varargs call, named arguments go into VRs or on the stack as
5009 // usual; unnamed arguments always go to the stack or the corresponding
5010 // GPRs when within range. For now, we always put the value in both
5011 // locations (or even all three).
5013 // We could elide this store in the case where the object fits
5014 // entirely in R registers. Maybe later.
5015 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5016 MachinePointerInfo(), false, false, 0);
5017 MemOpChains.push_back(Store);
5018 if (VR_idx != NumVRs) {
5019 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5020 MachinePointerInfo(),
5021 false, false, false, 0);
5022 MemOpChains.push_back(Load.getValue(1));
5024 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5025 Arg.getSimpleValueType() == MVT::v2i64) ?
5026 VSRH[VR_idx] : VR[VR_idx];
5029 RegsToPass.push_back(std::make_pair(VReg, Load));
5032 for (unsigned i=0; i<16; i+=PtrByteSize) {
5033 if (GPR_idx == NumGPRs)
5035 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5036 DAG.getConstant(i, dl, PtrVT));
5037 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5038 false, false, false, 0);
5039 MemOpChains.push_back(Load.getValue(1));
5040 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5045 // Non-varargs Altivec params go into VRs or on the stack.
5046 if (VR_idx != NumVRs) {
5047 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5048 Arg.getSimpleValueType() == MVT::v2i64) ?
5049 VSRH[VR_idx] : VR[VR_idx];
5052 RegsToPass.push_back(std::make_pair(VReg, Arg));
5054 if (CallConv == CallingConv::Fast)
5057 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5058 true, isTailCall, true, MemOpChains,
5059 TailCallArguments, dl);
5060 if (CallConv == CallingConv::Fast)
5064 if (CallConv != CallingConv::Fast)
5069 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5070 "Invalid QPX parameter type");
5075 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5077 // We could elide this store in the case where the object fits
5078 // entirely in R registers. Maybe later.
5079 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5080 MachinePointerInfo(), false, false, 0);
5081 MemOpChains.push_back(Store);
5082 if (QFPR_idx != NumQFPRs) {
5083 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5084 Store, PtrOff, MachinePointerInfo(),
5085 false, false, false, 0);
5086 MemOpChains.push_back(Load.getValue(1));
5087 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5089 ArgOffset += (IsF32 ? 16 : 32);
5090 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5091 if (GPR_idx == NumGPRs)
5093 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5094 DAG.getConstant(i, dl, PtrVT));
5095 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5096 false, false, false, 0);
5097 MemOpChains.push_back(Load.getValue(1));
5098 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5103 // Non-varargs QPX params go into registers or on the stack.
5104 if (QFPR_idx != NumQFPRs) {
5105 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5107 if (CallConv == CallingConv::Fast)
5110 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5111 true, isTailCall, true, MemOpChains,
5112 TailCallArguments, dl);
5113 if (CallConv == CallingConv::Fast)
5114 ArgOffset += (IsF32 ? 16 : 32);
5117 if (CallConv != CallingConv::Fast)
5118 ArgOffset += (IsF32 ? 16 : 32);
5124 assert(NumBytesActuallyUsed == ArgOffset);
5125 (void)NumBytesActuallyUsed;
5127 if (!MemOpChains.empty())
5128 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5130 // Check if this is an indirect call (MTCTR/BCTRL).
5131 // See PrepareCall() for more information about calls through function
5132 // pointers in the 64-bit SVR4 ABI.
5133 if (!isTailCall && !IsPatchPoint &&
5134 !isFunctionGlobalAddress(Callee) &&
5135 !isa<ExternalSymbolSDNode>(Callee)) {
5136 // Load r2 into a virtual register and store it to the TOC save area.
5137 setUsesTOCBasePtr(DAG);
5138 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5139 // TOC save area offset.
5140 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5141 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5142 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5143 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5144 MachinePointerInfo::getStack(TOCSaveOffset),
5146 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5147 // This does not mean the MTCTR instruction must use R12; it's easier
5148 // to model this as an extra parameter, so do that.
5149 if (isELFv2ABI && !IsPatchPoint)
5150 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5153 // Build a sequence of copy-to-reg nodes chained together with token chain
5154 // and flag operands which copy the outgoing args into the appropriate regs.
5156 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5157 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5158 RegsToPass[i].second, InFlag);
5159 InFlag = Chain.getValue(1);
5163 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5164 FPOp, true, TailCallArguments);
5166 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5167 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5168 NumBytes, Ins, InVals, CS);
5172 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5173 CallingConv::ID CallConv, bool isVarArg,
5174 bool isTailCall, bool IsPatchPoint,
5175 const SmallVectorImpl<ISD::OutputArg> &Outs,
5176 const SmallVectorImpl<SDValue> &OutVals,
5177 const SmallVectorImpl<ISD::InputArg> &Ins,
5178 SDLoc dl, SelectionDAG &DAG,
5179 SmallVectorImpl<SDValue> &InVals,
5180 ImmutableCallSite *CS) const {
5182 unsigned NumOps = Outs.size();
5184 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5185 bool isPPC64 = PtrVT == MVT::i64;
5186 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5188 MachineFunction &MF = DAG.getMachineFunction();
5190 // Mark this function as potentially containing a function that contains a
5191 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5192 // and restoring the callers stack pointer in this functions epilog. This is
5193 // done because by tail calling the called function might overwrite the value
5194 // in this function's (MF) stack pointer stack slot 0(SP).
5195 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5196 CallConv == CallingConv::Fast)
5197 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5199 // Count how many bytes are to be pushed on the stack, including the linkage
5200 // area, and parameter passing area. We start with 24/48 bytes, which is
5201 // prereserved space for [SP][CR][LR][3 x unused].
5202 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5203 unsigned NumBytes = LinkageSize;
5205 // Add up all the space actually used.
5206 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5207 // they all go in registers, but we must reserve stack space for them for
5208 // possible use by the caller. In varargs or 64-bit calls, parameters are
5209 // assigned stack space in order, with padding so Altivec parameters are
5211 unsigned nAltivecParamsAtEnd = 0;
5212 for (unsigned i = 0; i != NumOps; ++i) {
5213 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5214 EVT ArgVT = Outs[i].VT;
5215 // Varargs Altivec parameters are padded to a 16 byte boundary.
5216 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5217 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5218 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5219 if (!isVarArg && !isPPC64) {
5220 // Non-varargs Altivec parameters go after all the non-Altivec
5221 // parameters; handle those later so we know how much padding we need.
5222 nAltivecParamsAtEnd++;
5225 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5226 NumBytes = ((NumBytes+15)/16)*16;
5228 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5231 // Allow for Altivec parameters at the end, if needed.
5232 if (nAltivecParamsAtEnd) {
5233 NumBytes = ((NumBytes+15)/16)*16;
5234 NumBytes += 16*nAltivecParamsAtEnd;
5237 // The prolog code of the callee may store up to 8 GPR argument registers to
5238 // the stack, allowing va_start to index over them in memory if its varargs.
5239 // Because we cannot tell if this is needed on the caller side, we have to
5240 // conservatively assume that it is needed. As such, make sure we have at
5241 // least enough stack space for the caller to store the 8 GPRs.
5242 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5244 // Tail call needs the stack to be aligned.
5245 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5246 CallConv == CallingConv::Fast)
5247 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5249 // Calculate by how many bytes the stack has to be adjusted in case of tail
5250 // call optimization.
5251 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5253 // To protect arguments on the stack from being clobbered in a tail call,
5254 // force all the loads to happen before doing any other lowering.
5256 Chain = DAG.getStackArgumentTokenFactor(Chain);
5258 // Adjust the stack pointer for the new arguments...
5259 // These operations are automatically eliminated by the prolog/epilog pass
5260 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5262 SDValue CallSeqStart = Chain;
5264 // Load the return address and frame pointer so it can be move somewhere else
5267 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5270 // Set up a copy of the stack pointer for use loading and storing any
5271 // arguments that may not fit in the registers available for argument
5275 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5277 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5279 // Figure out which arguments are going to go in registers, and which in
5280 // memory. Also, if this is a vararg function, floating point operations
5281 // must be stored to our stack, and loaded into integer regs as well, if
5282 // any integer regs are available for argument passing.
5283 unsigned ArgOffset = LinkageSize;
5284 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5286 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5287 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5288 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5290 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5291 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5292 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5294 static const MCPhysReg VR[] = {
5295 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5296 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5298 const unsigned NumGPRs = array_lengthof(GPR_32);
5299 const unsigned NumFPRs = 13;
5300 const unsigned NumVRs = array_lengthof(VR);
5302 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5304 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5305 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5307 SmallVector<SDValue, 8> MemOpChains;
5308 for (unsigned i = 0; i != NumOps; ++i) {
5309 SDValue Arg = OutVals[i];
5310 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5312 // PtrOff will be used to store the current argument to the stack if a
5313 // register cannot be found for it.
5316 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5318 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5320 // On PPC64, promote integers to 64-bit values.
5321 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5322 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5323 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5324 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5327 // FIXME memcpy is used way more than necessary. Correctness first.
5328 // Note: "by value" is code for passing a structure by value, not
5330 if (Flags.isByVal()) {
5331 unsigned Size = Flags.getByValSize();
5332 // Very small objects are passed right-justified. Everything else is
5333 // passed left-justified.
5334 if (Size==1 || Size==2) {
5335 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5336 if (GPR_idx != NumGPRs) {
5337 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5338 MachinePointerInfo(), VT,
5339 false, false, false, 0);
5340 MemOpChains.push_back(Load.getValue(1));
5341 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5343 ArgOffset += PtrByteSize;
5345 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5346 PtrOff.getValueType());
5347 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5348 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5351 ArgOffset += PtrByteSize;
5355 // Copy entire object into memory. There are cases where gcc-generated
5356 // code assumes it is there, even if it could be put entirely into
5357 // registers. (This is not what the doc says.)
5358 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5362 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5363 // copy the pieces of the object that fit into registers from the
5364 // parameter save area.
5365 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5366 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5367 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5368 if (GPR_idx != NumGPRs) {
5369 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5370 MachinePointerInfo(),
5371 false, false, false, 0);
5372 MemOpChains.push_back(Load.getValue(1));
5373 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5374 ArgOffset += PtrByteSize;
5376 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5383 switch (Arg.getSimpleValueType().SimpleTy) {
5384 default: llvm_unreachable("Unexpected ValueType for argument!");
5388 if (GPR_idx != NumGPRs) {
5389 if (Arg.getValueType() == MVT::i1)
5390 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5392 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5394 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5395 isPPC64, isTailCall, false, MemOpChains,
5396 TailCallArguments, dl);
5398 ArgOffset += PtrByteSize;
5402 if (FPR_idx != NumFPRs) {
5403 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5406 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5407 MachinePointerInfo(), false, false, 0);
5408 MemOpChains.push_back(Store);
5410 // Float varargs are always shadowed in available integer registers
5411 if (GPR_idx != NumGPRs) {
5412 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5413 MachinePointerInfo(), false, false,
5415 MemOpChains.push_back(Load.getValue(1));
5416 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5418 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5419 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5420 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5421 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5422 MachinePointerInfo(),
5423 false, false, false, 0);
5424 MemOpChains.push_back(Load.getValue(1));
5425 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5428 // If we have any FPRs remaining, we may also have GPRs remaining.
5429 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5431 if (GPR_idx != NumGPRs)
5433 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5434 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5438 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5439 isPPC64, isTailCall, false, MemOpChains,
5440 TailCallArguments, dl);
5444 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5451 // These go aligned on the stack, or in the corresponding R registers
5452 // when within range. The Darwin PPC ABI doc claims they also go in
5453 // V registers; in fact gcc does this only for arguments that are
5454 // prototyped, not for those that match the ... We do it for all
5455 // arguments, seems to work.
5456 while (ArgOffset % 16 !=0) {
5457 ArgOffset += PtrByteSize;
5458 if (GPR_idx != NumGPRs)
5461 // We could elide this store in the case where the object fits
5462 // entirely in R registers. Maybe later.
5463 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5464 DAG.getConstant(ArgOffset, dl, PtrVT));
5465 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5466 MachinePointerInfo(), false, false, 0);
5467 MemOpChains.push_back(Store);
5468 if (VR_idx != NumVRs) {
5469 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5470 MachinePointerInfo(),
5471 false, false, false, 0);
5472 MemOpChains.push_back(Load.getValue(1));
5473 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5476 for (unsigned i=0; i<16; i+=PtrByteSize) {
5477 if (GPR_idx == NumGPRs)
5479 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5480 DAG.getConstant(i, dl, PtrVT));
5481 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5482 false, false, false, 0);
5483 MemOpChains.push_back(Load.getValue(1));
5484 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5489 // Non-varargs Altivec params generally go in registers, but have
5490 // stack space allocated at the end.
5491 if (VR_idx != NumVRs) {
5492 // Doesn't have GPR space allocated.
5493 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5494 } else if (nAltivecParamsAtEnd==0) {
5495 // We are emitting Altivec params in order.
5496 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5497 isPPC64, isTailCall, true, MemOpChains,
5498 TailCallArguments, dl);
5504 // If all Altivec parameters fit in registers, as they usually do,
5505 // they get stack space following the non-Altivec parameters. We
5506 // don't track this here because nobody below needs it.
5507 // If there are more Altivec parameters than fit in registers emit
5509 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5511 // Offset is aligned; skip 1st 12 params which go in V registers.
5512 ArgOffset = ((ArgOffset+15)/16)*16;
5514 for (unsigned i = 0; i != NumOps; ++i) {
5515 SDValue Arg = OutVals[i];
5516 EVT ArgType = Outs[i].VT;
5517 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5518 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5521 // We are emitting Altivec params in order.
5522 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5523 isPPC64, isTailCall, true, MemOpChains,
5524 TailCallArguments, dl);
5531 if (!MemOpChains.empty())
5532 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5534 // On Darwin, R12 must contain the address of an indirect callee. This does
5535 // not mean the MTCTR instruction must use R12; it's easier to model this as
5536 // an extra parameter, so do that.
5538 !isFunctionGlobalAddress(Callee) &&
5539 !isa<ExternalSymbolSDNode>(Callee) &&
5540 !isBLACompatibleAddress(Callee, DAG))
5541 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5542 PPC::R12), Callee));
5544 // Build a sequence of copy-to-reg nodes chained together with token chain
5545 // and flag operands which copy the outgoing args into the appropriate regs.
5547 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5548 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5549 RegsToPass[i].second, InFlag);
5550 InFlag = Chain.getValue(1);
5554 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5555 FPOp, true, TailCallArguments);
5557 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5558 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5559 NumBytes, Ins, InVals, CS);
5563 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5564 MachineFunction &MF, bool isVarArg,
5565 const SmallVectorImpl<ISD::OutputArg> &Outs,
5566 LLVMContext &Context) const {
5567 SmallVector<CCValAssign, 16> RVLocs;
5568 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5569 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5573 PPCTargetLowering::LowerReturn(SDValue Chain,
5574 CallingConv::ID CallConv, bool isVarArg,
5575 const SmallVectorImpl<ISD::OutputArg> &Outs,
5576 const SmallVectorImpl<SDValue> &OutVals,
5577 SDLoc dl, SelectionDAG &DAG) const {
5579 SmallVector<CCValAssign, 16> RVLocs;
5580 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5582 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5585 SmallVector<SDValue, 4> RetOps(1, Chain);
5587 // Copy the result values into the output registers.
5588 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5589 CCValAssign &VA = RVLocs[i];
5590 assert(VA.isRegLoc() && "Can only return in registers!");
5592 SDValue Arg = OutVals[i];
5594 switch (VA.getLocInfo()) {
5595 default: llvm_unreachable("Unknown loc info!");
5596 case CCValAssign::Full: break;
5597 case CCValAssign::AExt:
5598 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5600 case CCValAssign::ZExt:
5601 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5603 case CCValAssign::SExt:
5604 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5608 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5609 Flag = Chain.getValue(1);
5610 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5613 RetOps[0] = Chain; // Update chain.
5615 // Add the flag if we have it.
5617 RetOps.push_back(Flag);
5619 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5622 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5623 const PPCSubtarget &Subtarget) const {
5624 // When we pop the dynamic allocation we need to restore the SP link.
5627 // Get the corect type for pointers.
5628 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5630 // Construct the stack pointer operand.
5631 bool isPPC64 = Subtarget.isPPC64();
5632 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5633 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5635 // Get the operands for the STACKRESTORE.
5636 SDValue Chain = Op.getOperand(0);
5637 SDValue SaveSP = Op.getOperand(1);
5639 // Load the old link SP.
5640 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5641 MachinePointerInfo(),
5642 false, false, false, 0);
5644 // Restore the stack pointer.
5645 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5647 // Store the old link SP.
5648 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5655 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5656 MachineFunction &MF = DAG.getMachineFunction();
5657 bool isPPC64 = Subtarget.isPPC64();
5658 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5660 // Get current frame pointer save index. The users of this index will be
5661 // primarily DYNALLOC instructions.
5662 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5663 int RASI = FI->getReturnAddrSaveIndex();
5665 // If the frame pointer save index hasn't been defined yet.
5667 // Find out what the fix offset of the frame pointer save area.
5668 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5669 // Allocate the frame index for frame pointer save area.
5670 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5672 FI->setReturnAddrSaveIndex(RASI);
5674 return DAG.getFrameIndex(RASI, PtrVT);
5678 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5679 MachineFunction &MF = DAG.getMachineFunction();
5680 bool isPPC64 = Subtarget.isPPC64();
5681 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5683 // Get current frame pointer save index. The users of this index will be
5684 // primarily DYNALLOC instructions.
5685 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5686 int FPSI = FI->getFramePointerSaveIndex();
5688 // If the frame pointer save index hasn't been defined yet.
5690 // Find out what the fix offset of the frame pointer save area.
5691 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5692 // Allocate the frame index for frame pointer save area.
5693 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5695 FI->setFramePointerSaveIndex(FPSI);
5697 return DAG.getFrameIndex(FPSI, PtrVT);
5700 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5702 const PPCSubtarget &Subtarget) const {
5704 SDValue Chain = Op.getOperand(0);
5705 SDValue Size = Op.getOperand(1);
5708 // Get the corect type for pointers.
5709 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5711 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5712 DAG.getConstant(0, dl, PtrVT), Size);
5713 // Construct a node for the frame pointer save index.
5714 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5715 // Build a DYNALLOC node.
5716 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5717 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5718 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5721 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5722 SelectionDAG &DAG) const {
5724 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5725 DAG.getVTList(MVT::i32, MVT::Other),
5726 Op.getOperand(0), Op.getOperand(1));
5729 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5730 SelectionDAG &DAG) const {
5732 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5733 Op.getOperand(0), Op.getOperand(1));
5736 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5737 if (Op.getValueType().isVector())
5738 return LowerVectorLoad(Op, DAG);
5740 assert(Op.getValueType() == MVT::i1 &&
5741 "Custom lowering only for i1 loads");
5743 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5746 LoadSDNode *LD = cast<LoadSDNode>(Op);
5748 SDValue Chain = LD->getChain();
5749 SDValue BasePtr = LD->getBasePtr();
5750 MachineMemOperand *MMO = LD->getMemOperand();
5752 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5753 BasePtr, MVT::i8, MMO);
5754 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5756 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5757 return DAG.getMergeValues(Ops, dl);
5760 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5761 if (Op.getOperand(1).getValueType().isVector())
5762 return LowerVectorStore(Op, DAG);
5764 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5765 "Custom lowering only for i1 stores");
5767 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5770 StoreSDNode *ST = cast<StoreSDNode>(Op);
5772 SDValue Chain = ST->getChain();
5773 SDValue BasePtr = ST->getBasePtr();
5774 SDValue Value = ST->getValue();
5775 MachineMemOperand *MMO = ST->getMemOperand();
5777 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5778 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5781 // FIXME: Remove this once the ANDI glue bug is fixed:
5782 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5783 assert(Op.getValueType() == MVT::i1 &&
5784 "Custom lowering only for i1 results");
5787 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5791 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5793 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5794 // Not FP? Not a fsel.
5795 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5796 !Op.getOperand(2).getValueType().isFloatingPoint())
5799 // We might be able to do better than this under some circumstances, but in
5800 // general, fsel-based lowering of select is a finite-math-only optimization.
5801 // For more information, see section F.3 of the 2.06 ISA specification.
5802 if (!DAG.getTarget().Options.NoInfsFPMath ||
5803 !DAG.getTarget().Options.NoNaNsFPMath)
5806 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5808 EVT ResVT = Op.getValueType();
5809 EVT CmpVT = Op.getOperand(0).getValueType();
5810 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5811 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5814 // If the RHS of the comparison is a 0.0, we don't need to do the
5815 // subtraction at all.
5817 if (isFloatingPointZero(RHS))
5819 default: break; // SETUO etc aren't handled by fsel.
5823 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5824 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5825 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5826 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5827 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5828 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5829 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5832 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5835 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5836 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5837 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5840 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5843 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5844 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5845 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5846 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5851 default: break; // SETUO etc aren't handled by fsel.
5855 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5856 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5857 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5858 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5859 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5860 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5861 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5862 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5865 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5866 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5867 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5868 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5871 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5872 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5873 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5874 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5877 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5878 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5879 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5880 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5883 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5884 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5885 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5886 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5891 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5894 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5895 SDValue Src = Op.getOperand(0);
5896 if (Src.getValueType() == MVT::f32)
5897 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5900 switch (Op.getSimpleValueType().SimpleTy) {
5901 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5904 Op.getOpcode() == ISD::FP_TO_SINT
5906 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5910 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5911 "i64 FP_TO_UINT is supported only with FPCVT");
5912 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5918 // Convert the FP value to an int value through memory.
5919 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5920 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5921 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5922 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5923 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5925 // Emit a store to the stack slot.
5928 MachineFunction &MF = DAG.getMachineFunction();
5929 MachineMemOperand *MMO =
5930 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5931 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5932 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5933 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5935 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5936 MPI, false, false, 0);
5938 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5940 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5941 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5942 DAG.getConstant(4, dl, FIPtr.getValueType()));
5943 MPI = MPI.getWithOffset(4);
5951 /// \brief Custom lowers floating point to integer conversions to use
5952 /// the direct move instructions available in ISA 2.07 to avoid the
5953 /// need for load/store combinations.
5954 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
5957 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5958 SDValue Src = Op.getOperand(0);
5960 if (Src.getValueType() == MVT::f32)
5961 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5964 switch (Op.getSimpleValueType().SimpleTy) {
5965 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5968 Op.getOpcode() == ISD::FP_TO_SINT
5970 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5972 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
5975 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5976 "i64 FP_TO_UINT is supported only with FPCVT");
5977 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5980 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
5986 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5988 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
5989 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
5992 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5994 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5995 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5999 // We're trying to insert a regular store, S, and then a load, L. If the
6000 // incoming value, O, is a load, we might just be able to have our load use the
6001 // address used by O. However, we don't know if anything else will store to
6002 // that address before we can load from it. To prevent this situation, we need
6003 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6004 // the same chain operand as O, we create a token factor from the chain results
6005 // of O and L, and we replace all uses of O's chain result with that token
6006 // factor (see spliceIntoChain below for this last part).
6007 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6010 ISD::LoadExtType ET) const {
6012 if (ET == ISD::NON_EXTLOAD &&
6013 (Op.getOpcode() == ISD::FP_TO_UINT ||
6014 Op.getOpcode() == ISD::FP_TO_SINT) &&
6015 isOperationLegalOrCustom(Op.getOpcode(),
6016 Op.getOperand(0).getValueType())) {
6018 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6022 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6023 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6024 LD->isNonTemporal())
6026 if (LD->getMemoryVT() != MemVT)
6029 RLI.Ptr = LD->getBasePtr();
6030 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6031 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6032 "Non-pre-inc AM on PPC?");
6033 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6037 RLI.Chain = LD->getChain();
6038 RLI.MPI = LD->getPointerInfo();
6039 RLI.IsInvariant = LD->isInvariant();
6040 RLI.Alignment = LD->getAlignment();
6041 RLI.AAInfo = LD->getAAInfo();
6042 RLI.Ranges = LD->getRanges();
6044 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6048 // Given the head of the old chain, ResChain, insert a token factor containing
6049 // it and NewResChain, and make users of ResChain now be users of that token
6051 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6052 SDValue NewResChain,
6053 SelectionDAG &DAG) const {
6057 SDLoc dl(NewResChain);
6059 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6060 NewResChain, DAG.getUNDEF(MVT::Other));
6061 assert(TF.getNode() != NewResChain.getNode() &&
6062 "A new TF really is required here");
6064 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6065 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6068 /// \brief Custom lowers integer to floating point conversions to use
6069 /// the direct move instructions available in ISA 2.07 to avoid the
6070 /// need for load/store combinations.
6071 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6074 assert((Op.getValueType() == MVT::f32 ||
6075 Op.getValueType() == MVT::f64) &&
6076 "Invalid floating point type as target of conversion");
6077 assert(Subtarget.hasFPCVT() &&
6078 "Int to FP conversions with direct moves require FPCVT");
6080 SDValue Src = Op.getOperand(0);
6081 bool SinglePrec = Op.getValueType() == MVT::f32;
6082 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6083 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6084 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6085 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6088 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6090 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6093 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6094 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6100 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6101 SelectionDAG &DAG) const {
6104 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6105 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6108 SDValue Value = Op.getOperand(0);
6109 // The values are now known to be -1 (false) or 1 (true). To convert this
6110 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6111 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6112 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6114 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6115 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6116 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6118 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6120 if (Op.getValueType() != MVT::v4f64)
6121 Value = DAG.getNode(ISD::FP_ROUND, dl,
6122 Op.getValueType(), Value,
6123 DAG.getIntPtrConstant(1, dl));
6127 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6128 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6131 if (Op.getOperand(0).getValueType() == MVT::i1)
6132 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6133 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6134 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6136 // If we have direct moves, we can do all the conversion, skip the store/load
6137 // however, without FPCVT we can't do most conversions.
6138 if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6139 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6141 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6142 "UINT_TO_FP is supported only with FPCVT");
6144 // If we have FCFIDS, then use it when converting to single-precision.
6145 // Otherwise, convert to double-precision and then round.
6146 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6147 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6149 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6151 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6155 if (Op.getOperand(0).getValueType() == MVT::i64) {
6156 SDValue SINT = Op.getOperand(0);
6157 // When converting to single-precision, we actually need to convert
6158 // to double-precision first and then round to single-precision.
6159 // To avoid double-rounding effects during that operation, we have
6160 // to prepare the input operand. Bits that might be truncated when
6161 // converting to double-precision are replaced by a bit that won't
6162 // be lost at this stage, but is below the single-precision rounding
6165 // However, if -enable-unsafe-fp-math is in effect, accept double
6166 // rounding to avoid the extra overhead.
6167 if (Op.getValueType() == MVT::f32 &&
6168 !Subtarget.hasFPCVT() &&
6169 !DAG.getTarget().Options.UnsafeFPMath) {
6171 // Twiddle input to make sure the low 11 bits are zero. (If this
6172 // is the case, we are guaranteed the value will fit into the 53 bit
6173 // mantissa of an IEEE double-precision value without rounding.)
6174 // If any of those low 11 bits were not zero originally, make sure
6175 // bit 12 (value 2048) is set instead, so that the final rounding
6176 // to single-precision gets the correct result.
6177 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6178 SINT, DAG.getConstant(2047, dl, MVT::i64));
6179 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6180 Round, DAG.getConstant(2047, dl, MVT::i64));
6181 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6182 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6183 Round, DAG.getConstant(-2048, dl, MVT::i64));
6185 // However, we cannot use that value unconditionally: if the magnitude
6186 // of the input value is small, the bit-twiddling we did above might
6187 // end up visibly changing the output. Fortunately, in that case, we
6188 // don't need to twiddle bits since the original input will convert
6189 // exactly to double-precision floating-point already. Therefore,
6190 // construct a conditional to use the original value if the top 11
6191 // bits are all sign-bit copies, and use the rounded value computed
6193 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6194 SINT, DAG.getConstant(53, dl, MVT::i32));
6195 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6196 Cond, DAG.getConstant(1, dl, MVT::i64));
6197 Cond = DAG.getSetCC(dl, MVT::i32,
6198 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6200 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6206 MachineFunction &MF = DAG.getMachineFunction();
6207 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6208 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6209 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6211 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6212 } else if (Subtarget.hasLFIWAX() &&
6213 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6214 MachineMemOperand *MMO =
6215 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6216 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6217 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6218 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6219 DAG.getVTList(MVT::f64, MVT::Other),
6220 Ops, MVT::i32, MMO);
6221 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6222 } else if (Subtarget.hasFPCVT() &&
6223 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6224 MachineMemOperand *MMO =
6225 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6226 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6227 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6228 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6229 DAG.getVTList(MVT::f64, MVT::Other),
6230 Ops, MVT::i32, MMO);
6231 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6232 } else if (((Subtarget.hasLFIWAX() &&
6233 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6234 (Subtarget.hasFPCVT() &&
6235 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6236 SINT.getOperand(0).getValueType() == MVT::i32) {
6237 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6238 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6240 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6241 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6244 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6245 MachinePointerInfo::getFixedStack(FrameIdx),
6248 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6249 "Expected an i32 store");
6253 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6256 MachineMemOperand *MMO =
6257 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6258 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6259 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6260 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6261 PPCISD::LFIWZX : PPCISD::LFIWAX,
6262 dl, DAG.getVTList(MVT::f64, MVT::Other),
6263 Ops, MVT::i32, MMO);
6265 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6267 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6269 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6270 FP = DAG.getNode(ISD::FP_ROUND, dl,
6271 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6275 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6276 "Unhandled INT_TO_FP type in custom expander!");
6277 // Since we only generate this in 64-bit mode, we can take advantage of
6278 // 64-bit registers. In particular, sign extend the input value into the
6279 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6280 // then lfd it and fcfid it.
6281 MachineFunction &MF = DAG.getMachineFunction();
6282 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6283 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6286 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6289 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6291 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6292 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6294 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6295 MachinePointerInfo::getFixedStack(FrameIdx),
6298 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6299 "Expected an i32 store");
6303 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6307 MachineMemOperand *MMO =
6308 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6309 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6310 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6311 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6312 PPCISD::LFIWZX : PPCISD::LFIWAX,
6313 dl, DAG.getVTList(MVT::f64, MVT::Other),
6314 Ops, MVT::i32, MMO);
6316 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6318 assert(Subtarget.isPPC64() &&
6319 "i32->FP without LFIWAX supported only on PPC64");
6321 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6322 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6324 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6327 // STD the extended value into the stack slot.
6328 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6329 MachinePointerInfo::getFixedStack(FrameIdx),
6332 // Load the value as a double.
6333 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6334 MachinePointerInfo::getFixedStack(FrameIdx),
6335 false, false, false, 0);
6338 // FCFID it and return it.
6339 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6340 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6341 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6342 DAG.getIntPtrConstant(0, dl));
6346 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6347 SelectionDAG &DAG) const {
6350 The rounding mode is in bits 30:31 of FPSR, and has the following
6357 FLT_ROUNDS, on the other hand, expects the following:
6364 To perform the conversion, we do:
6365 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6368 MachineFunction &MF = DAG.getMachineFunction();
6369 EVT VT = Op.getValueType();
6370 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6372 // Save FP Control Word to register
6374 MVT::f64, // return register
6375 MVT::Glue // unused in this context
6377 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6379 // Save FP register to stack slot
6380 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6381 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6382 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6383 StackSlot, MachinePointerInfo(), false, false,0);
6385 // Load FP Control Word from low 32 bits of stack slot.
6386 SDValue Four = DAG.getConstant(4, dl, PtrVT);
6387 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6388 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6389 false, false, false, 0);
6391 // Transform as necessary
6393 DAG.getNode(ISD::AND, dl, MVT::i32,
6394 CWD, DAG.getConstant(3, dl, MVT::i32));
6396 DAG.getNode(ISD::SRL, dl, MVT::i32,
6397 DAG.getNode(ISD::AND, dl, MVT::i32,
6398 DAG.getNode(ISD::XOR, dl, MVT::i32,
6399 CWD, DAG.getConstant(3, dl, MVT::i32)),
6400 DAG.getConstant(3, dl, MVT::i32)),
6401 DAG.getConstant(1, dl, MVT::i32));
6404 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6406 return DAG.getNode((VT.getSizeInBits() < 16 ?
6407 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6410 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6411 EVT VT = Op.getValueType();
6412 unsigned BitWidth = VT.getSizeInBits();
6414 assert(Op.getNumOperands() == 3 &&
6415 VT == Op.getOperand(1).getValueType() &&
6418 // Expand into a bunch of logical ops. Note that these ops
6419 // depend on the PPC behavior for oversized shift amounts.
6420 SDValue Lo = Op.getOperand(0);
6421 SDValue Hi = Op.getOperand(1);
6422 SDValue Amt = Op.getOperand(2);
6423 EVT AmtVT = Amt.getValueType();
6425 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6426 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6427 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6428 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6429 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6430 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6431 DAG.getConstant(-BitWidth, dl, AmtVT));
6432 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6433 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6434 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6435 SDValue OutOps[] = { OutLo, OutHi };
6436 return DAG.getMergeValues(OutOps, dl);
6439 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6440 EVT VT = Op.getValueType();
6442 unsigned BitWidth = VT.getSizeInBits();
6443 assert(Op.getNumOperands() == 3 &&
6444 VT == Op.getOperand(1).getValueType() &&
6447 // Expand into a bunch of logical ops. Note that these ops
6448 // depend on the PPC behavior for oversized shift amounts.
6449 SDValue Lo = Op.getOperand(0);
6450 SDValue Hi = Op.getOperand(1);
6451 SDValue Amt = Op.getOperand(2);
6452 EVT AmtVT = Amt.getValueType();
6454 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6455 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6456 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6457 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6458 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6459 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6460 DAG.getConstant(-BitWidth, dl, AmtVT));
6461 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6462 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6463 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6464 SDValue OutOps[] = { OutLo, OutHi };
6465 return DAG.getMergeValues(OutOps, dl);
6468 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6470 EVT VT = Op.getValueType();
6471 unsigned BitWidth = VT.getSizeInBits();
6472 assert(Op.getNumOperands() == 3 &&
6473 VT == Op.getOperand(1).getValueType() &&
6476 // Expand into a bunch of logical ops, followed by a select_cc.
6477 SDValue Lo = Op.getOperand(0);
6478 SDValue Hi = Op.getOperand(1);
6479 SDValue Amt = Op.getOperand(2);
6480 EVT AmtVT = Amt.getValueType();
6482 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6483 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6484 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6485 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6486 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6487 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6488 DAG.getConstant(-BitWidth, dl, AmtVT));
6489 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6490 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6491 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6492 Tmp4, Tmp6, ISD::SETLE);
6493 SDValue OutOps[] = { OutLo, OutHi };
6494 return DAG.getMergeValues(OutOps, dl);
6497 //===----------------------------------------------------------------------===//
6498 // Vector related lowering.
6501 /// BuildSplatI - Build a canonical splati of Val with an element size of
6502 /// SplatSize. Cast the result to VT.
6503 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6504 SelectionDAG &DAG, SDLoc dl) {
6505 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6507 static const MVT VTys[] = { // canonical VT to use for each size.
6508 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6511 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6513 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6517 EVT CanonicalVT = VTys[SplatSize-1];
6519 // Build a canonical splat for this value.
6520 SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6521 SmallVector<SDValue, 8> Ops;
6522 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6523 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6524 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6527 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6528 /// specified intrinsic ID.
6529 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6530 SelectionDAG &DAG, SDLoc dl,
6531 EVT DestVT = MVT::Other) {
6532 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6533 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6534 DAG.getConstant(IID, dl, MVT::i32), Op);
6537 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6538 /// specified intrinsic ID.
6539 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6540 SelectionDAG &DAG, SDLoc dl,
6541 EVT DestVT = MVT::Other) {
6542 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6543 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6544 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6547 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6548 /// specified intrinsic ID.
6549 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6550 SDValue Op2, SelectionDAG &DAG,
6551 SDLoc dl, EVT DestVT = MVT::Other) {
6552 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6553 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6554 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6558 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6559 /// amount. The result has the specified value type.
6560 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6561 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6562 // Force LHS/RHS to be the right type.
6563 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6564 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6567 for (unsigned i = 0; i != 16; ++i)
6569 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6570 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6573 // If this is a case we can't handle, return null and let the default
6574 // expansion code take care of it. If we CAN select this case, and if it
6575 // selects to a single instruction, return Op. Otherwise, if we can codegen
6576 // this case more efficiently than a constant pool load, lower it to the
6577 // sequence of ops that should be used.
6578 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6579 SelectionDAG &DAG) const {
6581 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6582 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6584 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6585 // We first build an i32 vector, load it into a QPX register,
6586 // then convert it to a floating-point vector and compare it
6587 // to a zero vector to get the boolean result.
6588 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6589 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6590 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6591 EVT PtrVT = getPointerTy();
6592 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6594 assert(BVN->getNumOperands() == 4 &&
6595 "BUILD_VECTOR for v4i1 does not have 4 operands");
6597 bool IsConst = true;
6598 for (unsigned i = 0; i < 4; ++i) {
6599 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6600 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6608 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6610 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6612 SmallVector<Constant*, 4> CV(4, NegOne);
6613 for (unsigned i = 0; i < 4; ++i) {
6614 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6615 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6616 else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6617 getConstantIntValue()->isZero())
6623 Constant *CP = ConstantVector::get(CV);
6624 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6625 16 /* alignment */);
6627 SmallVector<SDValue, 2> Ops;
6628 Ops.push_back(DAG.getEntryNode());
6629 Ops.push_back(CPIdx);
6631 SmallVector<EVT, 2> ValueVTs;
6632 ValueVTs.push_back(MVT::v4i1);
6633 ValueVTs.push_back(MVT::Other); // chain
6634 SDVTList VTs = DAG.getVTList(ValueVTs);
6636 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6637 dl, VTs, Ops, MVT::v4f32,
6638 MachinePointerInfo::getConstantPool());
6641 SmallVector<SDValue, 4> Stores;
6642 for (unsigned i = 0; i < 4; ++i) {
6643 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6645 unsigned Offset = 4*i;
6646 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6647 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6649 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6650 if (StoreSize > 4) {
6651 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6652 BVN->getOperand(i), Idx,
6653 PtrInfo.getWithOffset(Offset),
6654 MVT::i32, false, false, 0));
6656 SDValue StoreValue = BVN->getOperand(i);
6658 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6660 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6662 PtrInfo.getWithOffset(Offset),
6668 if (!Stores.empty())
6669 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6671 StoreChain = DAG.getEntryNode();
6673 // Now load from v4i32 into the QPX register; this will extend it to
6674 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6675 // is typed as v4f64 because the QPX register integer states are not
6676 // explicitly represented.
6678 SmallVector<SDValue, 2> Ops;
6679 Ops.push_back(StoreChain);
6680 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6681 Ops.push_back(FIdx);
6683 SmallVector<EVT, 2> ValueVTs;
6684 ValueVTs.push_back(MVT::v4f64);
6685 ValueVTs.push_back(MVT::Other); // chain
6686 SDVTList VTs = DAG.getVTList(ValueVTs);
6688 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6689 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6690 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6691 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6694 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6695 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6696 FPZeros, FPZeros, FPZeros, FPZeros);
6698 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6701 // All other QPX vectors are handled by generic code.
6702 if (Subtarget.hasQPX())
6705 // Check if this is a splat of a constant value.
6706 APInt APSplatBits, APSplatUndef;
6707 unsigned SplatBitSize;
6709 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6710 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6714 unsigned SplatBits = APSplatBits.getZExtValue();
6715 unsigned SplatUndef = APSplatUndef.getZExtValue();
6716 unsigned SplatSize = SplatBitSize / 8;
6718 // First, handle single instruction cases.
6721 if (SplatBits == 0) {
6722 // Canonicalize all zero vectors to be v4i32.
6723 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6724 SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6725 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6726 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6731 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6732 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6734 if (SextVal >= -16 && SextVal <= 15)
6735 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6738 // Two instruction sequences.
6740 // If this value is in the range [-32,30] and is even, use:
6741 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6742 // If this value is in the range [17,31] and is odd, use:
6743 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6744 // If this value is in the range [-31,-17] and is odd, use:
6745 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6746 // Note the last two are three-instruction sequences.
6747 if (SextVal >= -32 && SextVal <= 31) {
6748 // To avoid having these optimizations undone by constant folding,
6749 // we convert to a pseudo that will be expanded later into one of
6751 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6752 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6753 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6754 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6755 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6756 if (VT == Op.getValueType())
6759 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6762 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6763 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6765 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6766 // Make -1 and vspltisw -1:
6767 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6769 // Make the VSLW intrinsic, computing 0x8000_0000.
6770 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6773 // xor by OnesV to invert it.
6774 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6775 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6778 // Check to see if this is a wide variety of vsplti*, binop self cases.
6779 static const signed char SplatCsts[] = {
6780 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6781 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6784 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6785 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6786 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6787 int i = SplatCsts[idx];
6789 // Figure out what shift amount will be used by altivec if shifted by i in
6791 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6793 // vsplti + shl self.
6794 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6795 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6796 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6797 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6798 Intrinsic::ppc_altivec_vslw
6800 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6801 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6804 // vsplti + srl self.
6805 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6806 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6807 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6808 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6809 Intrinsic::ppc_altivec_vsrw
6811 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6812 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6815 // vsplti + sra self.
6816 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6817 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6818 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6819 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6820 Intrinsic::ppc_altivec_vsraw
6822 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6823 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6826 // vsplti + rol self.
6827 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6828 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6829 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6830 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6831 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6832 Intrinsic::ppc_altivec_vrlw
6834 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6835 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6838 // t = vsplti c, result = vsldoi t, t, 1
6839 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6840 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6841 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6843 // t = vsplti c, result = vsldoi t, t, 2
6844 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6845 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6846 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6848 // t = vsplti c, result = vsldoi t, t, 3
6849 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6850 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6851 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6858 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6859 /// the specified operations to build the shuffle.
6860 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6861 SDValue RHS, SelectionDAG &DAG,
6863 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6864 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6865 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6868 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6880 if (OpNum == OP_COPY) {
6881 if (LHSID == (1*9+2)*9+3) return LHS;
6882 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6886 SDValue OpLHS, OpRHS;
6887 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6888 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6892 default: llvm_unreachable("Unknown i32 permute!");
6894 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6895 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6896 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6897 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6900 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6901 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6902 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6903 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6906 for (unsigned i = 0; i != 16; ++i)
6907 ShufIdxs[i] = (i&3)+0;
6910 for (unsigned i = 0; i != 16; ++i)
6911 ShufIdxs[i] = (i&3)+4;
6914 for (unsigned i = 0; i != 16; ++i)
6915 ShufIdxs[i] = (i&3)+8;
6918 for (unsigned i = 0; i != 16; ++i)
6919 ShufIdxs[i] = (i&3)+12;
6922 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6924 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6926 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6928 EVT VT = OpLHS.getValueType();
6929 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6930 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6931 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6932 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6935 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6936 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6937 /// return the code it can be lowered into. Worst case, it can always be
6938 /// lowered into a vperm.
6939 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6940 SelectionDAG &DAG) const {
6942 SDValue V1 = Op.getOperand(0);
6943 SDValue V2 = Op.getOperand(1);
6944 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6945 EVT VT = Op.getValueType();
6946 bool isLittleEndian = Subtarget.isLittleEndian();
6948 if (Subtarget.hasQPX()) {
6949 if (VT.getVectorNumElements() != 4)
6952 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6954 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6955 if (AlignIdx != -1) {
6956 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6957 DAG.getConstant(AlignIdx, dl, MVT::i32));
6958 } else if (SVOp->isSplat()) {
6959 int SplatIdx = SVOp->getSplatIndex();
6960 if (SplatIdx >= 4) {
6965 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6968 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6969 DAG.getConstant(SplatIdx, dl, MVT::i32));
6972 // Lower this into a qvgpci/qvfperm pair.
6974 // Compute the qvgpci literal
6976 for (unsigned i = 0; i < 4; ++i) {
6977 int m = SVOp->getMaskElt(i);
6978 unsigned mm = m >= 0 ? (unsigned) m : i;
6979 idx |= mm << (3-i)*3;
6982 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6983 DAG.getConstant(idx, dl, MVT::i32));
6984 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6987 // Cases that are handled by instructions that take permute immediates
6988 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6989 // selected by the instruction selector.
6990 if (V2.getOpcode() == ISD::UNDEF) {
6991 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6992 PPC::isSplatShuffleMask(SVOp, 2) ||
6993 PPC::isSplatShuffleMask(SVOp, 4) ||
6994 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6995 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6996 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6997 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6998 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6999 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7000 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7001 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7002 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
7007 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7008 // and produce a fixed permutation. If any of these match, do not lower to
7010 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7011 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7012 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7013 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7014 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7015 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7016 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7017 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7018 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7019 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
7022 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7023 // perfect shuffle table to emit an optimal matching sequence.
7024 ArrayRef<int> PermMask = SVOp->getMask();
7026 unsigned PFIndexes[4];
7027 bool isFourElementShuffle = true;
7028 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7029 unsigned EltNo = 8; // Start out undef.
7030 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7031 if (PermMask[i*4+j] < 0)
7032 continue; // Undef, ignore it.
7034 unsigned ByteSource = PermMask[i*4+j];
7035 if ((ByteSource & 3) != j) {
7036 isFourElementShuffle = false;
7041 EltNo = ByteSource/4;
7042 } else if (EltNo != ByteSource/4) {
7043 isFourElementShuffle = false;
7047 PFIndexes[i] = EltNo;
7050 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7051 // perfect shuffle vector to determine if it is cost effective to do this as
7052 // discrete instructions, or whether we should use a vperm.
7053 // For now, we skip this for little endian until such time as we have a
7054 // little-endian perfect shuffle table.
7055 if (isFourElementShuffle && !isLittleEndian) {
7056 // Compute the index in the perfect shuffle table.
7057 unsigned PFTableIndex =
7058 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7060 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7061 unsigned Cost = (PFEntry >> 30);
7063 // Determining when to avoid vperm is tricky. Many things affect the cost
7064 // of vperm, particularly how many times the perm mask needs to be computed.
7065 // For example, if the perm mask can be hoisted out of a loop or is already
7066 // used (perhaps because there are multiple permutes with the same shuffle
7067 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7068 // the loop requires an extra register.
7070 // As a compromise, we only emit discrete instructions if the shuffle can be
7071 // generated in 3 or fewer operations. When we have loop information
7072 // available, if this block is within a loop, we should avoid using vperm
7073 // for 3-operation perms and use a constant pool load instead.
7075 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7078 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7079 // vector that will get spilled to the constant pool.
7080 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7082 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7083 // that it is in input element units, not in bytes. Convert now.
7085 // For little endian, the order of the input vectors is reversed, and
7086 // the permutation mask is complemented with respect to 31. This is
7087 // necessary to produce proper semantics with the big-endian-biased vperm
7089 EVT EltVT = V1.getValueType().getVectorElementType();
7090 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7092 SmallVector<SDValue, 16> ResultMask;
7093 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7094 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7096 for (unsigned j = 0; j != BytesPerElement; ++j)
7098 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7101 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7105 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7108 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7111 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7115 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7116 /// altivec comparison. If it is, return true and fill in Opc/isDot with
7117 /// information about the intrinsic.
7118 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7119 bool &isDot, const PPCSubtarget &Subtarget) {
7120 unsigned IntrinsicID =
7121 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7124 switch (IntrinsicID) {
7125 default: return false;
7126 // Comparison predicates.
7127 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7128 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7129 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7130 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7131 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7132 case Intrinsic::ppc_altivec_vcmpequd_p:
7133 if (Subtarget.hasP8Altivec()) {
7141 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7142 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7143 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7144 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7145 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7146 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7147 if (Subtarget.hasP8Altivec()) {
7155 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7156 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7157 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7158 case Intrinsic::ppc_altivec_vcmpgtud_p:
7159 if (Subtarget.hasP8Altivec()) {
7168 // Normal Comparisons.
7169 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7170 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7171 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7172 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7173 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7174 case Intrinsic::ppc_altivec_vcmpequd:
7175 if (Subtarget.hasP8Altivec()) {
7183 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7184 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7185 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7186 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7187 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7188 case Intrinsic::ppc_altivec_vcmpgtsd:
7189 if (Subtarget.hasP8Altivec()) {
7197 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7198 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7199 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7200 case Intrinsic::ppc_altivec_vcmpgtud:
7201 if (Subtarget.hasP8Altivec()) {
7213 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7214 /// lower, do it, otherwise return null.
7215 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7216 SelectionDAG &DAG) const {
7217 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7218 // opcode number of the comparison.
7222 if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7223 return SDValue(); // Don't custom lower most intrinsics.
7225 // If this is a non-dot comparison, make the VCMP node and we are done.
7227 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7228 Op.getOperand(1), Op.getOperand(2),
7229 DAG.getConstant(CompareOpc, dl, MVT::i32));
7230 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7233 // Create the PPCISD altivec 'dot' comparison node.
7235 Op.getOperand(2), // LHS
7236 Op.getOperand(3), // RHS
7237 DAG.getConstant(CompareOpc, dl, MVT::i32)
7239 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7240 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7242 // Now that we have the comparison, emit a copy from the CR to a GPR.
7243 // This is flagged to the above dot comparison.
7244 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7245 DAG.getRegister(PPC::CR6, MVT::i32),
7246 CompNode.getValue(1));
7248 // Unpack the result based on how the target uses it.
7249 unsigned BitNo; // Bit # of CR6.
7250 bool InvertBit; // Invert result?
7251 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7252 default: // Can't happen, don't crash on invalid number though.
7253 case 0: // Return the value of the EQ bit of CR6.
7254 BitNo = 0; InvertBit = false;
7256 case 1: // Return the inverted value of the EQ bit of CR6.
7257 BitNo = 0; InvertBit = true;
7259 case 2: // Return the value of the LT bit of CR6.
7260 BitNo = 2; InvertBit = false;
7262 case 3: // Return the inverted value of the LT bit of CR6.
7263 BitNo = 2; InvertBit = true;
7267 // Shift the bit into the low position.
7268 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7269 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7271 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7272 DAG.getConstant(1, dl, MVT::i32));
7274 // If we are supposed to, toggle the bit.
7276 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7277 DAG.getConstant(1, dl, MVT::i32));
7281 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7282 SelectionDAG &DAG) const {
7284 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7285 // instructions), but for smaller types, we need to first extend up to v2i32
7286 // before doing going farther.
7287 if (Op.getValueType() == MVT::v2i64) {
7288 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7289 if (ExtVT != MVT::v2i32) {
7290 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7291 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7292 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7293 ExtVT.getVectorElementType(), 4)));
7294 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7295 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7296 DAG.getValueType(MVT::v2i32));
7305 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7306 SelectionDAG &DAG) const {
7308 // Create a stack slot that is 16-byte aligned.
7309 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7310 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7311 EVT PtrVT = getPointerTy();
7312 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7314 // Store the input value into Value#0 of the stack slot.
7315 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7316 Op.getOperand(0), FIdx, MachinePointerInfo(),
7319 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7320 false, false, false, 0);
7323 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7324 SelectionDAG &DAG) const {
7326 SDNode *N = Op.getNode();
7328 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7329 "Unknown extract_vector_elt type");
7331 SDValue Value = N->getOperand(0);
7333 // The first part of this is like the store lowering except that we don't
7334 // need to track the chain.
7336 // The values are now known to be -1 (false) or 1 (true). To convert this
7337 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7338 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7339 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7341 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7342 // understand how to form the extending load.
7343 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7344 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7345 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7347 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7349 // Now convert to an integer and store.
7350 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7351 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7354 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7355 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7356 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7357 EVT PtrVT = getPointerTy();
7358 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7360 SDValue StoreChain = DAG.getEntryNode();
7361 SmallVector<SDValue, 2> Ops;
7362 Ops.push_back(StoreChain);
7363 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7364 Ops.push_back(Value);
7365 Ops.push_back(FIdx);
7367 SmallVector<EVT, 2> ValueVTs;
7368 ValueVTs.push_back(MVT::Other); // chain
7369 SDVTList VTs = DAG.getVTList(ValueVTs);
7371 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7372 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7374 // Extract the value requested.
7375 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7376 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7377 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7379 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7380 PtrInfo.getWithOffset(Offset),
7381 false, false, false, 0);
7383 if (!Subtarget.useCRBits())
7386 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7389 /// Lowering for QPX v4i1 loads
7390 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7391 SelectionDAG &DAG) const {
7393 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7394 SDValue LoadChain = LN->getChain();
7395 SDValue BasePtr = LN->getBasePtr();
7397 if (Op.getValueType() == MVT::v4f64 ||
7398 Op.getValueType() == MVT::v4f32) {
7399 EVT MemVT = LN->getMemoryVT();
7400 unsigned Alignment = LN->getAlignment();
7402 // If this load is properly aligned, then it is legal.
7403 if (Alignment >= MemVT.getStoreSize())
7406 EVT ScalarVT = Op.getValueType().getScalarType(),
7407 ScalarMemVT = MemVT.getScalarType();
7408 unsigned Stride = ScalarMemVT.getStoreSize();
7410 SmallVector<SDValue, 8> Vals, LoadChains;
7411 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7413 if (ScalarVT != ScalarMemVT)
7415 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7417 LN->getPointerInfo().getWithOffset(Idx*Stride),
7418 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7419 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7423 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7424 LN->getPointerInfo().getWithOffset(Idx*Stride),
7425 LN->isVolatile(), LN->isNonTemporal(),
7426 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7429 if (Idx == 0 && LN->isIndexed()) {
7430 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7431 "Unknown addressing mode on vector load");
7432 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7433 LN->getAddressingMode());
7436 Vals.push_back(Load);
7437 LoadChains.push_back(Load.getValue(1));
7439 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7440 DAG.getConstant(Stride, dl,
7441 BasePtr.getValueType()));
7444 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7445 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7446 Op.getValueType(), Vals);
7448 if (LN->isIndexed()) {
7449 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7450 return DAG.getMergeValues(RetOps, dl);
7453 SDValue RetOps[] = { Value, TF };
7454 return DAG.getMergeValues(RetOps, dl);
7457 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7458 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7460 // To lower v4i1 from a byte array, we load the byte elements of the
7461 // vector and then reuse the BUILD_VECTOR logic.
7463 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7464 for (unsigned i = 0; i < 4; ++i) {
7465 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7466 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7468 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7469 dl, MVT::i32, LoadChain, Idx,
7470 LN->getPointerInfo().getWithOffset(i),
7471 MVT::i8 /* memory type */,
7472 LN->isVolatile(), LN->isNonTemporal(),
7474 1 /* alignment */, LN->getAAInfo()));
7475 VectElmtChains.push_back(VectElmts[i].getValue(1));
7478 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7479 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7481 SDValue RVals[] = { Value, LoadChain };
7482 return DAG.getMergeValues(RVals, dl);
7485 /// Lowering for QPX v4i1 stores
7486 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7487 SelectionDAG &DAG) const {
7489 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7490 SDValue StoreChain = SN->getChain();
7491 SDValue BasePtr = SN->getBasePtr();
7492 SDValue Value = SN->getValue();
7494 if (Value.getValueType() == MVT::v4f64 ||
7495 Value.getValueType() == MVT::v4f32) {
7496 EVT MemVT = SN->getMemoryVT();
7497 unsigned Alignment = SN->getAlignment();
7499 // If this store is properly aligned, then it is legal.
7500 if (Alignment >= MemVT.getStoreSize())
7503 EVT ScalarVT = Value.getValueType().getScalarType(),
7504 ScalarMemVT = MemVT.getScalarType();
7505 unsigned Stride = ScalarMemVT.getStoreSize();
7507 SmallVector<SDValue, 8> Stores;
7508 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7510 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7511 DAG.getConstant(Idx, dl, getVectorIdxTy()));
7513 if (ScalarVT != ScalarMemVT)
7515 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7516 SN->getPointerInfo().getWithOffset(Idx*Stride),
7517 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7518 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7521 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7522 SN->getPointerInfo().getWithOffset(Idx*Stride),
7523 SN->isVolatile(), SN->isNonTemporal(),
7524 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7526 if (Idx == 0 && SN->isIndexed()) {
7527 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7528 "Unknown addressing mode on vector store");
7529 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7530 SN->getAddressingMode());
7533 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7534 DAG.getConstant(Stride, dl,
7535 BasePtr.getValueType()));
7536 Stores.push_back(Store);
7539 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7541 if (SN->isIndexed()) {
7542 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7543 return DAG.getMergeValues(RetOps, dl);
7549 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7550 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7552 // The values are now known to be -1 (false) or 1 (true). To convert this
7553 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7554 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7555 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7557 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7558 // understand how to form the extending load.
7559 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7560 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7561 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7563 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7565 // Now convert to an integer and store.
7566 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7567 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7570 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7571 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7572 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7573 EVT PtrVT = getPointerTy();
7574 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7576 SmallVector<SDValue, 2> Ops;
7577 Ops.push_back(StoreChain);
7578 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7579 Ops.push_back(Value);
7580 Ops.push_back(FIdx);
7582 SmallVector<EVT, 2> ValueVTs;
7583 ValueVTs.push_back(MVT::Other); // chain
7584 SDVTList VTs = DAG.getVTList(ValueVTs);
7586 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7587 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7589 // Move data into the byte array.
7590 SmallVector<SDValue, 4> Loads, LoadChains;
7591 for (unsigned i = 0; i < 4; ++i) {
7592 unsigned Offset = 4*i;
7593 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7594 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7596 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7597 PtrInfo.getWithOffset(Offset),
7598 false, false, false, 0));
7599 LoadChains.push_back(Loads[i].getValue(1));
7602 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7604 SmallVector<SDValue, 4> Stores;
7605 for (unsigned i = 0; i < 4; ++i) {
7606 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7607 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7609 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7610 SN->getPointerInfo().getWithOffset(i),
7611 MVT::i8 /* memory type */,
7612 SN->isNonTemporal(), SN->isVolatile(),
7613 1 /* alignment */, SN->getAAInfo()));
7616 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7621 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7623 if (Op.getValueType() == MVT::v4i32) {
7624 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7626 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7627 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7629 SDValue RHSSwap = // = vrlw RHS, 16
7630 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7632 // Shrinkify inputs to v8i16.
7633 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7634 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7635 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7637 // Low parts multiplied together, generating 32-bit results (we ignore the
7639 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7640 LHS, RHS, DAG, dl, MVT::v4i32);
7642 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7643 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7644 // Shift the high parts up 16 bits.
7645 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7647 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7648 } else if (Op.getValueType() == MVT::v8i16) {
7649 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7651 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7653 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7654 LHS, RHS, Zero, DAG, dl);
7655 } else if (Op.getValueType() == MVT::v16i8) {
7656 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7657 bool isLittleEndian = Subtarget.isLittleEndian();
7659 // Multiply the even 8-bit parts, producing 16-bit sums.
7660 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7661 LHS, RHS, DAG, dl, MVT::v8i16);
7662 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7664 // Multiply the odd 8-bit parts, producing 16-bit sums.
7665 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7666 LHS, RHS, DAG, dl, MVT::v8i16);
7667 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7669 // Merge the results together. Because vmuleub and vmuloub are
7670 // instructions with a big-endian bias, we must reverse the
7671 // element numbering and reverse the meaning of "odd" and "even"
7672 // when generating little endian code.
7674 for (unsigned i = 0; i != 8; ++i) {
7675 if (isLittleEndian) {
7677 Ops[i*2+1] = 2*i+16;
7680 Ops[i*2+1] = 2*i+1+16;
7684 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7686 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7688 llvm_unreachable("Unknown mul to lower!");
7692 /// LowerOperation - Provide custom lowering hooks for some operations.
7694 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7695 switch (Op.getOpcode()) {
7696 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7697 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7698 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7699 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7700 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7701 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7702 case ISD::SETCC: return LowerSETCC(Op, DAG);
7703 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7704 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7706 return LowerVASTART(Op, DAG, Subtarget);
7709 return LowerVAARG(Op, DAG, Subtarget);
7712 return LowerVACOPY(Op, DAG, Subtarget);
7714 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7715 case ISD::DYNAMIC_STACKALLOC:
7716 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7718 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7719 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7721 case ISD::LOAD: return LowerLOAD(Op, DAG);
7722 case ISD::STORE: return LowerSTORE(Op, DAG);
7723 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7724 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7725 case ISD::FP_TO_UINT:
7726 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7728 case ISD::UINT_TO_FP:
7729 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7730 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7732 // Lower 64-bit shifts.
7733 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7734 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7735 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7737 // Vector-related lowering.
7738 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7739 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7740 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7741 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7742 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7743 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7744 case ISD::MUL: return LowerMUL(Op, DAG);
7746 // For counter-based loop handling.
7747 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7749 // Frame & Return address.
7750 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7751 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7755 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7756 SmallVectorImpl<SDValue>&Results,
7757 SelectionDAG &DAG) const {
7759 switch (N->getOpcode()) {
7761 llvm_unreachable("Do not know how to custom type legalize this operation!");
7762 case ISD::READCYCLECOUNTER: {
7763 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7764 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7766 Results.push_back(RTB);
7767 Results.push_back(RTB.getValue(1));
7768 Results.push_back(RTB.getValue(2));
7771 case ISD::INTRINSIC_W_CHAIN: {
7772 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7773 Intrinsic::ppc_is_decremented_ctr_nonzero)
7776 assert(N->getValueType(0) == MVT::i1 &&
7777 "Unexpected result type for CTR decrement intrinsic");
7778 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7779 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7780 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7783 Results.push_back(NewInt);
7784 Results.push_back(NewInt.getValue(1));
7788 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7791 EVT VT = N->getValueType(0);
7793 if (VT == MVT::i64) {
7794 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7796 Results.push_back(NewNode);
7797 Results.push_back(NewNode.getValue(1));
7801 case ISD::FP_ROUND_INREG: {
7802 assert(N->getValueType(0) == MVT::ppcf128);
7803 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7804 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7805 MVT::f64, N->getOperand(0),
7806 DAG.getIntPtrConstant(0, dl));
7807 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7808 MVT::f64, N->getOperand(0),
7809 DAG.getIntPtrConstant(1, dl));
7811 // Add the two halves of the long double in round-to-zero mode.
7812 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7814 // We know the low half is about to be thrown away, so just use something
7816 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7820 case ISD::FP_TO_SINT:
7821 case ISD::FP_TO_UINT:
7822 // LowerFP_TO_INT() can only handle f32 and f64.
7823 if (N->getOperand(0).getValueType() == MVT::ppcf128)
7825 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7831 //===----------------------------------------------------------------------===//
7832 // Other Lowering Code
7833 //===----------------------------------------------------------------------===//
7835 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7836 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7837 Function *Func = Intrinsic::getDeclaration(M, Id);
7838 return Builder.CreateCall(Func);
7841 // The mappings for emitLeading/TrailingFence is taken from
7842 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7843 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7844 AtomicOrdering Ord, bool IsStore,
7845 bool IsLoad) const {
7846 if (Ord == SequentiallyConsistent)
7847 return callIntrinsic(Builder, Intrinsic::ppc_sync);
7848 else if (isAtLeastRelease(Ord))
7849 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7854 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7855 AtomicOrdering Ord, bool IsStore,
7856 bool IsLoad) const {
7857 if (IsLoad && isAtLeastAcquire(Ord))
7858 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7859 // FIXME: this is too conservative, a dependent branch + isync is enough.
7860 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7861 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7862 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7868 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7869 unsigned AtomicSize,
7870 unsigned BinOpcode) const {
7871 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7872 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7874 auto LoadMnemonic = PPC::LDARX;
7875 auto StoreMnemonic = PPC::STDCX;
7876 switch (AtomicSize) {
7878 llvm_unreachable("Unexpected size of atomic entity");
7880 LoadMnemonic = PPC::LBARX;
7881 StoreMnemonic = PPC::STBCX;
7882 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7885 LoadMnemonic = PPC::LHARX;
7886 StoreMnemonic = PPC::STHCX;
7887 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7890 LoadMnemonic = PPC::LWARX;
7891 StoreMnemonic = PPC::STWCX;
7894 LoadMnemonic = PPC::LDARX;
7895 StoreMnemonic = PPC::STDCX;
7899 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7900 MachineFunction *F = BB->getParent();
7901 MachineFunction::iterator It = BB;
7904 unsigned dest = MI->getOperand(0).getReg();
7905 unsigned ptrA = MI->getOperand(1).getReg();
7906 unsigned ptrB = MI->getOperand(2).getReg();
7907 unsigned incr = MI->getOperand(3).getReg();
7908 DebugLoc dl = MI->getDebugLoc();
7910 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7911 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7912 F->insert(It, loopMBB);
7913 F->insert(It, exitMBB);
7914 exitMBB->splice(exitMBB->begin(), BB,
7915 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7916 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7918 MachineRegisterInfo &RegInfo = F->getRegInfo();
7919 unsigned TmpReg = (!BinOpcode) ? incr :
7920 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7921 : &PPC::GPRCRegClass);
7925 // fallthrough --> loopMBB
7926 BB->addSuccessor(loopMBB);
7929 // l[wd]arx dest, ptr
7930 // add r0, dest, incr
7931 // st[wd]cx. r0, ptr
7933 // fallthrough --> exitMBB
7935 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7936 .addReg(ptrA).addReg(ptrB);
7938 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7939 BuildMI(BB, dl, TII->get(StoreMnemonic))
7940 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7941 BuildMI(BB, dl, TII->get(PPC::BCC))
7942 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7943 BB->addSuccessor(loopMBB);
7944 BB->addSuccessor(exitMBB);
7953 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7954 MachineBasicBlock *BB,
7955 bool is8bit, // operation
7956 unsigned BinOpcode) const {
7957 // If we support part-word atomic mnemonics, just use them
7958 if (Subtarget.hasPartwordAtomics())
7959 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7961 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7962 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7963 // In 64 bit mode we have to use 64 bits for addresses, even though the
7964 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7965 // registers without caring whether they're 32 or 64, but here we're
7966 // doing actual arithmetic on the addresses.
7967 bool is64bit = Subtarget.isPPC64();
7968 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7970 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7971 MachineFunction *F = BB->getParent();
7972 MachineFunction::iterator It = BB;
7975 unsigned dest = MI->getOperand(0).getReg();
7976 unsigned ptrA = MI->getOperand(1).getReg();
7977 unsigned ptrB = MI->getOperand(2).getReg();
7978 unsigned incr = MI->getOperand(3).getReg();
7979 DebugLoc dl = MI->getDebugLoc();
7981 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7982 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7983 F->insert(It, loopMBB);
7984 F->insert(It, exitMBB);
7985 exitMBB->splice(exitMBB->begin(), BB,
7986 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7987 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7989 MachineRegisterInfo &RegInfo = F->getRegInfo();
7990 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7991 : &PPC::GPRCRegClass;
7992 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7993 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7994 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7995 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7996 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7997 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7998 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7999 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8000 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8001 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8002 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8004 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8008 // fallthrough --> loopMBB
8009 BB->addSuccessor(loopMBB);
8011 // The 4-byte load must be aligned, while a char or short may be
8012 // anywhere in the word. Hence all this nasty bookkeeping code.
8013 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8014 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8015 // xori shift, shift1, 24 [16]
8016 // rlwinm ptr, ptr1, 0, 0, 29
8017 // slw incr2, incr, shift
8018 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8019 // slw mask, mask2, shift
8021 // lwarx tmpDest, ptr
8022 // add tmp, tmpDest, incr2
8023 // andc tmp2, tmpDest, mask
8024 // and tmp3, tmp, mask
8025 // or tmp4, tmp3, tmp2
8028 // fallthrough --> exitMBB
8029 // srw dest, tmpDest, shift
8030 if (ptrA != ZeroReg) {
8031 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8032 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8033 .addReg(ptrA).addReg(ptrB);
8037 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8038 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8039 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8040 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8042 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8043 .addReg(Ptr1Reg).addImm(0).addImm(61);
8045 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8046 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8047 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8048 .addReg(incr).addReg(ShiftReg);
8050 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8052 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8053 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8055 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8056 .addReg(Mask2Reg).addReg(ShiftReg);
8059 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8060 .addReg(ZeroReg).addReg(PtrReg);
8062 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8063 .addReg(Incr2Reg).addReg(TmpDestReg);
8064 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8065 .addReg(TmpDestReg).addReg(MaskReg);
8066 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8067 .addReg(TmpReg).addReg(MaskReg);
8068 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8069 .addReg(Tmp3Reg).addReg(Tmp2Reg);
8070 BuildMI(BB, dl, TII->get(PPC::STWCX))
8071 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8072 BuildMI(BB, dl, TII->get(PPC::BCC))
8073 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8074 BB->addSuccessor(loopMBB);
8075 BB->addSuccessor(exitMBB);
8080 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8085 llvm::MachineBasicBlock*
8086 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8087 MachineBasicBlock *MBB) const {
8088 DebugLoc DL = MI->getDebugLoc();
8089 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8091 MachineFunction *MF = MBB->getParent();
8092 MachineRegisterInfo &MRI = MF->getRegInfo();
8094 const BasicBlock *BB = MBB->getBasicBlock();
8095 MachineFunction::iterator I = MBB;
8099 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8100 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8102 unsigned DstReg = MI->getOperand(0).getReg();
8103 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8104 assert(RC->hasType(MVT::i32) && "Invalid destination!");
8105 unsigned mainDstReg = MRI.createVirtualRegister(RC);
8106 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8108 MVT PVT = getPointerTy();
8109 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8110 "Invalid Pointer Size!");
8111 // For v = setjmp(buf), we generate
8114 // SjLjSetup mainMBB
8120 // buf[LabelOffset] = LR
8124 // v = phi(main, restore)
8127 MachineBasicBlock *thisMBB = MBB;
8128 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8129 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8130 MF->insert(I, mainMBB);
8131 MF->insert(I, sinkMBB);
8133 MachineInstrBuilder MIB;
8135 // Transfer the remainder of BB and its successor edges to sinkMBB.
8136 sinkMBB->splice(sinkMBB->begin(), MBB,
8137 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8138 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8140 // Note that the structure of the jmp_buf used here is not compatible
8141 // with that used by libc, and is not designed to be. Specifically, it
8142 // stores only those 'reserved' registers that LLVM does not otherwise
8143 // understand how to spill. Also, by convention, by the time this
8144 // intrinsic is called, Clang has already stored the frame address in the
8145 // first slot of the buffer and stack address in the third. Following the
8146 // X86 target code, we'll store the jump address in the second slot. We also
8147 // need to save the TOC pointer (R2) to handle jumps between shared
8148 // libraries, and that will be stored in the fourth slot. The thread
8149 // identifier (R13) is not affected.
8152 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8153 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8154 const int64_t BPOffset = 4 * PVT.getStoreSize();
8156 // Prepare IP either in reg.
8157 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8158 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8159 unsigned BufReg = MI->getOperand(1).getReg();
8161 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8162 setUsesTOCBasePtr(*MBB->getParent());
8163 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8167 MIB.setMemRefs(MMOBegin, MMOEnd);
8170 // Naked functions never have a base pointer, and so we use r1. For all
8171 // other functions, this decision must be delayed until during PEI.
8173 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8174 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8176 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8178 MIB = BuildMI(*thisMBB, MI, DL,
8179 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8183 MIB.setMemRefs(MMOBegin, MMOEnd);
8186 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8187 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8188 MIB.addRegMask(TRI->getNoPreservedMask());
8190 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8192 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8194 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8196 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8197 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8202 BuildMI(mainMBB, DL,
8203 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8206 if (Subtarget.isPPC64()) {
8207 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8209 .addImm(LabelOffset)
8212 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8214 .addImm(LabelOffset)
8218 MIB.setMemRefs(MMOBegin, MMOEnd);
8220 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8221 mainMBB->addSuccessor(sinkMBB);
8224 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8225 TII->get(PPC::PHI), DstReg)
8226 .addReg(mainDstReg).addMBB(mainMBB)
8227 .addReg(restoreDstReg).addMBB(thisMBB);
8229 MI->eraseFromParent();
8234 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8235 MachineBasicBlock *MBB) const {
8236 DebugLoc DL = MI->getDebugLoc();
8237 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8239 MachineFunction *MF = MBB->getParent();
8240 MachineRegisterInfo &MRI = MF->getRegInfo();
8243 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8244 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8246 MVT PVT = getPointerTy();
8247 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8248 "Invalid Pointer Size!");
8250 const TargetRegisterClass *RC =
8251 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8252 unsigned Tmp = MRI.createVirtualRegister(RC);
8253 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8254 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8255 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8259 : (Subtarget.isSVR4ABI() &&
8260 MF->getTarget().getRelocationModel() == Reloc::PIC_
8264 MachineInstrBuilder MIB;
8266 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8267 const int64_t SPOffset = 2 * PVT.getStoreSize();
8268 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8269 const int64_t BPOffset = 4 * PVT.getStoreSize();
8271 unsigned BufReg = MI->getOperand(0).getReg();
8273 // Reload FP (the jumped-to function may not have had a
8274 // frame pointer, and if so, then its r31 will be restored
8276 if (PVT == MVT::i64) {
8277 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8281 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8285 MIB.setMemRefs(MMOBegin, MMOEnd);
8288 if (PVT == MVT::i64) {
8289 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8290 .addImm(LabelOffset)
8293 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8294 .addImm(LabelOffset)
8297 MIB.setMemRefs(MMOBegin, MMOEnd);
8300 if (PVT == MVT::i64) {
8301 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8305 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8309 MIB.setMemRefs(MMOBegin, MMOEnd);
8312 if (PVT == MVT::i64) {
8313 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8317 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8321 MIB.setMemRefs(MMOBegin, MMOEnd);
8324 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8325 setUsesTOCBasePtr(*MBB->getParent());
8326 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8330 MIB.setMemRefs(MMOBegin, MMOEnd);
8334 BuildMI(*MBB, MI, DL,
8335 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8336 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8338 MI->eraseFromParent();
8343 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8344 MachineBasicBlock *BB) const {
8345 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8346 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8347 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8348 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8349 // Call lowering should have added an r2 operand to indicate a dependence
8350 // on the TOC base pointer value. It can't however, because there is no
8351 // way to mark the dependence as implicit there, and so the stackmap code
8352 // will confuse it with a regular operand. Instead, add the dependence
8354 setUsesTOCBasePtr(*BB->getParent());
8355 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8358 return emitPatchPoint(MI, BB);
8361 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8362 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8363 return emitEHSjLjSetJmp(MI, BB);
8364 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8365 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8366 return emitEHSjLjLongJmp(MI, BB);
8369 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8371 // To "insert" these instructions we actually have to insert their
8372 // control-flow patterns.
8373 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8374 MachineFunction::iterator It = BB;
8377 MachineFunction *F = BB->getParent();
8379 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8380 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8381 MI->getOpcode() == PPC::SELECT_I4 ||
8382 MI->getOpcode() == PPC::SELECT_I8)) {
8383 SmallVector<MachineOperand, 2> Cond;
8384 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8385 MI->getOpcode() == PPC::SELECT_CC_I8)
8386 Cond.push_back(MI->getOperand(4));
8388 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8389 Cond.push_back(MI->getOperand(1));
8391 DebugLoc dl = MI->getDebugLoc();
8392 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8393 Cond, MI->getOperand(2).getReg(),
8394 MI->getOperand(3).getReg());
8395 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8396 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8397 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8398 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8399 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8400 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8401 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8402 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8403 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8404 MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8405 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8406 MI->getOpcode() == PPC::SELECT_I4 ||
8407 MI->getOpcode() == PPC::SELECT_I8 ||
8408 MI->getOpcode() == PPC::SELECT_F4 ||
8409 MI->getOpcode() == PPC::SELECT_F8 ||
8410 MI->getOpcode() == PPC::SELECT_QFRC ||
8411 MI->getOpcode() == PPC::SELECT_QSRC ||
8412 MI->getOpcode() == PPC::SELECT_QBRC ||
8413 MI->getOpcode() == PPC::SELECT_VRRC ||
8414 MI->getOpcode() == PPC::SELECT_VSFRC ||
8415 MI->getOpcode() == PPC::SELECT_VSSRC ||
8416 MI->getOpcode() == PPC::SELECT_VSRC) {
8417 // The incoming instruction knows the destination vreg to set, the
8418 // condition code register to branch on, the true/false values to
8419 // select between, and a branch opcode to use.
8424 // cmpTY ccX, r1, r2
8426 // fallthrough --> copy0MBB
8427 MachineBasicBlock *thisMBB = BB;
8428 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8429 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8430 DebugLoc dl = MI->getDebugLoc();
8431 F->insert(It, copy0MBB);
8432 F->insert(It, sinkMBB);
8434 // Transfer the remainder of BB and its successor edges to sinkMBB.
8435 sinkMBB->splice(sinkMBB->begin(), BB,
8436 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8437 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8439 // Next, add the true and fallthrough blocks as its successors.
8440 BB->addSuccessor(copy0MBB);
8441 BB->addSuccessor(sinkMBB);
8443 if (MI->getOpcode() == PPC::SELECT_I4 ||
8444 MI->getOpcode() == PPC::SELECT_I8 ||
8445 MI->getOpcode() == PPC::SELECT_F4 ||
8446 MI->getOpcode() == PPC::SELECT_F8 ||
8447 MI->getOpcode() == PPC::SELECT_QFRC ||
8448 MI->getOpcode() == PPC::SELECT_QSRC ||
8449 MI->getOpcode() == PPC::SELECT_QBRC ||
8450 MI->getOpcode() == PPC::SELECT_VRRC ||
8451 MI->getOpcode() == PPC::SELECT_VSFRC ||
8452 MI->getOpcode() == PPC::SELECT_VSSRC ||
8453 MI->getOpcode() == PPC::SELECT_VSRC) {
8454 BuildMI(BB, dl, TII->get(PPC::BC))
8455 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8457 unsigned SelectPred = MI->getOperand(4).getImm();
8458 BuildMI(BB, dl, TII->get(PPC::BCC))
8459 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8463 // %FalseValue = ...
8464 // # fallthrough to sinkMBB
8467 // Update machine-CFG edges
8468 BB->addSuccessor(sinkMBB);
8471 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8474 BuildMI(*BB, BB->begin(), dl,
8475 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8476 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8477 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8478 } else if (MI->getOpcode() == PPC::ReadTB) {
8479 // To read the 64-bit time-base register on a 32-bit target, we read the
8480 // two halves. Should the counter have wrapped while it was being read, we
8481 // need to try again.
8484 // mfspr Rx,TBU # load from TBU
8485 // mfspr Ry,TB # load from TB
8486 // mfspr Rz,TBU # load from TBU
8487 // cmpw crX,Rx,Rz # check if ‘old’=’new’
8488 // bne readLoop # branch if they're not equal
8491 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8492 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8493 DebugLoc dl = MI->getDebugLoc();
8494 F->insert(It, readMBB);
8495 F->insert(It, sinkMBB);
8497 // Transfer the remainder of BB and its successor edges to sinkMBB.
8498 sinkMBB->splice(sinkMBB->begin(), BB,
8499 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8500 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8502 BB->addSuccessor(readMBB);
8505 MachineRegisterInfo &RegInfo = F->getRegInfo();
8506 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8507 unsigned LoReg = MI->getOperand(0).getReg();
8508 unsigned HiReg = MI->getOperand(1).getReg();
8510 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8511 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8512 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8514 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8516 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8517 .addReg(HiReg).addReg(ReadAgainReg);
8518 BuildMI(BB, dl, TII->get(PPC::BCC))
8519 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8521 BB->addSuccessor(readMBB);
8522 BB->addSuccessor(sinkMBB);
8524 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8525 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8526 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8527 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8528 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8529 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8530 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8531 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8533 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8534 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8535 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8536 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8537 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8538 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8539 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8540 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8542 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8543 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8544 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8545 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8546 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8547 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8548 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8549 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8551 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8552 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8553 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8554 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8555 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8556 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8557 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8558 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8560 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8561 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8562 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8563 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8564 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8565 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8566 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8567 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8569 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8570 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8571 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8572 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8573 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8574 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8575 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8576 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8578 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8579 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8580 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8581 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8582 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8583 BB = EmitAtomicBinary(MI, BB, 4, 0);
8584 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8585 BB = EmitAtomicBinary(MI, BB, 8, 0);
8587 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8588 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8589 (Subtarget.hasPartwordAtomics() &&
8590 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8591 (Subtarget.hasPartwordAtomics() &&
8592 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8593 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8595 auto LoadMnemonic = PPC::LDARX;
8596 auto StoreMnemonic = PPC::STDCX;
8597 switch(MI->getOpcode()) {
8599 llvm_unreachable("Compare and swap of unknown size");
8600 case PPC::ATOMIC_CMP_SWAP_I8:
8601 LoadMnemonic = PPC::LBARX;
8602 StoreMnemonic = PPC::STBCX;
8603 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8605 case PPC::ATOMIC_CMP_SWAP_I16:
8606 LoadMnemonic = PPC::LHARX;
8607 StoreMnemonic = PPC::STHCX;
8608 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8610 case PPC::ATOMIC_CMP_SWAP_I32:
8611 LoadMnemonic = PPC::LWARX;
8612 StoreMnemonic = PPC::STWCX;
8614 case PPC::ATOMIC_CMP_SWAP_I64:
8615 LoadMnemonic = PPC::LDARX;
8616 StoreMnemonic = PPC::STDCX;
8619 unsigned dest = MI->getOperand(0).getReg();
8620 unsigned ptrA = MI->getOperand(1).getReg();
8621 unsigned ptrB = MI->getOperand(2).getReg();
8622 unsigned oldval = MI->getOperand(3).getReg();
8623 unsigned newval = MI->getOperand(4).getReg();
8624 DebugLoc dl = MI->getDebugLoc();
8626 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8627 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8628 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8629 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8630 F->insert(It, loop1MBB);
8631 F->insert(It, loop2MBB);
8632 F->insert(It, midMBB);
8633 F->insert(It, exitMBB);
8634 exitMBB->splice(exitMBB->begin(), BB,
8635 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8636 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8640 // fallthrough --> loopMBB
8641 BB->addSuccessor(loop1MBB);
8644 // l[bhwd]arx dest, ptr
8645 // cmp[wd] dest, oldval
8648 // st[bhwd]cx. newval, ptr
8652 // st[bhwd]cx. dest, ptr
8655 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8656 .addReg(ptrA).addReg(ptrB);
8657 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8658 .addReg(oldval).addReg(dest);
8659 BuildMI(BB, dl, TII->get(PPC::BCC))
8660 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8661 BB->addSuccessor(loop2MBB);
8662 BB->addSuccessor(midMBB);
8665 BuildMI(BB, dl, TII->get(StoreMnemonic))
8666 .addReg(newval).addReg(ptrA).addReg(ptrB);
8667 BuildMI(BB, dl, TII->get(PPC::BCC))
8668 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8669 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8670 BB->addSuccessor(loop1MBB);
8671 BB->addSuccessor(exitMBB);
8674 BuildMI(BB, dl, TII->get(StoreMnemonic))
8675 .addReg(dest).addReg(ptrA).addReg(ptrB);
8676 BB->addSuccessor(exitMBB);
8681 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8682 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8683 // We must use 64-bit registers for addresses when targeting 64-bit,
8684 // since we're actually doing arithmetic on them. Other registers
8686 bool is64bit = Subtarget.isPPC64();
8687 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8689 unsigned dest = MI->getOperand(0).getReg();
8690 unsigned ptrA = MI->getOperand(1).getReg();
8691 unsigned ptrB = MI->getOperand(2).getReg();
8692 unsigned oldval = MI->getOperand(3).getReg();
8693 unsigned newval = MI->getOperand(4).getReg();
8694 DebugLoc dl = MI->getDebugLoc();
8696 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8697 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8698 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8699 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8700 F->insert(It, loop1MBB);
8701 F->insert(It, loop2MBB);
8702 F->insert(It, midMBB);
8703 F->insert(It, exitMBB);
8704 exitMBB->splice(exitMBB->begin(), BB,
8705 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8706 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8708 MachineRegisterInfo &RegInfo = F->getRegInfo();
8709 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8710 : &PPC::GPRCRegClass;
8711 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8712 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8713 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8714 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8715 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8716 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8717 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8718 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8719 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8720 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8721 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8722 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8723 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8725 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8726 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8729 // fallthrough --> loopMBB
8730 BB->addSuccessor(loop1MBB);
8732 // The 4-byte load must be aligned, while a char or short may be
8733 // anywhere in the word. Hence all this nasty bookkeeping code.
8734 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8735 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8736 // xori shift, shift1, 24 [16]
8737 // rlwinm ptr, ptr1, 0, 0, 29
8738 // slw newval2, newval, shift
8739 // slw oldval2, oldval,shift
8740 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8741 // slw mask, mask2, shift
8742 // and newval3, newval2, mask
8743 // and oldval3, oldval2, mask
8745 // lwarx tmpDest, ptr
8746 // and tmp, tmpDest, mask
8747 // cmpw tmp, oldval3
8750 // andc tmp2, tmpDest, mask
8751 // or tmp4, tmp2, newval3
8756 // stwcx. tmpDest, ptr
8758 // srw dest, tmpDest, shift
8759 if (ptrA != ZeroReg) {
8760 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8761 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8762 .addReg(ptrA).addReg(ptrB);
8766 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8767 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8768 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8769 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8771 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8772 .addReg(Ptr1Reg).addImm(0).addImm(61);
8774 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8775 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8776 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8777 .addReg(newval).addReg(ShiftReg);
8778 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8779 .addReg(oldval).addReg(ShiftReg);
8781 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8783 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8784 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8785 .addReg(Mask3Reg).addImm(65535);
8787 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8788 .addReg(Mask2Reg).addReg(ShiftReg);
8789 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8790 .addReg(NewVal2Reg).addReg(MaskReg);
8791 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8792 .addReg(OldVal2Reg).addReg(MaskReg);
8795 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8796 .addReg(ZeroReg).addReg(PtrReg);
8797 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8798 .addReg(TmpDestReg).addReg(MaskReg);
8799 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8800 .addReg(TmpReg).addReg(OldVal3Reg);
8801 BuildMI(BB, dl, TII->get(PPC::BCC))
8802 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8803 BB->addSuccessor(loop2MBB);
8804 BB->addSuccessor(midMBB);
8807 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8808 .addReg(TmpDestReg).addReg(MaskReg);
8809 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8810 .addReg(Tmp2Reg).addReg(NewVal3Reg);
8811 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8812 .addReg(ZeroReg).addReg(PtrReg);
8813 BuildMI(BB, dl, TII->get(PPC::BCC))
8814 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8815 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8816 BB->addSuccessor(loop1MBB);
8817 BB->addSuccessor(exitMBB);
8820 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8821 .addReg(ZeroReg).addReg(PtrReg);
8822 BB->addSuccessor(exitMBB);
8827 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8829 } else if (MI->getOpcode() == PPC::FADDrtz) {
8830 // This pseudo performs an FADD with rounding mode temporarily forced
8831 // to round-to-zero. We emit this via custom inserter since the FPSCR
8832 // is not modeled at the SelectionDAG level.
8833 unsigned Dest = MI->getOperand(0).getReg();
8834 unsigned Src1 = MI->getOperand(1).getReg();
8835 unsigned Src2 = MI->getOperand(2).getReg();
8836 DebugLoc dl = MI->getDebugLoc();
8838 MachineRegisterInfo &RegInfo = F->getRegInfo();
8839 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8841 // Save FPSCR value.
8842 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8844 // Set rounding mode to round-to-zero.
8845 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8846 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8848 // Perform addition.
8849 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8851 // Restore FPSCR value.
8852 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8853 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8854 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8855 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8856 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8857 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8858 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8859 PPC::ANDIo8 : PPC::ANDIo;
8860 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8861 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8863 MachineRegisterInfo &RegInfo = F->getRegInfo();
8864 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8865 &PPC::GPRCRegClass :
8866 &PPC::G8RCRegClass);
8868 DebugLoc dl = MI->getDebugLoc();
8869 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8870 .addReg(MI->getOperand(1).getReg()).addImm(1);
8871 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8872 MI->getOperand(0).getReg())
8873 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8874 } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8875 DebugLoc Dl = MI->getDebugLoc();
8876 MachineRegisterInfo &RegInfo = F->getRegInfo();
8877 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8878 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8881 llvm_unreachable("Unexpected instr type to insert");
8884 MI->eraseFromParent(); // The pseudo instruction is gone now.
8888 //===----------------------------------------------------------------------===//
8889 // Target Optimization Hooks
8890 //===----------------------------------------------------------------------===//
8892 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8893 DAGCombinerInfo &DCI,
8894 unsigned &RefinementSteps,
8895 bool &UseOneConstNR) const {
8896 EVT VT = Operand.getValueType();
8897 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8898 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8899 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8900 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8901 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8902 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8903 // Convergence is quadratic, so we essentially double the number of digits
8904 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8905 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8906 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8907 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8908 if (VT.getScalarType() == MVT::f64)
8910 UseOneConstNR = true;
8911 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8916 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8917 DAGCombinerInfo &DCI,
8918 unsigned &RefinementSteps) const {
8919 EVT VT = Operand.getValueType();
8920 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8921 (VT == MVT::f64 && Subtarget.hasFRE()) ||
8922 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8923 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8924 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8925 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8926 // Convergence is quadratic, so we essentially double the number of digits
8927 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8928 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8929 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8930 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8931 if (VT.getScalarType() == MVT::f64)
8933 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8938 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8939 // Note: This functionality is used only when unsafe-fp-math is enabled, and
8940 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8941 // enabled for division), this functionality is redundant with the default
8942 // combiner logic (once the division -> reciprocal/multiply transformation
8943 // has taken place). As a result, this matters more for older cores than for
8946 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8947 // reciprocal if there are two or more FDIVs (for embedded cores with only
8948 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8949 switch (Subtarget.getDarwinDirective()) {
8951 return NumUsers > 2;
8954 case PPC::DIR_E500mc:
8955 case PPC::DIR_E5500:
8956 return NumUsers > 1;
8960 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8961 unsigned Bytes, int Dist,
8962 SelectionDAG &DAG) {
8963 if (VT.getSizeInBits() / 8 != Bytes)
8966 SDValue BaseLoc = Base->getBasePtr();
8967 if (Loc.getOpcode() == ISD::FrameIndex) {
8968 if (BaseLoc.getOpcode() != ISD::FrameIndex)
8970 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8971 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
8972 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8973 int FS = MFI->getObjectSize(FI);
8974 int BFS = MFI->getObjectSize(BFI);
8975 if (FS != BFS || FS != (int)Bytes) return false;
8976 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8980 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8981 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8985 const GlobalValue *GV1 = nullptr;
8986 const GlobalValue *GV2 = nullptr;
8987 int64_t Offset1 = 0;
8988 int64_t Offset2 = 0;
8989 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8990 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8991 if (isGA1 && isGA2 && GV1 == GV2)
8992 return Offset1 == (Offset2 + Dist*Bytes);
8996 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8997 // not enforce equality of the chain operands.
8998 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8999 unsigned Bytes, int Dist,
9000 SelectionDAG &DAG) {
9001 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9002 EVT VT = LS->getMemoryVT();
9003 SDValue Loc = LS->getBasePtr();
9004 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9007 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9009 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9010 default: return false;
9011 case Intrinsic::ppc_qpx_qvlfd:
9012 case Intrinsic::ppc_qpx_qvlfda:
9015 case Intrinsic::ppc_qpx_qvlfs:
9016 case Intrinsic::ppc_qpx_qvlfsa:
9019 case Intrinsic::ppc_qpx_qvlfcd:
9020 case Intrinsic::ppc_qpx_qvlfcda:
9023 case Intrinsic::ppc_qpx_qvlfcs:
9024 case Intrinsic::ppc_qpx_qvlfcsa:
9027 case Intrinsic::ppc_qpx_qvlfiwa:
9028 case Intrinsic::ppc_qpx_qvlfiwz:
9029 case Intrinsic::ppc_altivec_lvx:
9030 case Intrinsic::ppc_altivec_lvxl:
9031 case Intrinsic::ppc_vsx_lxvw4x:
9034 case Intrinsic::ppc_vsx_lxvd2x:
9037 case Intrinsic::ppc_altivec_lvebx:
9040 case Intrinsic::ppc_altivec_lvehx:
9043 case Intrinsic::ppc_altivec_lvewx:
9048 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9051 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9053 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9054 default: return false;
9055 case Intrinsic::ppc_qpx_qvstfd:
9056 case Intrinsic::ppc_qpx_qvstfda:
9059 case Intrinsic::ppc_qpx_qvstfs:
9060 case Intrinsic::ppc_qpx_qvstfsa:
9063 case Intrinsic::ppc_qpx_qvstfcd:
9064 case Intrinsic::ppc_qpx_qvstfcda:
9067 case Intrinsic::ppc_qpx_qvstfcs:
9068 case Intrinsic::ppc_qpx_qvstfcsa:
9071 case Intrinsic::ppc_qpx_qvstfiw:
9072 case Intrinsic::ppc_qpx_qvstfiwa:
9073 case Intrinsic::ppc_altivec_stvx:
9074 case Intrinsic::ppc_altivec_stvxl:
9075 case Intrinsic::ppc_vsx_stxvw4x:
9078 case Intrinsic::ppc_vsx_stxvd2x:
9081 case Intrinsic::ppc_altivec_stvebx:
9084 case Intrinsic::ppc_altivec_stvehx:
9087 case Intrinsic::ppc_altivec_stvewx:
9092 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9098 // Return true is there is a nearyby consecutive load to the one provided
9099 // (regardless of alignment). We search up and down the chain, looking though
9100 // token factors and other loads (but nothing else). As a result, a true result
9101 // indicates that it is safe to create a new consecutive load adjacent to the
9103 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9104 SDValue Chain = LD->getChain();
9105 EVT VT = LD->getMemoryVT();
9107 SmallSet<SDNode *, 16> LoadRoots;
9108 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9109 SmallSet<SDNode *, 16> Visited;
9111 // First, search up the chain, branching to follow all token-factor operands.
9112 // If we find a consecutive load, then we're done, otherwise, record all
9113 // nodes just above the top-level loads and token factors.
9114 while (!Queue.empty()) {
9115 SDNode *ChainNext = Queue.pop_back_val();
9116 if (!Visited.insert(ChainNext).second)
9119 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9120 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9123 if (!Visited.count(ChainLD->getChain().getNode()))
9124 Queue.push_back(ChainLD->getChain().getNode());
9125 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9126 for (const SDUse &O : ChainNext->ops())
9127 if (!Visited.count(O.getNode()))
9128 Queue.push_back(O.getNode());
9130 LoadRoots.insert(ChainNext);
9133 // Second, search down the chain, starting from the top-level nodes recorded
9134 // in the first phase. These top-level nodes are the nodes just above all
9135 // loads and token factors. Starting with their uses, recursively look though
9136 // all loads (just the chain uses) and token factors to find a consecutive
9141 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9142 IE = LoadRoots.end(); I != IE; ++I) {
9143 Queue.push_back(*I);
9145 while (!Queue.empty()) {
9146 SDNode *LoadRoot = Queue.pop_back_val();
9147 if (!Visited.insert(LoadRoot).second)
9150 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9151 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9154 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9155 UE = LoadRoot->use_end(); UI != UE; ++UI)
9156 if (((isa<MemSDNode>(*UI) &&
9157 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9158 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9159 Queue.push_back(*UI);
9166 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9167 DAGCombinerInfo &DCI) const {
9168 SelectionDAG &DAG = DCI.DAG;
9171 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9172 // If we're tracking CR bits, we need to be careful that we don't have:
9173 // trunc(binary-ops(zext(x), zext(y)))
9175 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9176 // such that we're unnecessarily moving things into GPRs when it would be
9177 // better to keep them in CR bits.
9179 // Note that trunc here can be an actual i1 trunc, or can be the effective
9180 // truncation that comes from a setcc or select_cc.
9181 if (N->getOpcode() == ISD::TRUNCATE &&
9182 N->getValueType(0) != MVT::i1)
9185 if (N->getOperand(0).getValueType() != MVT::i32 &&
9186 N->getOperand(0).getValueType() != MVT::i64)
9189 if (N->getOpcode() == ISD::SETCC ||
9190 N->getOpcode() == ISD::SELECT_CC) {
9191 // If we're looking at a comparison, then we need to make sure that the
9192 // high bits (all except for the first) don't matter the result.
9194 cast<CondCodeSDNode>(N->getOperand(
9195 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9196 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9198 if (ISD::isSignedIntSetCC(CC)) {
9199 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9200 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9202 } else if (ISD::isUnsignedIntSetCC(CC)) {
9203 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9204 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9205 !DAG.MaskedValueIsZero(N->getOperand(1),
9206 APInt::getHighBitsSet(OpBits, OpBits-1)))
9209 // This is neither a signed nor an unsigned comparison, just make sure
9210 // that the high bits are equal.
9211 APInt Op1Zero, Op1One;
9212 APInt Op2Zero, Op2One;
9213 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9214 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9216 // We don't really care about what is known about the first bit (if
9217 // anything), so clear it in all masks prior to comparing them.
9218 Op1Zero.clearBit(0); Op1One.clearBit(0);
9219 Op2Zero.clearBit(0); Op2One.clearBit(0);
9221 if (Op1Zero != Op2Zero || Op1One != Op2One)
9226 // We now know that the higher-order bits are irrelevant, we just need to
9227 // make sure that all of the intermediate operations are bit operations, and
9228 // all inputs are extensions.
9229 if (N->getOperand(0).getOpcode() != ISD::AND &&
9230 N->getOperand(0).getOpcode() != ISD::OR &&
9231 N->getOperand(0).getOpcode() != ISD::XOR &&
9232 N->getOperand(0).getOpcode() != ISD::SELECT &&
9233 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9234 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9235 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9236 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9237 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9240 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9241 N->getOperand(1).getOpcode() != ISD::AND &&
9242 N->getOperand(1).getOpcode() != ISD::OR &&
9243 N->getOperand(1).getOpcode() != ISD::XOR &&
9244 N->getOperand(1).getOpcode() != ISD::SELECT &&
9245 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9246 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9247 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9248 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9249 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9252 SmallVector<SDValue, 4> Inputs;
9253 SmallVector<SDValue, 8> BinOps, PromOps;
9254 SmallPtrSet<SDNode *, 16> Visited;
9256 for (unsigned i = 0; i < 2; ++i) {
9257 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9258 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9259 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9260 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9261 isa<ConstantSDNode>(N->getOperand(i)))
9262 Inputs.push_back(N->getOperand(i));
9264 BinOps.push_back(N->getOperand(i));
9266 if (N->getOpcode() == ISD::TRUNCATE)
9270 // Visit all inputs, collect all binary operations (and, or, xor and
9271 // select) that are all fed by extensions.
9272 while (!BinOps.empty()) {
9273 SDValue BinOp = BinOps.back();
9276 if (!Visited.insert(BinOp.getNode()).second)
9279 PromOps.push_back(BinOp);
9281 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9282 // The condition of the select is not promoted.
9283 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9285 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9288 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9289 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9290 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9291 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9292 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9293 Inputs.push_back(BinOp.getOperand(i));
9294 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9295 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9296 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9297 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9298 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9299 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9300 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9301 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9302 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9303 BinOps.push_back(BinOp.getOperand(i));
9305 // We have an input that is not an extension or another binary
9306 // operation; we'll abort this transformation.
9312 // Make sure that this is a self-contained cluster of operations (which
9313 // is not quite the same thing as saying that everything has only one
9315 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9316 if (isa<ConstantSDNode>(Inputs[i]))
9319 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9320 UE = Inputs[i].getNode()->use_end();
9323 if (User != N && !Visited.count(User))
9326 // Make sure that we're not going to promote the non-output-value
9327 // operand(s) or SELECT or SELECT_CC.
9328 // FIXME: Although we could sometimes handle this, and it does occur in
9329 // practice that one of the condition inputs to the select is also one of
9330 // the outputs, we currently can't deal with this.
9331 if (User->getOpcode() == ISD::SELECT) {
9332 if (User->getOperand(0) == Inputs[i])
9334 } else if (User->getOpcode() == ISD::SELECT_CC) {
9335 if (User->getOperand(0) == Inputs[i] ||
9336 User->getOperand(1) == Inputs[i])
9342 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9343 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9344 UE = PromOps[i].getNode()->use_end();
9347 if (User != N && !Visited.count(User))
9350 // Make sure that we're not going to promote the non-output-value
9351 // operand(s) or SELECT or SELECT_CC.
9352 // FIXME: Although we could sometimes handle this, and it does occur in
9353 // practice that one of the condition inputs to the select is also one of
9354 // the outputs, we currently can't deal with this.
9355 if (User->getOpcode() == ISD::SELECT) {
9356 if (User->getOperand(0) == PromOps[i])
9358 } else if (User->getOpcode() == ISD::SELECT_CC) {
9359 if (User->getOperand(0) == PromOps[i] ||
9360 User->getOperand(1) == PromOps[i])
9366 // Replace all inputs with the extension operand.
9367 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9368 // Constants may have users outside the cluster of to-be-promoted nodes,
9369 // and so we need to replace those as we do the promotions.
9370 if (isa<ConstantSDNode>(Inputs[i]))
9373 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9376 // Replace all operations (these are all the same, but have a different
9377 // (i1) return type). DAG.getNode will validate that the types of
9378 // a binary operator match, so go through the list in reverse so that
9379 // we've likely promoted both operands first. Any intermediate truncations or
9380 // extensions disappear.
9381 while (!PromOps.empty()) {
9382 SDValue PromOp = PromOps.back();
9385 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9386 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9387 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9388 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9389 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9390 PromOp.getOperand(0).getValueType() != MVT::i1) {
9391 // The operand is not yet ready (see comment below).
9392 PromOps.insert(PromOps.begin(), PromOp);
9396 SDValue RepValue = PromOp.getOperand(0);
9397 if (isa<ConstantSDNode>(RepValue))
9398 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9400 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9405 switch (PromOp.getOpcode()) {
9406 default: C = 0; break;
9407 case ISD::SELECT: C = 1; break;
9408 case ISD::SELECT_CC: C = 2; break;
9411 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9412 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9413 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9414 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9415 // The to-be-promoted operands of this node have not yet been
9416 // promoted (this should be rare because we're going through the
9417 // list backward, but if one of the operands has several users in
9418 // this cluster of to-be-promoted nodes, it is possible).
9419 PromOps.insert(PromOps.begin(), PromOp);
9423 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9424 PromOp.getNode()->op_end());
9426 // If there are any constant inputs, make sure they're replaced now.
9427 for (unsigned i = 0; i < 2; ++i)
9428 if (isa<ConstantSDNode>(Ops[C+i]))
9429 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9431 DAG.ReplaceAllUsesOfValueWith(PromOp,
9432 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9435 // Now we're left with the initial truncation itself.
9436 if (N->getOpcode() == ISD::TRUNCATE)
9437 return N->getOperand(0);
9439 // Otherwise, this is a comparison. The operands to be compared have just
9440 // changed type (to i1), but everything else is the same.
9441 return SDValue(N, 0);
9444 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9445 DAGCombinerInfo &DCI) const {
9446 SelectionDAG &DAG = DCI.DAG;
9449 // If we're tracking CR bits, we need to be careful that we don't have:
9450 // zext(binary-ops(trunc(x), trunc(y)))
9452 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9453 // such that we're unnecessarily moving things into CR bits that can more
9454 // efficiently stay in GPRs. Note that if we're not certain that the high
9455 // bits are set as required by the final extension, we still may need to do
9456 // some masking to get the proper behavior.
9458 // This same functionality is important on PPC64 when dealing with
9459 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9460 // the return values of functions. Because it is so similar, it is handled
9463 if (N->getValueType(0) != MVT::i32 &&
9464 N->getValueType(0) != MVT::i64)
9467 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9468 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9471 if (N->getOperand(0).getOpcode() != ISD::AND &&
9472 N->getOperand(0).getOpcode() != ISD::OR &&
9473 N->getOperand(0).getOpcode() != ISD::XOR &&
9474 N->getOperand(0).getOpcode() != ISD::SELECT &&
9475 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9478 SmallVector<SDValue, 4> Inputs;
9479 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9480 SmallPtrSet<SDNode *, 16> Visited;
9482 // Visit all inputs, collect all binary operations (and, or, xor and
9483 // select) that are all fed by truncations.
9484 while (!BinOps.empty()) {
9485 SDValue BinOp = BinOps.back();
9488 if (!Visited.insert(BinOp.getNode()).second)
9491 PromOps.push_back(BinOp);
9493 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9494 // The condition of the select is not promoted.
9495 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9497 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9500 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9501 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9502 Inputs.push_back(BinOp.getOperand(i));
9503 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9504 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9505 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9506 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9507 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9508 BinOps.push_back(BinOp.getOperand(i));
9510 // We have an input that is not a truncation or another binary
9511 // operation; we'll abort this transformation.
9517 // The operands of a select that must be truncated when the select is
9518 // promoted because the operand is actually part of the to-be-promoted set.
9519 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9521 // Make sure that this is a self-contained cluster of operations (which
9522 // is not quite the same thing as saying that everything has only one
9524 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9525 if (isa<ConstantSDNode>(Inputs[i]))
9528 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9529 UE = Inputs[i].getNode()->use_end();
9532 if (User != N && !Visited.count(User))
9535 // If we're going to promote the non-output-value operand(s) or SELECT or
9536 // SELECT_CC, record them for truncation.
9537 if (User->getOpcode() == ISD::SELECT) {
9538 if (User->getOperand(0) == Inputs[i])
9539 SelectTruncOp[0].insert(std::make_pair(User,
9540 User->getOperand(0).getValueType()));
9541 } else if (User->getOpcode() == ISD::SELECT_CC) {
9542 if (User->getOperand(0) == Inputs[i])
9543 SelectTruncOp[0].insert(std::make_pair(User,
9544 User->getOperand(0).getValueType()));
9545 if (User->getOperand(1) == Inputs[i])
9546 SelectTruncOp[1].insert(std::make_pair(User,
9547 User->getOperand(1).getValueType()));
9552 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9553 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9554 UE = PromOps[i].getNode()->use_end();
9557 if (User != N && !Visited.count(User))
9560 // If we're going to promote the non-output-value operand(s) or SELECT or
9561 // SELECT_CC, record them for truncation.
9562 if (User->getOpcode() == ISD::SELECT) {
9563 if (User->getOperand(0) == PromOps[i])
9564 SelectTruncOp[0].insert(std::make_pair(User,
9565 User->getOperand(0).getValueType()));
9566 } else if (User->getOpcode() == ISD::SELECT_CC) {
9567 if (User->getOperand(0) == PromOps[i])
9568 SelectTruncOp[0].insert(std::make_pair(User,
9569 User->getOperand(0).getValueType()));
9570 if (User->getOperand(1) == PromOps[i])
9571 SelectTruncOp[1].insert(std::make_pair(User,
9572 User->getOperand(1).getValueType()));
9577 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9578 bool ReallyNeedsExt = false;
9579 if (N->getOpcode() != ISD::ANY_EXTEND) {
9580 // If all of the inputs are not already sign/zero extended, then
9581 // we'll still need to do that at the end.
9582 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9583 if (isa<ConstantSDNode>(Inputs[i]))
9587 Inputs[i].getOperand(0).getValueSizeInBits();
9588 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9590 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9591 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9592 APInt::getHighBitsSet(OpBits,
9593 OpBits-PromBits))) ||
9594 (N->getOpcode() == ISD::SIGN_EXTEND &&
9595 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9596 (OpBits-(PromBits-1)))) {
9597 ReallyNeedsExt = true;
9603 // Replace all inputs, either with the truncation operand, or a
9604 // truncation or extension to the final output type.
9605 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9606 // Constant inputs need to be replaced with the to-be-promoted nodes that
9607 // use them because they might have users outside of the cluster of
9609 if (isa<ConstantSDNode>(Inputs[i]))
9612 SDValue InSrc = Inputs[i].getOperand(0);
9613 if (Inputs[i].getValueType() == N->getValueType(0))
9614 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9615 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9616 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9617 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9618 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9619 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9620 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9622 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9623 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9626 // Replace all operations (these are all the same, but have a different
9627 // (promoted) return type). DAG.getNode will validate that the types of
9628 // a binary operator match, so go through the list in reverse so that
9629 // we've likely promoted both operands first.
9630 while (!PromOps.empty()) {
9631 SDValue PromOp = PromOps.back();
9635 switch (PromOp.getOpcode()) {
9636 default: C = 0; break;
9637 case ISD::SELECT: C = 1; break;
9638 case ISD::SELECT_CC: C = 2; break;
9641 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9642 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9643 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9644 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9645 // The to-be-promoted operands of this node have not yet been
9646 // promoted (this should be rare because we're going through the
9647 // list backward, but if one of the operands has several users in
9648 // this cluster of to-be-promoted nodes, it is possible).
9649 PromOps.insert(PromOps.begin(), PromOp);
9653 // For SELECT and SELECT_CC nodes, we do a similar check for any
9654 // to-be-promoted comparison inputs.
9655 if (PromOp.getOpcode() == ISD::SELECT ||
9656 PromOp.getOpcode() == ISD::SELECT_CC) {
9657 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9658 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9659 (SelectTruncOp[1].count(PromOp.getNode()) &&
9660 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9661 PromOps.insert(PromOps.begin(), PromOp);
9666 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9667 PromOp.getNode()->op_end());
9669 // If this node has constant inputs, then they'll need to be promoted here.
9670 for (unsigned i = 0; i < 2; ++i) {
9671 if (!isa<ConstantSDNode>(Ops[C+i]))
9673 if (Ops[C+i].getValueType() == N->getValueType(0))
9676 if (N->getOpcode() == ISD::SIGN_EXTEND)
9677 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9678 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9679 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9681 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9684 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9685 // truncate them again to the original value type.
9686 if (PromOp.getOpcode() == ISD::SELECT ||
9687 PromOp.getOpcode() == ISD::SELECT_CC) {
9688 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9689 if (SI0 != SelectTruncOp[0].end())
9690 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9691 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9692 if (SI1 != SelectTruncOp[1].end())
9693 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9696 DAG.ReplaceAllUsesOfValueWith(PromOp,
9697 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9700 // Now we're left with the initial extension itself.
9701 if (!ReallyNeedsExt)
9702 return N->getOperand(0);
9704 // To zero extend, just mask off everything except for the first bit (in the
9706 if (N->getOpcode() == ISD::ZERO_EXTEND)
9707 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9708 DAG.getConstant(APInt::getLowBitsSet(
9709 N->getValueSizeInBits(0), PromBits),
9710 dl, N->getValueType(0)));
9712 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9713 "Invalid extension type");
9714 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9716 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9717 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
9718 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9719 N->getOperand(0), ShiftCst), ShiftCst);
9722 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9723 DAGCombinerInfo &DCI) const {
9724 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9725 N->getOpcode() == ISD::UINT_TO_FP) &&
9726 "Need an int -> FP conversion node here");
9728 if (!Subtarget.has64BitSupport())
9731 SelectionDAG &DAG = DCI.DAG;
9735 // Don't handle ppc_fp128 here or i1 conversions.
9736 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9738 if (Op.getOperand(0).getValueType() == MVT::i1)
9741 // For i32 intermediate values, unfortunately, the conversion functions
9742 // leave the upper 32 bits of the value are undefined. Within the set of
9743 // scalar instructions, we have no method for zero- or sign-extending the
9744 // value. Thus, we cannot handle i32 intermediate values here.
9745 if (Op.getOperand(0).getValueType() == MVT::i32)
9748 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9749 "UINT_TO_FP is supported only with FPCVT");
9751 // If we have FCFIDS, then use it when converting to single-precision.
9752 // Otherwise, convert to double-precision and then round.
9753 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9754 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9756 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9758 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9762 // If we're converting from a float, to an int, and back to a float again,
9763 // then we don't need the store/load pair at all.
9764 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9765 Subtarget.hasFPCVT()) ||
9766 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9767 SDValue Src = Op.getOperand(0).getOperand(0);
9768 if (Src.getValueType() == MVT::f32) {
9769 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9770 DCI.AddToWorklist(Src.getNode());
9774 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9777 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9778 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9780 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9781 FP = DAG.getNode(ISD::FP_ROUND, dl,
9782 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
9783 DCI.AddToWorklist(FP.getNode());
9792 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9793 // builtins) into loads with swaps.
9794 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9795 DAGCombinerInfo &DCI) const {
9796 SelectionDAG &DAG = DCI.DAG;
9800 MachineMemOperand *MMO;
9802 switch (N->getOpcode()) {
9804 llvm_unreachable("Unexpected opcode for little endian VSX load");
9806 LoadSDNode *LD = cast<LoadSDNode>(N);
9807 Chain = LD->getChain();
9808 Base = LD->getBasePtr();
9809 MMO = LD->getMemOperand();
9810 // If the MMO suggests this isn't a load of a full vector, leave
9811 // things alone. For a built-in, we have to make the change for
9812 // correctness, so if there is a size problem that will be a bug.
9813 if (MMO->getSize() < 16)
9817 case ISD::INTRINSIC_W_CHAIN: {
9818 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9819 Chain = Intrin->getChain();
9820 Base = Intrin->getBasePtr();
9821 MMO = Intrin->getMemOperand();
9826 MVT VecTy = N->getValueType(0).getSimpleVT();
9827 SDValue LoadOps[] = { Chain, Base };
9828 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9829 DAG.getVTList(VecTy, MVT::Other),
9830 LoadOps, VecTy, MMO);
9831 DCI.AddToWorklist(Load.getNode());
9832 Chain = Load.getValue(1);
9833 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9834 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9835 DCI.AddToWorklist(Swap.getNode());
9839 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9840 // builtins) into stores with swaps.
9841 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9842 DAGCombinerInfo &DCI) const {
9843 SelectionDAG &DAG = DCI.DAG;
9848 MachineMemOperand *MMO;
9850 switch (N->getOpcode()) {
9852 llvm_unreachable("Unexpected opcode for little endian VSX store");
9854 StoreSDNode *ST = cast<StoreSDNode>(N);
9855 Chain = ST->getChain();
9856 Base = ST->getBasePtr();
9857 MMO = ST->getMemOperand();
9859 // If the MMO suggests this isn't a store of a full vector, leave
9860 // things alone. For a built-in, we have to make the change for
9861 // correctness, so if there is a size problem that will be a bug.
9862 if (MMO->getSize() < 16)
9866 case ISD::INTRINSIC_VOID: {
9867 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9868 Chain = Intrin->getChain();
9869 // Intrin->getBasePtr() oddly does not get what we want.
9870 Base = Intrin->getOperand(3);
9871 MMO = Intrin->getMemOperand();
9877 SDValue Src = N->getOperand(SrcOpnd);
9878 MVT VecTy = Src.getValueType().getSimpleVT();
9879 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9880 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9881 DCI.AddToWorklist(Swap.getNode());
9882 Chain = Swap.getValue(1);
9883 SDValue StoreOps[] = { Chain, Swap, Base };
9884 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9885 DAG.getVTList(MVT::Other),
9886 StoreOps, VecTy, MMO);
9887 DCI.AddToWorklist(Store.getNode());
9891 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9892 DAGCombinerInfo &DCI) const {
9893 SelectionDAG &DAG = DCI.DAG;
9895 switch (N->getOpcode()) {
9898 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9899 if (C->isNullValue()) // 0 << V -> 0.
9900 return N->getOperand(0);
9904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9905 if (C->isNullValue()) // 0 >>u V -> 0.
9906 return N->getOperand(0);
9910 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9911 if (C->isNullValue() || // 0 >>s V -> 0.
9912 C->isAllOnesValue()) // -1 >>s V -> -1.
9913 return N->getOperand(0);
9916 case ISD::SIGN_EXTEND:
9917 case ISD::ZERO_EXTEND:
9918 case ISD::ANY_EXTEND:
9919 return DAGCombineExtBoolTrunc(N, DCI);
9922 case ISD::SELECT_CC:
9923 return DAGCombineTruncBoolExt(N, DCI);
9924 case ISD::SINT_TO_FP:
9925 case ISD::UINT_TO_FP:
9926 return combineFPToIntToFP(N, DCI);
9928 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9929 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9930 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9931 N->getOperand(1).getValueType() == MVT::i32 &&
9932 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9933 SDValue Val = N->getOperand(1).getOperand(0);
9934 if (Val.getValueType() == MVT::f32) {
9935 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9936 DCI.AddToWorklist(Val.getNode());
9938 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9939 DCI.AddToWorklist(Val.getNode());
9942 N->getOperand(0), Val, N->getOperand(2),
9943 DAG.getValueType(N->getOperand(1).getValueType())
9946 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9947 DAG.getVTList(MVT::Other), Ops,
9948 cast<StoreSDNode>(N)->getMemoryVT(),
9949 cast<StoreSDNode>(N)->getMemOperand());
9950 DCI.AddToWorklist(Val.getNode());
9954 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9955 if (cast<StoreSDNode>(N)->isUnindexed() &&
9956 N->getOperand(1).getOpcode() == ISD::BSWAP &&
9957 N->getOperand(1).getNode()->hasOneUse() &&
9958 (N->getOperand(1).getValueType() == MVT::i32 ||
9959 N->getOperand(1).getValueType() == MVT::i16 ||
9960 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9961 N->getOperand(1).getValueType() == MVT::i64))) {
9962 SDValue BSwapOp = N->getOperand(1).getOperand(0);
9963 // Do an any-extend to 32-bits if this is a half-word input.
9964 if (BSwapOp.getValueType() == MVT::i16)
9965 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9968 N->getOperand(0), BSwapOp, N->getOperand(2),
9969 DAG.getValueType(N->getOperand(1).getValueType())
9972 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9973 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9974 cast<StoreSDNode>(N)->getMemOperand());
9977 // For little endian, VSX stores require generating xxswapd/lxvd2x.
9978 EVT VT = N->getOperand(1).getValueType();
9979 if (VT.isSimple()) {
9980 MVT StoreVT = VT.getSimpleVT();
9981 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9982 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9983 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9984 return expandVSXStoreForLE(N, DCI);
9989 LoadSDNode *LD = cast<LoadSDNode>(N);
9990 EVT VT = LD->getValueType(0);
9992 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9993 if (VT.isSimple()) {
9994 MVT LoadVT = VT.getSimpleVT();
9995 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9996 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9997 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9998 return expandVSXLoadForLE(N, DCI);
10001 EVT MemVT = LD->getMemoryVT();
10002 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10003 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
10004 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10005 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
10006 if (LD->isUnindexed() && VT.isVector() &&
10007 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10008 // P8 and later hardware should just use LOAD.
10009 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10010 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10011 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10012 LD->getAlignment() >= ScalarABIAlignment)) &&
10013 LD->getAlignment() < ABIAlignment) {
10014 // This is a type-legal unaligned Altivec or QPX load.
10015 SDValue Chain = LD->getChain();
10016 SDValue Ptr = LD->getBasePtr();
10017 bool isLittleEndian = Subtarget.isLittleEndian();
10019 // This implements the loading of unaligned vectors as described in
10020 // the venerable Apple Velocity Engine overview. Specifically:
10021 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10022 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10024 // The general idea is to expand a sequence of one or more unaligned
10025 // loads into an alignment-based permutation-control instruction (lvsl
10026 // or lvsr), a series of regular vector loads (which always truncate
10027 // their input address to an aligned address), and a series of
10028 // permutations. The results of these permutations are the requested
10029 // loaded values. The trick is that the last "extra" load is not taken
10030 // from the address you might suspect (sizeof(vector) bytes after the
10031 // last requested load), but rather sizeof(vector) - 1 bytes after the
10032 // last requested vector. The point of this is to avoid a page fault if
10033 // the base address happened to be aligned. This works because if the
10034 // base address is aligned, then adding less than a full vector length
10035 // will cause the last vector in the sequence to be (re)loaded.
10036 // Otherwise, the next vector will be fetched as you might suspect was
10039 // We might be able to reuse the permutation generation from
10040 // a different base address offset from this one by an aligned amount.
10041 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10042 // optimization later.
10043 Intrinsic::ID Intr, IntrLD, IntrPerm;
10044 MVT PermCntlTy, PermTy, LDTy;
10045 if (Subtarget.hasAltivec()) {
10046 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
10047 Intrinsic::ppc_altivec_lvsl;
10048 IntrLD = Intrinsic::ppc_altivec_lvx;
10049 IntrPerm = Intrinsic::ppc_altivec_vperm;
10050 PermCntlTy = MVT::v16i8;
10051 PermTy = MVT::v4i32;
10054 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10055 Intrinsic::ppc_qpx_qvlpcls;
10056 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10057 Intrinsic::ppc_qpx_qvlfs;
10058 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10059 PermCntlTy = MVT::v4f64;
10060 PermTy = MVT::v4f64;
10061 LDTy = MemVT.getSimpleVT();
10064 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10066 // Create the new MMO for the new base load. It is like the original MMO,
10067 // but represents an area in memory almost twice the vector size centered
10068 // on the original address. If the address is unaligned, we might start
10069 // reading up to (sizeof(vector)-1) bytes below the address of the
10070 // original unaligned load.
10071 MachineFunction &MF = DAG.getMachineFunction();
10072 MachineMemOperand *BaseMMO =
10073 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10074 2*MemVT.getStoreSize()-1);
10076 // Create the new base load.
10077 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, dl, getPointerTy());
10078 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10080 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10081 DAG.getVTList(PermTy, MVT::Other),
10082 BaseLoadOps, LDTy, BaseMMO);
10084 // Note that the value of IncOffset (which is provided to the next
10085 // load's pointer info offset value, and thus used to calculate the
10086 // alignment), and the value of IncValue (which is actually used to
10087 // increment the pointer value) are different! This is because we
10088 // require the next load to appear to be aligned, even though it
10089 // is actually offset from the base pointer by a lesser amount.
10090 int IncOffset = VT.getSizeInBits() / 8;
10091 int IncValue = IncOffset;
10093 // Walk (both up and down) the chain looking for another load at the real
10094 // (aligned) offset (the alignment of the other load does not matter in
10095 // this case). If found, then do not use the offset reduction trick, as
10096 // that will prevent the loads from being later combined (as they would
10097 // otherwise be duplicates).
10098 if (!findConsecutiveLoad(LD, DAG))
10101 SDValue Increment = DAG.getConstant(IncValue, dl, getPointerTy());
10102 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10104 MachineMemOperand *ExtraMMO =
10105 MF.getMachineMemOperand(LD->getMemOperand(),
10106 1, 2*MemVT.getStoreSize()-1);
10107 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10108 SDValue ExtraLoad =
10109 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10110 DAG.getVTList(PermTy, MVT::Other),
10111 ExtraLoadOps, LDTy, ExtraMMO);
10113 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10114 BaseLoad.getValue(1), ExtraLoad.getValue(1));
10116 // Because vperm has a big-endian bias, we must reverse the order
10117 // of the input vectors and complement the permute control vector
10118 // when generating little endian code. We have already handled the
10119 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10120 // and ExtraLoad here.
10122 if (isLittleEndian)
10123 Perm = BuildIntrinsicOp(IntrPerm,
10124 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10126 Perm = BuildIntrinsicOp(IntrPerm,
10127 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10130 Perm = Subtarget.hasAltivec() ?
10131 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10132 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10133 DAG.getTargetConstant(1, dl, MVT::i64));
10134 // second argument is 1 because this rounding
10135 // is always exact.
10137 // The output of the permutation is our loaded result, the TokenFactor is
10139 DCI.CombineTo(N, Perm, TF);
10140 return SDValue(N, 0);
10144 case ISD::INTRINSIC_WO_CHAIN: {
10145 bool isLittleEndian = Subtarget.isLittleEndian();
10146 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10147 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10148 : Intrinsic::ppc_altivec_lvsl);
10149 if ((IID == Intr ||
10150 IID == Intrinsic::ppc_qpx_qvlpcld ||
10151 IID == Intrinsic::ppc_qpx_qvlpcls) &&
10152 N->getOperand(1)->getOpcode() == ISD::ADD) {
10153 SDValue Add = N->getOperand(1);
10155 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10156 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10158 if (DAG.MaskedValueIsZero(
10159 Add->getOperand(1),
10160 APInt::getAllOnesValue(Bits /* alignment */)
10162 Add.getValueType().getScalarType().getSizeInBits()))) {
10163 SDNode *BasePtr = Add->getOperand(0).getNode();
10164 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10165 UE = BasePtr->use_end();
10167 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10168 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10169 // We've found another LVSL/LVSR, and this address is an aligned
10170 // multiple of that one. The results will be the same, so use the
10171 // one we've just found instead.
10173 return SDValue(*UI, 0);
10178 if (isa<ConstantSDNode>(Add->getOperand(1))) {
10179 SDNode *BasePtr = Add->getOperand(0).getNode();
10180 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10181 UE = BasePtr->use_end(); UI != UE; ++UI) {
10182 if (UI->getOpcode() == ISD::ADD &&
10183 isa<ConstantSDNode>(UI->getOperand(1)) &&
10184 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10185 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10186 (1ULL << Bits) == 0) {
10187 SDNode *OtherAdd = *UI;
10188 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10189 VE = OtherAdd->use_end(); VI != VE; ++VI) {
10190 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10191 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10192 return SDValue(*VI, 0);
10202 case ISD::INTRINSIC_W_CHAIN: {
10203 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10204 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10205 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10208 case Intrinsic::ppc_vsx_lxvw4x:
10209 case Intrinsic::ppc_vsx_lxvd2x:
10210 return expandVSXLoadForLE(N, DCI);
10215 case ISD::INTRINSIC_VOID: {
10216 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10217 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10218 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10221 case Intrinsic::ppc_vsx_stxvw4x:
10222 case Intrinsic::ppc_vsx_stxvd2x:
10223 return expandVSXStoreForLE(N, DCI);
10229 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10230 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10231 N->getOperand(0).hasOneUse() &&
10232 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10233 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10234 N->getValueType(0) == MVT::i64))) {
10235 SDValue Load = N->getOperand(0);
10236 LoadSDNode *LD = cast<LoadSDNode>(Load);
10237 // Create the byte-swapping load.
10239 LD->getChain(), // Chain
10240 LD->getBasePtr(), // Ptr
10241 DAG.getValueType(N->getValueType(0)) // VT
10244 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10245 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10246 MVT::i64 : MVT::i32, MVT::Other),
10247 Ops, LD->getMemoryVT(), LD->getMemOperand());
10249 // If this is an i16 load, insert the truncate.
10250 SDValue ResVal = BSLoad;
10251 if (N->getValueType(0) == MVT::i16)
10252 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10254 // First, combine the bswap away. This makes the value produced by the
10256 DCI.CombineTo(N, ResVal);
10258 // Next, combine the load away, we give it a bogus result value but a real
10259 // chain result. The result value is dead because the bswap is dead.
10260 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10262 // Return N so it doesn't get rechecked!
10263 return SDValue(N, 0);
10267 case PPCISD::VCMP: {
10268 // If a VCMPo node already exists with exactly the same operands as this
10269 // node, use its result instead of this node (VCMPo computes both a CR6 and
10270 // a normal output).
10272 if (!N->getOperand(0).hasOneUse() &&
10273 !N->getOperand(1).hasOneUse() &&
10274 !N->getOperand(2).hasOneUse()) {
10276 // Scan all of the users of the LHS, looking for VCMPo's that match.
10277 SDNode *VCMPoNode = nullptr;
10279 SDNode *LHSN = N->getOperand(0).getNode();
10280 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10282 if (UI->getOpcode() == PPCISD::VCMPo &&
10283 UI->getOperand(1) == N->getOperand(1) &&
10284 UI->getOperand(2) == N->getOperand(2) &&
10285 UI->getOperand(0) == N->getOperand(0)) {
10290 // If there is no VCMPo node, or if the flag value has a single use, don't
10292 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10295 // Look at the (necessarily single) use of the flag value. If it has a
10296 // chain, this transformation is more complex. Note that multiple things
10297 // could use the value result, which we should ignore.
10298 SDNode *FlagUser = nullptr;
10299 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10300 FlagUser == nullptr; ++UI) {
10301 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10302 SDNode *User = *UI;
10303 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10304 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10311 // If the user is a MFOCRF instruction, we know this is safe.
10312 // Otherwise we give up for right now.
10313 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10314 return SDValue(VCMPoNode, 0);
10318 case ISD::BRCOND: {
10319 SDValue Cond = N->getOperand(1);
10320 SDValue Target = N->getOperand(2);
10322 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10323 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10324 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10326 // We now need to make the intrinsic dead (it cannot be instruction
10328 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10329 assert(Cond.getNode()->hasOneUse() &&
10330 "Counter decrement has more than one use");
10332 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10333 N->getOperand(0), Target);
10338 // If this is a branch on an altivec predicate comparison, lower this so
10339 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10340 // lowering is done pre-legalize, because the legalizer lowers the predicate
10341 // compare down to code that is difficult to reassemble.
10342 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10343 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10345 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10346 // value. If so, pass-through the AND to get to the intrinsic.
10347 if (LHS.getOpcode() == ISD::AND &&
10348 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10349 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10350 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10351 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10352 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10354 LHS = LHS.getOperand(0);
10356 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10357 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10358 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10359 isa<ConstantSDNode>(RHS)) {
10360 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10361 "Counter decrement comparison is not EQ or NE");
10363 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10364 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10365 (CC == ISD::SETNE && !Val);
10367 // We now need to make the intrinsic dead (it cannot be instruction
10369 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10370 assert(LHS.getNode()->hasOneUse() &&
10371 "Counter decrement has more than one use");
10373 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10374 N->getOperand(0), N->getOperand(4));
10380 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10381 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10382 getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10383 assert(isDot && "Can't compare against a vector result!");
10385 // If this is a comparison against something other than 0/1, then we know
10386 // that the condition is never/always true.
10387 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10388 if (Val != 0 && Val != 1) {
10389 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10390 return N->getOperand(0);
10391 // Always !=, turn it into an unconditional branch.
10392 return DAG.getNode(ISD::BR, dl, MVT::Other,
10393 N->getOperand(0), N->getOperand(4));
10396 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10398 // Create the PPCISD altivec 'dot' comparison node.
10400 LHS.getOperand(2), // LHS of compare
10401 LHS.getOperand(3), // RHS of compare
10402 DAG.getConstant(CompareOpc, dl, MVT::i32)
10404 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10405 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10407 // Unpack the result based on how the target uses it.
10408 PPC::Predicate CompOpc;
10409 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10410 default: // Can't happen, don't crash on invalid number though.
10411 case 0: // Branch on the value of the EQ bit of CR6.
10412 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10414 case 1: // Branch on the inverted value of the EQ bit of CR6.
10415 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10417 case 2: // Branch on the value of the LT bit of CR6.
10418 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10420 case 3: // Branch on the inverted value of the LT bit of CR6.
10421 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10425 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10426 DAG.getConstant(CompOpc, dl, MVT::i32),
10427 DAG.getRegister(PPC::CR6, MVT::i32),
10428 N->getOperand(4), CompNode.getValue(1));
10438 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10440 std::vector<SDNode *> *Created) const {
10441 // fold (sdiv X, pow2)
10442 EVT VT = N->getValueType(0);
10443 if (VT == MVT::i64 && !Subtarget.isPPC64())
10445 if ((VT != MVT::i32 && VT != MVT::i64) ||
10446 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10450 SDValue N0 = N->getOperand(0);
10452 bool IsNegPow2 = (-Divisor).isPowerOf2();
10453 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10454 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10456 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10458 Created->push_back(Op.getNode());
10461 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10463 Created->push_back(Op.getNode());
10469 //===----------------------------------------------------------------------===//
10470 // Inline Assembly Support
10471 //===----------------------------------------------------------------------===//
10473 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10476 const SelectionDAG &DAG,
10477 unsigned Depth) const {
10478 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10479 switch (Op.getOpcode()) {
10481 case PPCISD::LBRX: {
10482 // lhbrx is known to have the top bits cleared out.
10483 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10484 KnownZero = 0xFFFF0000;
10487 case ISD::INTRINSIC_WO_CHAIN: {
10488 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10490 case Intrinsic::ppc_altivec_vcmpbfp_p:
10491 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10492 case Intrinsic::ppc_altivec_vcmpequb_p:
10493 case Intrinsic::ppc_altivec_vcmpequh_p:
10494 case Intrinsic::ppc_altivec_vcmpequw_p:
10495 case Intrinsic::ppc_altivec_vcmpequd_p:
10496 case Intrinsic::ppc_altivec_vcmpgefp_p:
10497 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10498 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10499 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10500 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10501 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10502 case Intrinsic::ppc_altivec_vcmpgtub_p:
10503 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10504 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10505 case Intrinsic::ppc_altivec_vcmpgtud_p:
10506 KnownZero = ~1U; // All bits but the low one are known to be zero.
10513 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10514 switch (Subtarget.getDarwinDirective()) {
10517 case PPC::DIR_PWR4:
10518 case PPC::DIR_PWR5:
10519 case PPC::DIR_PWR5X:
10520 case PPC::DIR_PWR6:
10521 case PPC::DIR_PWR6X:
10522 case PPC::DIR_PWR7:
10523 case PPC::DIR_PWR8: {
10527 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10529 // For small loops (between 5 and 8 instructions), align to a 32-byte
10530 // boundary so that the entire loop fits in one instruction-cache line.
10531 uint64_t LoopSize = 0;
10532 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10533 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10534 LoopSize += TII->GetInstSizeInBytes(J);
10536 if (LoopSize > 16 && LoopSize <= 32)
10543 return TargetLowering::getPrefLoopAlignment(ML);
10546 /// getConstraintType - Given a constraint, return the type of
10547 /// constraint it is for this target.
10548 PPCTargetLowering::ConstraintType
10549 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10550 if (Constraint.size() == 1) {
10551 switch (Constraint[0]) {
10558 return C_RegisterClass;
10560 // FIXME: While Z does indicate a memory constraint, it specifically
10561 // indicates an r+r address (used in conjunction with the 'y' modifier
10562 // in the replacement string). Currently, we're forcing the base
10563 // register to be r0 in the asm printer (which is interpreted as zero)
10564 // and forming the complete address in the second register. This is
10568 } else if (Constraint == "wc") { // individual CR bits.
10569 return C_RegisterClass;
10570 } else if (Constraint == "wa" || Constraint == "wd" ||
10571 Constraint == "wf" || Constraint == "ws") {
10572 return C_RegisterClass; // VSX registers.
10574 return TargetLowering::getConstraintType(Constraint);
10577 /// Examine constraint type and operand type and determine a weight value.
10578 /// This object must already have been set up with the operand type
10579 /// and the current alternative constraint selected.
10580 TargetLowering::ConstraintWeight
10581 PPCTargetLowering::getSingleConstraintMatchWeight(
10582 AsmOperandInfo &info, const char *constraint) const {
10583 ConstraintWeight weight = CW_Invalid;
10584 Value *CallOperandVal = info.CallOperandVal;
10585 // If we don't have a value, we can't do a match,
10586 // but allow it at the lowest weight.
10587 if (!CallOperandVal)
10589 Type *type = CallOperandVal->getType();
10591 // Look at the constraint type.
10592 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10593 return CW_Register; // an individual CR bit.
10594 else if ((StringRef(constraint) == "wa" ||
10595 StringRef(constraint) == "wd" ||
10596 StringRef(constraint) == "wf") &&
10597 type->isVectorTy())
10598 return CW_Register;
10599 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10600 return CW_Register;
10602 switch (*constraint) {
10604 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10607 if (type->isIntegerTy())
10608 weight = CW_Register;
10611 if (type->isFloatTy())
10612 weight = CW_Register;
10615 if (type->isDoubleTy())
10616 weight = CW_Register;
10619 if (type->isVectorTy())
10620 weight = CW_Register;
10623 weight = CW_Register;
10626 weight = CW_Memory;
10632 std::pair<unsigned, const TargetRegisterClass *>
10633 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10634 const std::string &Constraint,
10636 if (Constraint.size() == 1) {
10637 // GCC RS6000 Constraint Letters
10638 switch (Constraint[0]) {
10639 case 'b': // R1-R31
10640 if (VT == MVT::i64 && Subtarget.isPPC64())
10641 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10642 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10643 case 'r': // R0-R31
10644 if (VT == MVT::i64 && Subtarget.isPPC64())
10645 return std::make_pair(0U, &PPC::G8RCRegClass);
10646 return std::make_pair(0U, &PPC::GPRCRegClass);
10648 if (VT == MVT::f32 || VT == MVT::i32)
10649 return std::make_pair(0U, &PPC::F4RCRegClass);
10650 if (VT == MVT::f64 || VT == MVT::i64)
10651 return std::make_pair(0U, &PPC::F8RCRegClass);
10652 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10653 return std::make_pair(0U, &PPC::QFRCRegClass);
10654 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10655 return std::make_pair(0U, &PPC::QSRCRegClass);
10658 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10659 return std::make_pair(0U, &PPC::QFRCRegClass);
10660 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10661 return std::make_pair(0U, &PPC::QSRCRegClass);
10662 return std::make_pair(0U, &PPC::VRRCRegClass);
10664 return std::make_pair(0U, &PPC::CRRCRegClass);
10666 } else if (Constraint == "wc") { // an individual CR bit.
10667 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10668 } else if (Constraint == "wa" || Constraint == "wd" ||
10669 Constraint == "wf") {
10670 return std::make_pair(0U, &PPC::VSRCRegClass);
10671 } else if (Constraint == "ws") {
10672 if (VT == MVT::f32)
10673 return std::make_pair(0U, &PPC::VSSRCRegClass);
10675 return std::make_pair(0U, &PPC::VSFRCRegClass);
10678 std::pair<unsigned, const TargetRegisterClass *> R =
10679 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10681 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10682 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10683 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10685 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10686 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10687 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10688 PPC::GPRCRegClass.contains(R.first))
10689 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10690 PPC::sub_32, &PPC::G8RCRegClass),
10691 &PPC::G8RCRegClass);
10693 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10694 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10695 R.first = PPC::CR0;
10696 R.second = &PPC::CRRCRegClass;
10703 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10704 /// vector. If it is invalid, don't add anything to Ops.
10705 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10706 std::string &Constraint,
10707 std::vector<SDValue>&Ops,
10708 SelectionDAG &DAG) const {
10711 // Only support length 1 constraints.
10712 if (Constraint.length() > 1) return;
10714 char Letter = Constraint[0];
10725 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10726 if (!CST) return; // Must be an immediate to match.
10728 int64_t Value = CST->getSExtValue();
10729 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10730 // numbers are printed as such.
10732 default: llvm_unreachable("Unknown constraint letter!");
10733 case 'I': // "I" is a signed 16-bit constant.
10734 if (isInt<16>(Value))
10735 Result = DAG.getTargetConstant(Value, dl, TCVT);
10737 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
10738 if (isShiftedUInt<16, 16>(Value))
10739 Result = DAG.getTargetConstant(Value, dl, TCVT);
10741 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
10742 if (isShiftedInt<16, 16>(Value))
10743 Result = DAG.getTargetConstant(Value, dl, TCVT);
10745 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
10746 if (isUInt<16>(Value))
10747 Result = DAG.getTargetConstant(Value, dl, TCVT);
10749 case 'M': // "M" is a constant that is greater than 31.
10751 Result = DAG.getTargetConstant(Value, dl, TCVT);
10753 case 'N': // "N" is a positive constant that is an exact power of two.
10754 if (Value > 0 && isPowerOf2_64(Value))
10755 Result = DAG.getTargetConstant(Value, dl, TCVT);
10757 case 'O': // "O" is the constant zero.
10759 Result = DAG.getTargetConstant(Value, dl, TCVT);
10761 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
10762 if (isInt<16>(-Value))
10763 Result = DAG.getTargetConstant(Value, dl, TCVT);
10770 if (Result.getNode()) {
10771 Ops.push_back(Result);
10775 // Handle standard constraint letters.
10776 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10779 // isLegalAddressingMode - Return true if the addressing mode represented
10780 // by AM is legal for this target, for a load/store of the specified type.
10781 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10783 // PPC does not allow r+i addressing modes for vectors!
10784 if (Ty->isVectorTy() && AM.BaseOffs != 0)
10787 // PPC allows a sign-extended 16-bit immediate field.
10788 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10791 // No global is ever allowed as a base.
10795 // PPC only support r+r,
10796 switch (AM.Scale) {
10797 case 0: // "r+i" or just "i", depending on HasBaseReg.
10800 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
10802 // Otherwise we have r+r or r+i.
10805 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
10807 // Allow 2*r as r+r.
10810 // No other scales are supported.
10817 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10818 SelectionDAG &DAG) const {
10819 MachineFunction &MF = DAG.getMachineFunction();
10820 MachineFrameInfo *MFI = MF.getFrameInfo();
10821 MFI->setReturnAddressIsTaken(true);
10823 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10827 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10829 // Make sure the function does not optimize away the store of the RA to
10831 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10832 FuncInfo->setLRStoreRequired();
10833 bool isPPC64 = Subtarget.isPPC64();
10836 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10838 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
10839 isPPC64 ? MVT::i64 : MVT::i32);
10840 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10841 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10842 FrameAddr, Offset),
10843 MachinePointerInfo(), false, false, false, 0);
10846 // Just load the return address off the stack.
10847 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10848 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10849 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10852 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10853 SelectionDAG &DAG) const {
10855 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10857 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10858 bool isPPC64 = PtrVT == MVT::i64;
10860 MachineFunction &MF = DAG.getMachineFunction();
10861 MachineFrameInfo *MFI = MF.getFrameInfo();
10862 MFI->setFrameAddressIsTaken(true);
10864 // Naked functions never have a frame pointer, and so we use r1. For all
10865 // other functions, this decision must be delayed until during PEI.
10867 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10868 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10870 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10872 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10875 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10876 FrameAddr, MachinePointerInfo(), false, false,
10881 // FIXME? Maybe this could be a TableGen attribute on some registers and
10882 // this table could be generated automatically from RegInfo.
10883 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10885 bool isPPC64 = Subtarget.isPPC64();
10886 bool isDarwinABI = Subtarget.isDarwinABI();
10888 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10889 (!isPPC64 && VT != MVT::i32))
10890 report_fatal_error("Invalid register global variable type");
10892 bool is64Bit = isPPC64 && VT == MVT::i64;
10893 unsigned Reg = StringSwitch<unsigned>(RegName)
10894 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10895 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10896 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10897 (is64Bit ? PPC::X13 : PPC::R13))
10902 report_fatal_error("Invalid register name global variable");
10906 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10907 // The PowerPC target isn't yet aware of offsets.
10911 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10913 unsigned Intrinsic) const {
10915 switch (Intrinsic) {
10916 case Intrinsic::ppc_qpx_qvlfd:
10917 case Intrinsic::ppc_qpx_qvlfs:
10918 case Intrinsic::ppc_qpx_qvlfcd:
10919 case Intrinsic::ppc_qpx_qvlfcs:
10920 case Intrinsic::ppc_qpx_qvlfiwa:
10921 case Intrinsic::ppc_qpx_qvlfiwz:
10922 case Intrinsic::ppc_altivec_lvx:
10923 case Intrinsic::ppc_altivec_lvxl:
10924 case Intrinsic::ppc_altivec_lvebx:
10925 case Intrinsic::ppc_altivec_lvehx:
10926 case Intrinsic::ppc_altivec_lvewx:
10927 case Intrinsic::ppc_vsx_lxvd2x:
10928 case Intrinsic::ppc_vsx_lxvw4x: {
10930 switch (Intrinsic) {
10931 case Intrinsic::ppc_altivec_lvebx:
10934 case Intrinsic::ppc_altivec_lvehx:
10937 case Intrinsic::ppc_altivec_lvewx:
10940 case Intrinsic::ppc_vsx_lxvd2x:
10943 case Intrinsic::ppc_qpx_qvlfd:
10946 case Intrinsic::ppc_qpx_qvlfs:
10949 case Intrinsic::ppc_qpx_qvlfcd:
10952 case Intrinsic::ppc_qpx_qvlfcs:
10960 Info.opc = ISD::INTRINSIC_W_CHAIN;
10962 Info.ptrVal = I.getArgOperand(0);
10963 Info.offset = -VT.getStoreSize()+1;
10964 Info.size = 2*VT.getStoreSize()-1;
10967 Info.readMem = true;
10968 Info.writeMem = false;
10971 case Intrinsic::ppc_qpx_qvlfda:
10972 case Intrinsic::ppc_qpx_qvlfsa:
10973 case Intrinsic::ppc_qpx_qvlfcda:
10974 case Intrinsic::ppc_qpx_qvlfcsa:
10975 case Intrinsic::ppc_qpx_qvlfiwaa:
10976 case Intrinsic::ppc_qpx_qvlfiwza: {
10978 switch (Intrinsic) {
10979 case Intrinsic::ppc_qpx_qvlfda:
10982 case Intrinsic::ppc_qpx_qvlfsa:
10985 case Intrinsic::ppc_qpx_qvlfcda:
10988 case Intrinsic::ppc_qpx_qvlfcsa:
10996 Info.opc = ISD::INTRINSIC_W_CHAIN;
10998 Info.ptrVal = I.getArgOperand(0);
11000 Info.size = VT.getStoreSize();
11003 Info.readMem = true;
11004 Info.writeMem = false;
11007 case Intrinsic::ppc_qpx_qvstfd:
11008 case Intrinsic::ppc_qpx_qvstfs:
11009 case Intrinsic::ppc_qpx_qvstfcd:
11010 case Intrinsic::ppc_qpx_qvstfcs:
11011 case Intrinsic::ppc_qpx_qvstfiw:
11012 case Intrinsic::ppc_altivec_stvx:
11013 case Intrinsic::ppc_altivec_stvxl:
11014 case Intrinsic::ppc_altivec_stvebx:
11015 case Intrinsic::ppc_altivec_stvehx:
11016 case Intrinsic::ppc_altivec_stvewx:
11017 case Intrinsic::ppc_vsx_stxvd2x:
11018 case Intrinsic::ppc_vsx_stxvw4x: {
11020 switch (Intrinsic) {
11021 case Intrinsic::ppc_altivec_stvebx:
11024 case Intrinsic::ppc_altivec_stvehx:
11027 case Intrinsic::ppc_altivec_stvewx:
11030 case Intrinsic::ppc_vsx_stxvd2x:
11033 case Intrinsic::ppc_qpx_qvstfd:
11036 case Intrinsic::ppc_qpx_qvstfs:
11039 case Intrinsic::ppc_qpx_qvstfcd:
11042 case Intrinsic::ppc_qpx_qvstfcs:
11050 Info.opc = ISD::INTRINSIC_VOID;
11052 Info.ptrVal = I.getArgOperand(1);
11053 Info.offset = -VT.getStoreSize()+1;
11054 Info.size = 2*VT.getStoreSize()-1;
11057 Info.readMem = false;
11058 Info.writeMem = true;
11061 case Intrinsic::ppc_qpx_qvstfda:
11062 case Intrinsic::ppc_qpx_qvstfsa:
11063 case Intrinsic::ppc_qpx_qvstfcda:
11064 case Intrinsic::ppc_qpx_qvstfcsa:
11065 case Intrinsic::ppc_qpx_qvstfiwa: {
11067 switch (Intrinsic) {
11068 case Intrinsic::ppc_qpx_qvstfda:
11071 case Intrinsic::ppc_qpx_qvstfsa:
11074 case Intrinsic::ppc_qpx_qvstfcda:
11077 case Intrinsic::ppc_qpx_qvstfcsa:
11085 Info.opc = ISD::INTRINSIC_VOID;
11087 Info.ptrVal = I.getArgOperand(1);
11089 Info.size = VT.getStoreSize();
11092 Info.readMem = false;
11093 Info.writeMem = true;
11103 /// getOptimalMemOpType - Returns the target specific optimal type for load
11104 /// and store operations as a result of memset, memcpy, and memmove
11105 /// lowering. If DstAlign is zero that means it's safe to destination
11106 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11107 /// means there isn't a need to check it against alignment requirement,
11108 /// probably because the source does not need to be loaded. If 'IsMemset' is
11109 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11110 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11111 /// source is constant so it does not need to be loaded.
11112 /// It returns EVT::Other if the type should be determined using generic
11113 /// target-independent logic.
11114 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11115 unsigned DstAlign, unsigned SrcAlign,
11116 bool IsMemset, bool ZeroMemset,
11118 MachineFunction &MF) const {
11119 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11120 const Function *F = MF.getFunction();
11121 // When expanding a memset, require at least two QPX instructions to cover
11122 // the cost of loading the value to be stored from the constant pool.
11123 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11124 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11125 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11129 // We should use Altivec/VSX loads and stores when available. For unaligned
11130 // addresses, unaligned VSX loads are only fast starting with the P8.
11131 if (Subtarget.hasAltivec() && Size >= 16 &&
11132 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11133 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11137 if (Subtarget.isPPC64()) {
11144 /// \brief Returns true if it is beneficial to convert a load of a constant
11145 /// to just the constant itself.
11146 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11148 assert(Ty->isIntegerTy());
11150 unsigned BitSize = Ty->getPrimitiveSizeInBits();
11151 if (BitSize == 0 || BitSize > 64)
11156 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11157 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11159 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11160 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11161 return NumBits1 == 64 && NumBits2 == 32;
11164 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11165 if (!VT1.isInteger() || !VT2.isInteger())
11167 unsigned NumBits1 = VT1.getSizeInBits();
11168 unsigned NumBits2 = VT2.getSizeInBits();
11169 return NumBits1 == 64 && NumBits2 == 32;
11172 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11173 // Generally speaking, zexts are not free, but they are free when they can be
11174 // folded with other operations.
11175 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11176 EVT MemVT = LD->getMemoryVT();
11177 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11178 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11179 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11180 LD->getExtensionType() == ISD::ZEXTLOAD))
11184 // FIXME: Add other cases...
11185 // - 32-bit shifts with a zext to i64
11186 // - zext after ctlz, bswap, etc.
11187 // - zext after and by a constant mask
11189 return TargetLowering::isZExtFree(Val, VT2);
11192 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11193 assert(VT.isFloatingPoint());
11197 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11198 return isInt<16>(Imm) || isUInt<16>(Imm);
11201 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11202 return isInt<16>(Imm) || isUInt<16>(Imm);
11205 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11208 bool *Fast) const {
11209 if (DisablePPCUnaligned)
11212 // PowerPC supports unaligned memory access for simple non-vector types.
11213 // Although accessing unaligned addresses is not as efficient as accessing
11214 // aligned addresses, it is generally more efficient than manual expansion,
11215 // and generally only traps for software emulation when crossing page
11218 if (!VT.isSimple())
11221 if (VT.getSimpleVT().isVector()) {
11222 if (Subtarget.hasVSX()) {
11223 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11224 VT != MVT::v4f32 && VT != MVT::v4i32)
11231 if (VT == MVT::ppcf128)
11240 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11241 VT = VT.getScalarType();
11243 if (!VT.isSimple())
11246 switch (VT.getSimpleVT().SimpleTy) {
11258 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11259 // LR is a callee-save register, but we must treat it as clobbered by any call
11260 // site. Hence we include LR in the scratch registers, which are in turn added
11261 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11262 // to CTR, which is used by any indirect call.
11263 static const MCPhysReg ScratchRegs[] = {
11264 PPC::X12, PPC::LR8, PPC::CTR8, 0
11267 return ScratchRegs;
11271 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11272 EVT VT , unsigned DefinedValues) const {
11273 if (VT == MVT::v2i64)
11276 if (Subtarget.hasQPX()) {
11277 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11281 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11284 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11285 if (DisableILPPref || Subtarget.enableMachineScheduler())
11286 return TargetLowering::getSchedulingPreference(N);
11291 // Create a fast isel object.
11293 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11294 const TargetLibraryInfo *LibInfo) const {
11295 return PPC::createFastISel(FuncInfo, LibInfo);