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 setOperationAction(ISD::ADD , VT, Legal);
407 setOperationAction(ISD::SUB , VT, Legal);
409 // Vector instructions introduced in P8
410 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
411 setOperationAction(ISD::CTPOP, VT, Legal);
412 setOperationAction(ISD::CTLZ, VT, Legal);
415 setOperationAction(ISD::CTPOP, VT, Expand);
416 setOperationAction(ISD::CTLZ, VT, Expand);
419 // We promote all shuffles to v16i8.
420 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
421 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
423 // We promote all non-typed operations to v4i32.
424 setOperationAction(ISD::AND , VT, Promote);
425 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
426 setOperationAction(ISD::OR , VT, Promote);
427 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
428 setOperationAction(ISD::XOR , VT, Promote);
429 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
430 setOperationAction(ISD::LOAD , VT, Promote);
431 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
432 setOperationAction(ISD::SELECT, VT, Promote);
433 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
434 setOperationAction(ISD::STORE, VT, Promote);
435 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
437 // No other operations are legal.
438 setOperationAction(ISD::MUL , VT, Expand);
439 setOperationAction(ISD::SDIV, VT, Expand);
440 setOperationAction(ISD::SREM, VT, Expand);
441 setOperationAction(ISD::UDIV, VT, Expand);
442 setOperationAction(ISD::UREM, VT, Expand);
443 setOperationAction(ISD::FDIV, VT, Expand);
444 setOperationAction(ISD::FREM, VT, Expand);
445 setOperationAction(ISD::FNEG, VT, Expand);
446 setOperationAction(ISD::FSQRT, VT, Expand);
447 setOperationAction(ISD::FLOG, VT, Expand);
448 setOperationAction(ISD::FLOG10, VT, Expand);
449 setOperationAction(ISD::FLOG2, VT, Expand);
450 setOperationAction(ISD::FEXP, VT, Expand);
451 setOperationAction(ISD::FEXP2, VT, Expand);
452 setOperationAction(ISD::FSIN, VT, Expand);
453 setOperationAction(ISD::FCOS, VT, Expand);
454 setOperationAction(ISD::FABS, VT, Expand);
455 setOperationAction(ISD::FPOWI, VT, Expand);
456 setOperationAction(ISD::FFLOOR, VT, Expand);
457 setOperationAction(ISD::FCEIL, VT, Expand);
458 setOperationAction(ISD::FTRUNC, VT, Expand);
459 setOperationAction(ISD::FRINT, VT, Expand);
460 setOperationAction(ISD::FNEARBYINT, VT, Expand);
461 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
462 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
463 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
464 setOperationAction(ISD::MULHU, VT, Expand);
465 setOperationAction(ISD::MULHS, VT, Expand);
466 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
467 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
468 setOperationAction(ISD::UDIVREM, VT, Expand);
469 setOperationAction(ISD::SDIVREM, VT, Expand);
470 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
471 setOperationAction(ISD::FPOW, VT, Expand);
472 setOperationAction(ISD::BSWAP, VT, Expand);
473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
474 setOperationAction(ISD::CTTZ, VT, Expand);
475 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
476 setOperationAction(ISD::VSELECT, VT, Expand);
477 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
479 for (MVT InnerVT : MVT::vector_valuetypes()) {
480 setTruncStoreAction(VT, InnerVT, Expand);
481 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
482 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
483 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
487 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
488 // with merges, splats, etc.
489 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
491 setOperationAction(ISD::AND , MVT::v4i32, Legal);
492 setOperationAction(ISD::OR , MVT::v4i32, Legal);
493 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
494 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
495 setOperationAction(ISD::SELECT, MVT::v4i32,
496 Subtarget.useCRBits() ? Legal : Expand);
497 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
498 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
499 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
500 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
501 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
502 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
503 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
504 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
505 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
507 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
508 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
509 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
510 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
512 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
513 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
515 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
516 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
517 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
521 if (Subtarget.hasP8Altivec())
522 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
524 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
526 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
527 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
529 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
530 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
532 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
533 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
534 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
535 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
537 // Altivec does not contain unordered floating-point compare instructions
538 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
539 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
540 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
541 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
543 if (Subtarget.hasVSX()) {
544 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
545 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
547 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
548 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
549 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
550 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
551 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
553 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
555 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
556 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
558 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
559 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
561 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
562 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
563 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
564 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
565 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
567 // Share the Altivec comparison restrictions.
568 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
569 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
570 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
571 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
573 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
574 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
576 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
578 if (Subtarget.hasP8Vector())
579 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
581 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
583 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
584 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
586 if (Subtarget.hasP8Altivec()) {
587 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
588 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
589 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
591 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
594 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
595 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
596 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
598 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
600 // VSX v2i64 only supports non-arithmetic operations.
601 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
602 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
605 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
606 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
607 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
608 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
610 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
612 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
613 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
614 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
615 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
617 // Vector operation legalization checks the result type of
618 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
619 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
620 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
621 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
622 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
624 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
627 if (Subtarget.hasP8Altivec()) {
628 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
629 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
633 if (Subtarget.hasQPX()) {
634 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
635 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
636 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
637 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
639 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
640 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
642 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
643 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
645 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
646 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
648 if (!Subtarget.useCRBits())
649 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
650 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
652 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
653 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
654 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
655 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
656 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
660 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
661 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
663 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
664 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
665 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
667 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
668 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
669 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
670 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
671 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
672 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
673 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
674 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
675 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
676 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
677 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
679 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
680 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
682 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
683 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
685 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
687 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
688 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
689 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
690 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
692 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
693 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
695 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
696 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
698 if (!Subtarget.useCRBits())
699 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
700 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
703 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
704 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
705 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
706 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
707 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
708 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
710 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
711 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
713 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
714 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
715 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
716 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
717 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
718 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
719 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
720 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
721 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
722 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
723 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
725 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
726 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
728 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
729 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
731 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
733 setOperationAction(ISD::AND , MVT::v4i1, Legal);
734 setOperationAction(ISD::OR , MVT::v4i1, Legal);
735 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
737 if (!Subtarget.useCRBits())
738 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
739 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
741 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
742 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
744 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
745 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
746 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
748 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
749 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
750 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
752 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
753 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
755 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
757 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
758 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
759 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
760 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
762 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
763 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
764 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
765 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
767 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
768 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
770 // These need to set FE_INEXACT, and so cannot be vectorized here.
771 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
772 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
774 if (TM.Options.UnsafeFPMath) {
775 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
776 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
778 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
779 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
781 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
782 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
784 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
785 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
789 if (Subtarget.has64BitSupport())
790 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
792 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
795 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
796 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
799 setBooleanContents(ZeroOrOneBooleanContent);
801 if (Subtarget.hasAltivec()) {
802 // Altivec instructions set fields to all zeros or all ones.
803 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
807 // These libcalls are not available in 32-bit.
808 setLibcallName(RTLIB::SHL_I128, nullptr);
809 setLibcallName(RTLIB::SRL_I128, nullptr);
810 setLibcallName(RTLIB::SRA_I128, nullptr);
814 setStackPointerRegisterToSaveRestore(PPC::X1);
815 setExceptionPointerRegister(PPC::X3);
816 setExceptionSelectorRegister(PPC::X4);
818 setStackPointerRegisterToSaveRestore(PPC::R1);
819 setExceptionPointerRegister(PPC::R3);
820 setExceptionSelectorRegister(PPC::R4);
823 // We have target-specific dag combine patterns for the following nodes:
824 setTargetDAGCombine(ISD::SINT_TO_FP);
825 if (Subtarget.hasFPCVT())
826 setTargetDAGCombine(ISD::UINT_TO_FP);
827 setTargetDAGCombine(ISD::LOAD);
828 setTargetDAGCombine(ISD::STORE);
829 setTargetDAGCombine(ISD::BR_CC);
830 if (Subtarget.useCRBits())
831 setTargetDAGCombine(ISD::BRCOND);
832 setTargetDAGCombine(ISD::BSWAP);
833 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
834 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
835 setTargetDAGCombine(ISD::INTRINSIC_VOID);
837 setTargetDAGCombine(ISD::SIGN_EXTEND);
838 setTargetDAGCombine(ISD::ZERO_EXTEND);
839 setTargetDAGCombine(ISD::ANY_EXTEND);
841 if (Subtarget.useCRBits()) {
842 setTargetDAGCombine(ISD::TRUNCATE);
843 setTargetDAGCombine(ISD::SETCC);
844 setTargetDAGCombine(ISD::SELECT_CC);
847 // Use reciprocal estimates.
848 if (TM.Options.UnsafeFPMath) {
849 setTargetDAGCombine(ISD::FDIV);
850 setTargetDAGCombine(ISD::FSQRT);
853 // Darwin long double math library functions have $LDBL128 appended.
854 if (Subtarget.isDarwin()) {
855 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
856 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
857 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
858 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
859 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
860 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
861 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
862 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
863 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
864 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
867 // With 32 condition bits, we don't need to sink (and duplicate) compares
868 // aggressively in CodeGenPrep.
869 if (Subtarget.useCRBits()) {
870 setHasMultipleConditionRegisters();
871 setJumpIsExpensive();
874 setMinFunctionAlignment(2);
875 if (Subtarget.isDarwin())
876 setPrefFunctionAlignment(4);
878 switch (Subtarget.getDarwinDirective()) {
882 case PPC::DIR_E500mc:
891 setPrefFunctionAlignment(4);
892 setPrefLoopAlignment(4);
896 setInsertFencesForAtomic(true);
898 if (Subtarget.enableMachineScheduler())
899 setSchedulingPreference(Sched::Source);
901 setSchedulingPreference(Sched::Hybrid);
903 computeRegisterProperties(STI.getRegisterInfo());
905 // The Freescale cores do better with aggressive inlining of memcpy and
906 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
907 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
908 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
909 MaxStoresPerMemset = 32;
910 MaxStoresPerMemsetOptSize = 16;
911 MaxStoresPerMemcpy = 32;
912 MaxStoresPerMemcpyOptSize = 8;
913 MaxStoresPerMemmove = 32;
914 MaxStoresPerMemmoveOptSize = 8;
915 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
916 // The A2 also benefits from (very) aggressive inlining of memcpy and
917 // friends. The overhead of a the function call, even when warm, can be
918 // over one hundred cycles.
919 MaxStoresPerMemset = 128;
920 MaxStoresPerMemcpy = 128;
921 MaxStoresPerMemmove = 128;
925 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
926 /// the desired ByVal argument alignment.
927 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
928 unsigned MaxMaxAlign) {
929 if (MaxAlign == MaxMaxAlign)
931 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
932 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
934 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
936 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
937 unsigned EltAlign = 0;
938 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
939 if (EltAlign > MaxAlign)
941 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
942 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
943 unsigned EltAlign = 0;
944 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
945 if (EltAlign > MaxAlign)
947 if (MaxAlign == MaxMaxAlign)
953 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
954 /// function arguments in the caller parameter area.
955 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
956 // Darwin passes everything on 4 byte boundary.
957 if (Subtarget.isDarwin())
960 // 16byte and wider vectors are passed on 16byte boundary.
961 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
962 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
963 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
964 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
968 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
969 switch ((PPCISD::NodeType)Opcode) {
970 case PPCISD::FIRST_NUMBER: break;
971 case PPCISD::FSEL: return "PPCISD::FSEL";
972 case PPCISD::FCFID: return "PPCISD::FCFID";
973 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
974 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
975 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
976 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
977 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
978 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
979 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
980 case PPCISD::FRE: return "PPCISD::FRE";
981 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
982 case PPCISD::STFIWX: return "PPCISD::STFIWX";
983 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
984 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
985 case PPCISD::VPERM: return "PPCISD::VPERM";
986 case PPCISD::CMPB: return "PPCISD::CMPB";
987 case PPCISD::Hi: return "PPCISD::Hi";
988 case PPCISD::Lo: return "PPCISD::Lo";
989 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
990 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
991 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
992 case PPCISD::SRL: return "PPCISD::SRL";
993 case PPCISD::SRA: return "PPCISD::SRA";
994 case PPCISD::SHL: return "PPCISD::SHL";
995 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
996 case PPCISD::CALL: return "PPCISD::CALL";
997 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
998 case PPCISD::MTCTR: return "PPCISD::MTCTR";
999 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1000 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1001 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1002 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1003 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1004 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1005 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1006 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1007 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1008 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1009 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1010 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1011 case PPCISD::VCMP: return "PPCISD::VCMP";
1012 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1013 case PPCISD::LBRX: return "PPCISD::LBRX";
1014 case PPCISD::STBRX: return "PPCISD::STBRX";
1015 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1016 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1017 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1018 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1019 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1020 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1021 case PPCISD::BDZ: return "PPCISD::BDZ";
1022 case PPCISD::MFFS: return "PPCISD::MFFS";
1023 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1024 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1025 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1026 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1027 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1028 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1029 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1030 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1031 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1032 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1033 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1034 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1035 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1036 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1037 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1038 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1039 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1040 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1041 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1042 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1043 case PPCISD::SC: return "PPCISD::SC";
1044 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1045 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1046 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1047 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1048 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1049 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1050 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1051 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1052 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1053 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1058 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1060 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1062 if (Subtarget.hasQPX())
1063 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1065 return VT.changeVectorElementTypeToInteger();
1068 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1069 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1073 //===----------------------------------------------------------------------===//
1074 // Node matching predicates, for use by the tblgen matching code.
1075 //===----------------------------------------------------------------------===//
1077 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1078 static bool isFloatingPointZero(SDValue Op) {
1079 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1080 return CFP->getValueAPF().isZero();
1081 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1082 // Maybe this has already been legalized into the constant pool?
1083 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1084 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1085 return CFP->getValueAPF().isZero();
1090 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1091 /// true if Op is undef or if it matches the specified value.
1092 static bool isConstantOrUndef(int Op, int Val) {
1093 return Op < 0 || Op == Val;
1096 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1097 /// VPKUHUM instruction.
1098 /// The ShuffleKind distinguishes between big-endian operations with
1099 /// two different inputs (0), either-endian operations with two identical
1100 /// inputs (1), and little-endian operations with two different inputs (2).
1101 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1102 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1103 SelectionDAG &DAG) {
1104 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1105 if (ShuffleKind == 0) {
1108 for (unsigned i = 0; i != 16; ++i)
1109 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1111 } else if (ShuffleKind == 2) {
1114 for (unsigned i = 0; i != 16; ++i)
1115 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1117 } else if (ShuffleKind == 1) {
1118 unsigned j = IsLE ? 0 : 1;
1119 for (unsigned i = 0; i != 8; ++i)
1120 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1121 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1127 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1128 /// VPKUWUM instruction.
1129 /// The ShuffleKind distinguishes between big-endian operations with
1130 /// two different inputs (0), either-endian operations with two identical
1131 /// inputs (1), and little-endian operations with two different inputs (2).
1132 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1133 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1134 SelectionDAG &DAG) {
1135 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1136 if (ShuffleKind == 0) {
1139 for (unsigned i = 0; i != 16; i += 2)
1140 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1141 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1143 } else if (ShuffleKind == 2) {
1146 for (unsigned i = 0; i != 16; i += 2)
1147 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1148 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1150 } else if (ShuffleKind == 1) {
1151 unsigned j = IsLE ? 0 : 2;
1152 for (unsigned i = 0; i != 8; i += 2)
1153 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1154 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1155 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1156 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1162 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1163 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1164 /// current subtarget.
1166 /// The ShuffleKind distinguishes between big-endian operations with
1167 /// two different inputs (0), either-endian operations with two identical
1168 /// inputs (1), and little-endian operations with two different inputs (2).
1169 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1170 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1171 SelectionDAG &DAG) {
1172 const PPCSubtarget& Subtarget =
1173 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1174 if (!Subtarget.hasP8Vector())
1177 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1178 if (ShuffleKind == 0) {
1181 for (unsigned i = 0; i != 16; i += 4)
1182 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1183 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1184 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1185 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1187 } else if (ShuffleKind == 2) {
1190 for (unsigned i = 0; i != 16; i += 4)
1191 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1192 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1193 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1194 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1196 } else if (ShuffleKind == 1) {
1197 unsigned j = IsLE ? 0 : 4;
1198 for (unsigned i = 0; i != 8; i += 4)
1199 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1200 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1201 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1202 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1203 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1204 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1205 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1206 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1212 /// isVMerge - Common function, used to match vmrg* shuffles.
1214 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1215 unsigned LHSStart, unsigned RHSStart) {
1216 if (N->getValueType(0) != MVT::v16i8)
1218 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1219 "Unsupported merge size!");
1221 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1222 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1223 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1224 LHSStart+j+i*UnitSize) ||
1225 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1226 RHSStart+j+i*UnitSize))
1232 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1233 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1234 /// The ShuffleKind distinguishes between big-endian merges with two
1235 /// different inputs (0), either-endian merges with two identical inputs (1),
1236 /// and little-endian merges with two different inputs (2). For the latter,
1237 /// the input operands are swapped (see PPCInstrAltivec.td).
1238 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1239 unsigned ShuffleKind, SelectionDAG &DAG) {
1240 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1241 if (ShuffleKind == 1) // unary
1242 return isVMerge(N, UnitSize, 0, 0);
1243 else if (ShuffleKind == 2) // swapped
1244 return isVMerge(N, UnitSize, 0, 16);
1248 if (ShuffleKind == 1) // unary
1249 return isVMerge(N, UnitSize, 8, 8);
1250 else if (ShuffleKind == 0) // normal
1251 return isVMerge(N, UnitSize, 8, 24);
1257 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1258 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1259 /// The ShuffleKind distinguishes between big-endian merges with two
1260 /// different inputs (0), either-endian merges with two identical inputs (1),
1261 /// and little-endian merges with two different inputs (2). For the latter,
1262 /// the input operands are swapped (see PPCInstrAltivec.td).
1263 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1264 unsigned ShuffleKind, SelectionDAG &DAG) {
1265 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1266 if (ShuffleKind == 1) // unary
1267 return isVMerge(N, UnitSize, 8, 8);
1268 else if (ShuffleKind == 2) // swapped
1269 return isVMerge(N, UnitSize, 8, 24);
1273 if (ShuffleKind == 1) // unary
1274 return isVMerge(N, UnitSize, 0, 0);
1275 else if (ShuffleKind == 0) // normal
1276 return isVMerge(N, UnitSize, 0, 16);
1283 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1284 /// amount, otherwise return -1.
1285 /// The ShuffleKind distinguishes between big-endian operations with two
1286 /// different inputs (0), either-endian operations with two identical inputs
1287 /// (1), and little-endian operations with two different inputs (2). For the
1288 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1289 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1290 SelectionDAG &DAG) {
1291 if (N->getValueType(0) != MVT::v16i8)
1294 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1296 // Find the first non-undef value in the shuffle mask.
1298 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1301 if (i == 16) return -1; // all undef.
1303 // Otherwise, check to see if the rest of the elements are consecutively
1304 // numbered from this value.
1305 unsigned ShiftAmt = SVOp->getMaskElt(i);
1306 if (ShiftAmt < i) return -1;
1309 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1311 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1312 // Check the rest of the elements to see if they are consecutive.
1313 for (++i; i != 16; ++i)
1314 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1316 } else if (ShuffleKind == 1) {
1317 // Check the rest of the elements to see if they are consecutive.
1318 for (++i; i != 16; ++i)
1319 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1324 if (ShuffleKind == 2 && isLE)
1325 ShiftAmt = 16 - ShiftAmt;
1330 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1331 /// specifies a splat of a single element that is suitable for input to
1332 /// VSPLTB/VSPLTH/VSPLTW.
1333 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1334 assert(N->getValueType(0) == MVT::v16i8 &&
1335 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1337 // This is a splat operation if each element of the permute is the same, and
1338 // if the value doesn't reference the second vector.
1339 unsigned ElementBase = N->getMaskElt(0);
1341 // FIXME: Handle UNDEF elements too!
1342 if (ElementBase >= 16)
1345 // Check that the indices are consecutive, in the case of a multi-byte element
1346 // splatted with a v16i8 mask.
1347 for (unsigned i = 1; i != EltSize; ++i)
1348 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1351 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1352 if (N->getMaskElt(i) < 0) continue;
1353 for (unsigned j = 0; j != EltSize; ++j)
1354 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1360 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1361 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1362 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1363 SelectionDAG &DAG) {
1364 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1365 assert(isSplatShuffleMask(SVOp, EltSize));
1366 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1367 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1369 return SVOp->getMaskElt(0) / EltSize;
1372 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1373 /// by using a vspltis[bhw] instruction of the specified element size, return
1374 /// the constant being splatted. The ByteSize field indicates the number of
1375 /// bytes of each element [124] -> [bhw].
1376 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1377 SDValue OpVal(nullptr, 0);
1379 // If ByteSize of the splat is bigger than the element size of the
1380 // build_vector, then we have a case where we are checking for a splat where
1381 // multiple elements of the buildvector are folded together into a single
1382 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1383 unsigned EltSize = 16/N->getNumOperands();
1384 if (EltSize < ByteSize) {
1385 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1386 SDValue UniquedVals[4];
1387 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1389 // See if all of the elements in the buildvector agree across.
1390 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1391 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1392 // If the element isn't a constant, bail fully out.
1393 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1396 if (!UniquedVals[i&(Multiple-1)].getNode())
1397 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1398 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1399 return SDValue(); // no match.
1402 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1403 // either constant or undef values that are identical for each chunk. See
1404 // if these chunks can form into a larger vspltis*.
1406 // Check to see if all of the leading entries are either 0 or -1. If
1407 // neither, then this won't fit into the immediate field.
1408 bool LeadingZero = true;
1409 bool LeadingOnes = true;
1410 for (unsigned i = 0; i != Multiple-1; ++i) {
1411 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1413 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1414 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1416 // Finally, check the least significant entry.
1418 if (!UniquedVals[Multiple-1].getNode())
1419 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1420 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1421 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1422 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1425 if (!UniquedVals[Multiple-1].getNode())
1426 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1427 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1428 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1429 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1435 // Check to see if this buildvec has a single non-undef value in its elements.
1436 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1437 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1438 if (!OpVal.getNode())
1439 OpVal = N->getOperand(i);
1440 else if (OpVal != N->getOperand(i))
1444 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1446 unsigned ValSizeInBytes = EltSize;
1448 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1449 Value = CN->getZExtValue();
1450 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1451 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1452 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1455 // If the splat value is larger than the element value, then we can never do
1456 // this splat. The only case that we could fit the replicated bits into our
1457 // immediate field for would be zero, and we prefer to use vxor for it.
1458 if (ValSizeInBytes < ByteSize) return SDValue();
1460 // If the element value is larger than the splat value, check if it consists
1461 // of a repeated bit pattern of size ByteSize.
1462 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1465 // Properly sign extend the value.
1466 int MaskVal = SignExtend32(Value, ByteSize * 8);
1468 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1469 if (MaskVal == 0) return SDValue();
1471 // Finally, if this value fits in a 5 bit sext field, return it
1472 if (SignExtend32<5>(MaskVal) == MaskVal)
1473 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1477 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1478 /// amount, otherwise return -1.
1479 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1480 EVT VT = N->getValueType(0);
1481 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1484 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1486 // Find the first non-undef value in the shuffle mask.
1488 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1491 if (i == 4) return -1; // all undef.
1493 // Otherwise, check to see if the rest of the elements are consecutively
1494 // numbered from this value.
1495 unsigned ShiftAmt = SVOp->getMaskElt(i);
1496 if (ShiftAmt < i) return -1;
1499 // Check the rest of the elements to see if they are consecutive.
1500 for (++i; i != 4; ++i)
1501 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1507 //===----------------------------------------------------------------------===//
1508 // Addressing Mode Selection
1509 //===----------------------------------------------------------------------===//
1511 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1512 /// or 64-bit immediate, and if the value can be accurately represented as a
1513 /// sign extension from a 16-bit value. If so, this returns true and the
1515 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1516 if (!isa<ConstantSDNode>(N))
1519 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1520 if (N->getValueType(0) == MVT::i32)
1521 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1523 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1525 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1526 return isIntS16Immediate(Op.getNode(), Imm);
1530 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1531 /// can be represented as an indexed [r+r] operation. Returns false if it
1532 /// can be more efficiently represented with [r+imm].
1533 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1535 SelectionDAG &DAG) const {
1537 if (N.getOpcode() == ISD::ADD) {
1538 if (isIntS16Immediate(N.getOperand(1), imm))
1539 return false; // r+i
1540 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1541 return false; // r+i
1543 Base = N.getOperand(0);
1544 Index = N.getOperand(1);
1546 } else if (N.getOpcode() == ISD::OR) {
1547 if (isIntS16Immediate(N.getOperand(1), imm))
1548 return false; // r+i can fold it if we can.
1550 // If this is an or of disjoint bitfields, we can codegen this as an add
1551 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1553 APInt LHSKnownZero, LHSKnownOne;
1554 APInt RHSKnownZero, RHSKnownOne;
1555 DAG.computeKnownBits(N.getOperand(0),
1556 LHSKnownZero, LHSKnownOne);
1558 if (LHSKnownZero.getBoolValue()) {
1559 DAG.computeKnownBits(N.getOperand(1),
1560 RHSKnownZero, RHSKnownOne);
1561 // If all of the bits are known zero on the LHS or RHS, the add won't
1563 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1564 Base = N.getOperand(0);
1565 Index = N.getOperand(1);
1574 // If we happen to be doing an i64 load or store into a stack slot that has
1575 // less than a 4-byte alignment, then the frame-index elimination may need to
1576 // use an indexed load or store instruction (because the offset may not be a
1577 // multiple of 4). The extra register needed to hold the offset comes from the
1578 // register scavenger, and it is possible that the scavenger will need to use
1579 // an emergency spill slot. As a result, we need to make sure that a spill slot
1580 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1582 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1583 // FIXME: This does not handle the LWA case.
1587 // NOTE: We'll exclude negative FIs here, which come from argument
1588 // lowering, because there are no known test cases triggering this problem
1589 // using packed structures (or similar). We can remove this exclusion if
1590 // we find such a test case. The reason why this is so test-case driven is
1591 // because this entire 'fixup' is only to prevent crashes (from the
1592 // register scavenger) on not-really-valid inputs. For example, if we have:
1594 // %b = bitcast i1* %a to i64*
1595 // store i64* a, i64 b
1596 // then the store should really be marked as 'align 1', but is not. If it
1597 // were marked as 'align 1' then the indexed form would have been
1598 // instruction-selected initially, and the problem this 'fixup' is preventing
1599 // won't happen regardless.
1603 MachineFunction &MF = DAG.getMachineFunction();
1604 MachineFrameInfo *MFI = MF.getFrameInfo();
1606 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1610 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1611 FuncInfo->setHasNonRISpills();
1614 /// Returns true if the address N can be represented by a base register plus
1615 /// a signed 16-bit displacement [r+imm], and if it is not better
1616 /// represented as reg+reg. If Aligned is true, only accept displacements
1617 /// suitable for STD and friends, i.e. multiples of 4.
1618 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1621 bool Aligned) const {
1622 // FIXME dl should come from parent load or store, not from address
1624 // If this can be more profitably realized as r+r, fail.
1625 if (SelectAddressRegReg(N, Disp, Base, DAG))
1628 if (N.getOpcode() == ISD::ADD) {
1630 if (isIntS16Immediate(N.getOperand(1), imm) &&
1631 (!Aligned || (imm & 3) == 0)) {
1632 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1633 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1634 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1635 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1637 Base = N.getOperand(0);
1639 return true; // [r+i]
1640 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1641 // Match LOAD (ADD (X, Lo(G))).
1642 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1643 && "Cannot handle constant offsets yet!");
1644 Disp = N.getOperand(1).getOperand(0); // The global address.
1645 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1646 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1647 Disp.getOpcode() == ISD::TargetConstantPool ||
1648 Disp.getOpcode() == ISD::TargetJumpTable);
1649 Base = N.getOperand(0);
1650 return true; // [&g+r]
1652 } else if (N.getOpcode() == ISD::OR) {
1654 if (isIntS16Immediate(N.getOperand(1), imm) &&
1655 (!Aligned || (imm & 3) == 0)) {
1656 // If this is an or of disjoint bitfields, we can codegen this as an add
1657 // (for better address arithmetic) if the LHS and RHS of the OR are
1658 // provably disjoint.
1659 APInt LHSKnownZero, LHSKnownOne;
1660 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1662 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1663 // If all of the bits are known zero on the LHS or RHS, the add won't
1665 if (FrameIndexSDNode *FI =
1666 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1667 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1668 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1670 Base = N.getOperand(0);
1672 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1676 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1677 // Loading from a constant address.
1679 // If this address fits entirely in a 16-bit sext immediate field, codegen
1682 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1683 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1684 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1685 CN->getValueType(0));
1689 // Handle 32-bit sext immediates with LIS + addr mode.
1690 if ((CN->getValueType(0) == MVT::i32 ||
1691 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1692 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1693 int Addr = (int)CN->getZExtValue();
1695 // Otherwise, break this down into an LIS + disp.
1696 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1698 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1700 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1701 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1706 Disp = DAG.getTargetConstant(0, dl, getPointerTy());
1707 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1708 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1709 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1712 return true; // [r+0]
1715 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1716 /// represented as an indexed [r+r] operation.
1717 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1719 SelectionDAG &DAG) const {
1720 // Check to see if we can easily represent this as an [r+r] address. This
1721 // will fail if it thinks that the address is more profitably represented as
1722 // reg+imm, e.g. where imm = 0.
1723 if (SelectAddressRegReg(N, Base, Index, DAG))
1726 // If the operand is an addition, always emit this as [r+r], since this is
1727 // better (for code size, and execution, as the memop does the add for free)
1728 // than emitting an explicit add.
1729 if (N.getOpcode() == ISD::ADD) {
1730 Base = N.getOperand(0);
1731 Index = N.getOperand(1);
1735 // Otherwise, do it the hard way, using R0 as the base register.
1736 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1742 /// getPreIndexedAddressParts - returns true by value, base pointer and
1743 /// offset pointer and addressing mode by reference if the node's address
1744 /// can be legally represented as pre-indexed load / store address.
1745 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1747 ISD::MemIndexedMode &AM,
1748 SelectionDAG &DAG) const {
1749 if (DisablePPCPreinc) return false;
1755 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1756 Ptr = LD->getBasePtr();
1757 VT = LD->getMemoryVT();
1758 Alignment = LD->getAlignment();
1759 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1760 Ptr = ST->getBasePtr();
1761 VT = ST->getMemoryVT();
1762 Alignment = ST->getAlignment();
1767 // PowerPC doesn't have preinc load/store instructions for vectors (except
1768 // for QPX, which does have preinc r+r forms).
1769 if (VT.isVector()) {
1770 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1772 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1778 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1780 // Common code will reject creating a pre-inc form if the base pointer
1781 // is a frame index, or if N is a store and the base pointer is either
1782 // the same as or a predecessor of the value being stored. Check for
1783 // those situations here, and try with swapped Base/Offset instead.
1786 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1789 SDValue Val = cast<StoreSDNode>(N)->getValue();
1790 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1795 std::swap(Base, Offset);
1801 // LDU/STU can only handle immediates that are a multiple of 4.
1802 if (VT != MVT::i64) {
1803 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1806 // LDU/STU need an address with at least 4-byte alignment.
1810 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1814 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1815 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1816 // sext i32 to i64 when addr mode is r+i.
1817 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1818 LD->getExtensionType() == ISD::SEXTLOAD &&
1819 isa<ConstantSDNode>(Offset))
1827 //===----------------------------------------------------------------------===//
1828 // LowerOperation implementation
1829 //===----------------------------------------------------------------------===//
1831 /// GetLabelAccessInfo - Return true if we should reference labels using a
1832 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1833 static bool GetLabelAccessInfo(const TargetMachine &TM,
1834 const PPCSubtarget &Subtarget,
1835 unsigned &HiOpFlags, unsigned &LoOpFlags,
1836 const GlobalValue *GV = nullptr) {
1837 HiOpFlags = PPCII::MO_HA;
1838 LoOpFlags = PPCII::MO_LO;
1840 // Don't use the pic base if not in PIC relocation model.
1841 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1844 HiOpFlags |= PPCII::MO_PIC_FLAG;
1845 LoOpFlags |= PPCII::MO_PIC_FLAG;
1848 // If this is a reference to a global value that requires a non-lazy-ptr, make
1849 // sure that instruction lowering adds it.
1850 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1851 HiOpFlags |= PPCII::MO_NLP_FLAG;
1852 LoOpFlags |= PPCII::MO_NLP_FLAG;
1854 if (GV->hasHiddenVisibility()) {
1855 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1856 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1863 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1864 SelectionDAG &DAG) {
1866 EVT PtrVT = HiPart.getValueType();
1867 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1869 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1870 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1872 // With PIC, the first instruction is actually "GR+hi(&G)".
1874 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1875 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1877 // Generate non-pic code that has direct accesses to the constant pool.
1878 // The address of the global is just (hi(&g)+lo(&g)).
1879 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1882 static void setUsesTOCBasePtr(MachineFunction &MF) {
1883 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1884 FuncInfo->setUsesTOCBasePtr();
1887 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1888 setUsesTOCBasePtr(DAG.getMachineFunction());
1891 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1893 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1894 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1895 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1897 SDValue Ops[] = { GA, Reg };
1898 return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1899 DAG.getVTList(VT, MVT::Other), Ops, VT,
1900 MachinePointerInfo::getGOT(), 0, false, true,
1904 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1905 SelectionDAG &DAG) const {
1906 EVT PtrVT = Op.getValueType();
1907 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1908 const Constant *C = CP->getConstVal();
1910 // 64-bit SVR4 ABI code is always position-independent.
1911 // The actual address of the GlobalValue is stored in the TOC.
1912 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1913 setUsesTOCBasePtr(DAG);
1914 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1915 return getTOCEntry(DAG, SDLoc(CP), true, GA);
1918 unsigned MOHiFlag, MOLoFlag;
1920 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1922 if (isPIC && Subtarget.isSVR4ABI()) {
1923 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1924 PPCII::MO_PIC_FLAG);
1925 return getTOCEntry(DAG, SDLoc(CP), false, GA);
1929 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1931 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1932 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1935 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1936 EVT PtrVT = Op.getValueType();
1937 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1939 // 64-bit SVR4 ABI code is always position-independent.
1940 // The actual address of the GlobalValue is stored in the TOC.
1941 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1942 setUsesTOCBasePtr(DAG);
1943 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1944 return getTOCEntry(DAG, SDLoc(JT), true, GA);
1947 unsigned MOHiFlag, MOLoFlag;
1949 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1951 if (isPIC && Subtarget.isSVR4ABI()) {
1952 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1953 PPCII::MO_PIC_FLAG);
1954 return getTOCEntry(DAG, SDLoc(GA), false, GA);
1957 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1958 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1959 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1962 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1963 SelectionDAG &DAG) const {
1964 EVT PtrVT = Op.getValueType();
1965 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1966 const BlockAddress *BA = BASDN->getBlockAddress();
1968 // 64-bit SVR4 ABI code is always position-independent.
1969 // The actual BlockAddress is stored in the TOC.
1970 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1971 setUsesTOCBasePtr(DAG);
1972 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1973 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1976 unsigned MOHiFlag, MOLoFlag;
1978 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1979 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1980 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1981 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1984 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1985 SelectionDAG &DAG) const {
1987 // FIXME: TLS addresses currently use medium model code sequences,
1988 // which is the most useful form. Eventually support for small and
1989 // large models could be added if users need it, at the cost of
1990 // additional complexity.
1991 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1993 const GlobalValue *GV = GA->getGlobal();
1994 EVT PtrVT = getPointerTy();
1995 bool is64bit = Subtarget.isPPC64();
1996 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1997 PICLevel::Level picLevel = M->getPICLevel();
1999 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2001 if (Model == TLSModel::LocalExec) {
2002 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2003 PPCII::MO_TPREL_HA);
2004 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2005 PPCII::MO_TPREL_LO);
2006 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2007 is64bit ? MVT::i64 : MVT::i32);
2008 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2009 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2012 if (Model == TLSModel::InitialExec) {
2013 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2014 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2018 setUsesTOCBasePtr(DAG);
2019 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2020 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2021 PtrVT, GOTReg, TGA);
2023 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2024 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2025 PtrVT, TGA, GOTPtr);
2026 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2029 if (Model == TLSModel::GeneralDynamic) {
2030 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2033 setUsesTOCBasePtr(DAG);
2034 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2035 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2038 if (picLevel == PICLevel::Small)
2039 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2041 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2043 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2047 if (Model == TLSModel::LocalDynamic) {
2048 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2051 setUsesTOCBasePtr(DAG);
2052 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2053 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2056 if (picLevel == PICLevel::Small)
2057 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2059 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2061 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2062 PtrVT, GOTPtr, TGA, TGA);
2063 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2064 PtrVT, TLSAddr, TGA);
2065 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2068 llvm_unreachable("Unknown TLS model!");
2071 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2072 SelectionDAG &DAG) const {
2073 EVT PtrVT = Op.getValueType();
2074 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2076 const GlobalValue *GV = GSDN->getGlobal();
2078 // 64-bit SVR4 ABI code is always position-independent.
2079 // The actual address of the GlobalValue is stored in the TOC.
2080 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2081 setUsesTOCBasePtr(DAG);
2082 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2083 return getTOCEntry(DAG, DL, true, GA);
2086 unsigned MOHiFlag, MOLoFlag;
2088 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2090 if (isPIC && Subtarget.isSVR4ABI()) {
2091 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2093 PPCII::MO_PIC_FLAG);
2094 return getTOCEntry(DAG, DL, false, GA);
2098 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2100 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2102 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2104 // If the global reference is actually to a non-lazy-pointer, we have to do an
2105 // extra load to get the address of the global.
2106 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2107 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2108 false, false, false, 0);
2112 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2113 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2116 if (Op.getValueType() == MVT::v2i64) {
2117 // When the operands themselves are v2i64 values, we need to do something
2118 // special because VSX has no underlying comparison operations for these.
2119 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2120 // Equality can be handled by casting to the legal type for Altivec
2121 // comparisons, everything else needs to be expanded.
2122 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2123 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2124 DAG.getSetCC(dl, MVT::v4i32,
2125 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2126 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2133 // We handle most of these in the usual way.
2137 // If we're comparing for equality to zero, expose the fact that this is
2138 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2139 // fold the new nodes.
2140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2141 if (C->isNullValue() && CC == ISD::SETEQ) {
2142 EVT VT = Op.getOperand(0).getValueType();
2143 SDValue Zext = Op.getOperand(0);
2144 if (VT.bitsLT(MVT::i32)) {
2146 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2148 unsigned Log2b = Log2_32(VT.getSizeInBits());
2149 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2150 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2151 DAG.getConstant(Log2b, dl, MVT::i32));
2152 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2154 // Leave comparisons against 0 and -1 alone for now, since they're usually
2155 // optimized. FIXME: revisit this when we can custom lower all setcc
2157 if (C->isAllOnesValue() || C->isNullValue())
2161 // If we have an integer seteq/setne, turn it into a compare against zero
2162 // by xor'ing the rhs with the lhs, which is faster than setting a
2163 // condition register, reading it back out, and masking the correct bit. The
2164 // normal approach here uses sub to do this instead of xor. Using xor exposes
2165 // the result to other bit-twiddling opportunities.
2166 EVT LHSVT = Op.getOperand(0).getValueType();
2167 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2168 EVT VT = Op.getValueType();
2169 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2171 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2176 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2177 const PPCSubtarget &Subtarget) const {
2178 SDNode *Node = Op.getNode();
2179 EVT VT = Node->getValueType(0);
2180 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2181 SDValue InChain = Node->getOperand(0);
2182 SDValue VAListPtr = Node->getOperand(1);
2183 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2186 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2189 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2190 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2191 false, false, false, 0);
2192 InChain = GprIndex.getValue(1);
2194 if (VT == MVT::i64) {
2195 // Check if GprIndex is even
2196 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2197 DAG.getConstant(1, dl, MVT::i32));
2198 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2199 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2200 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2201 DAG.getConstant(1, dl, MVT::i32));
2202 // Align GprIndex to be even if it isn't
2203 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2207 // fpr index is 1 byte after gpr
2208 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2209 DAG.getConstant(1, dl, MVT::i32));
2212 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2213 FprPtr, MachinePointerInfo(SV), MVT::i8,
2214 false, false, false, 0);
2215 InChain = FprIndex.getValue(1);
2217 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2218 DAG.getConstant(8, dl, MVT::i32));
2220 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2221 DAG.getConstant(4, dl, MVT::i32));
2224 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2225 MachinePointerInfo(), false, false,
2227 InChain = OverflowArea.getValue(1);
2229 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2230 MachinePointerInfo(), false, false,
2232 InChain = RegSaveArea.getValue(1);
2234 // select overflow_area if index > 8
2235 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2236 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2238 // adjustment constant gpr_index * 4/8
2239 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2240 VT.isInteger() ? GprIndex : FprIndex,
2241 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2244 // OurReg = RegSaveArea + RegConstant
2245 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2248 // Floating types are 32 bytes into RegSaveArea
2249 if (VT.isFloatingPoint())
2250 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2251 DAG.getConstant(32, dl, MVT::i32));
2253 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2254 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2255 VT.isInteger() ? GprIndex : FprIndex,
2256 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2259 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2260 VT.isInteger() ? VAListPtr : FprPtr,
2261 MachinePointerInfo(SV),
2262 MVT::i8, false, false, 0);
2264 // determine if we should load from reg_save_area or overflow_area
2265 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2267 // increase overflow_area by 4/8 if gpr/fpr > 8
2268 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2269 DAG.getConstant(VT.isInteger() ? 4 : 8,
2272 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2275 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2277 MachinePointerInfo(),
2278 MVT::i32, false, false, 0);
2280 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2281 false, false, false, 0);
2284 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2285 const PPCSubtarget &Subtarget) const {
2286 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2288 // We have to copy the entire va_list struct:
2289 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2290 return DAG.getMemcpy(Op.getOperand(0), Op,
2291 Op.getOperand(1), Op.getOperand(2),
2292 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2293 false, MachinePointerInfo(), MachinePointerInfo());
2296 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2297 SelectionDAG &DAG) const {
2298 return Op.getOperand(0);
2301 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2302 SelectionDAG &DAG) const {
2303 SDValue Chain = Op.getOperand(0);
2304 SDValue Trmp = Op.getOperand(1); // trampoline
2305 SDValue FPtr = Op.getOperand(2); // nested function
2306 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2309 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2310 bool isPPC64 = (PtrVT == MVT::i64);
2312 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2315 TargetLowering::ArgListTy Args;
2316 TargetLowering::ArgListEntry Entry;
2318 Entry.Ty = IntPtrTy;
2319 Entry.Node = Trmp; Args.push_back(Entry);
2321 // TrampSize == (isPPC64 ? 48 : 40);
2322 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2323 isPPC64 ? MVT::i64 : MVT::i32);
2324 Args.push_back(Entry);
2326 Entry.Node = FPtr; Args.push_back(Entry);
2327 Entry.Node = Nest; Args.push_back(Entry);
2329 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2330 TargetLowering::CallLoweringInfo CLI(DAG);
2331 CLI.setDebugLoc(dl).setChain(Chain)
2332 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2333 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2334 std::move(Args), 0);
2336 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2337 return CallResult.second;
2340 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2341 const PPCSubtarget &Subtarget) const {
2342 MachineFunction &MF = DAG.getMachineFunction();
2343 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2347 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2348 // vastart just stores the address of the VarArgsFrameIndex slot into the
2349 // memory location argument.
2350 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2351 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2352 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2353 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2354 MachinePointerInfo(SV),
2358 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2359 // We suppose the given va_list is already allocated.
2362 // char gpr; /* index into the array of 8 GPRs
2363 // * stored in the register save area
2364 // * gpr=0 corresponds to r3,
2365 // * gpr=1 to r4, etc.
2367 // char fpr; /* index into the array of 8 FPRs
2368 // * stored in the register save area
2369 // * fpr=0 corresponds to f1,
2370 // * fpr=1 to f2, etc.
2372 // char *overflow_arg_area;
2373 // /* location on stack that holds
2374 // * the next overflow argument
2376 // char *reg_save_area;
2377 // /* where r3:r10 and f1:f8 (if saved)
2383 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2384 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2387 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2389 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2391 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2394 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2395 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2397 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2398 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2400 uint64_t FPROffset = 1;
2401 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2403 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2405 // Store first byte : number of int regs
2406 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2408 MachinePointerInfo(SV),
2409 MVT::i8, false, false, 0);
2410 uint64_t nextOffset = FPROffset;
2411 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2414 // Store second byte : number of float regs
2415 SDValue secondStore =
2416 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2417 MachinePointerInfo(SV, nextOffset), MVT::i8,
2419 nextOffset += StackOffset;
2420 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2422 // Store second word : arguments given on stack
2423 SDValue thirdStore =
2424 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2425 MachinePointerInfo(SV, nextOffset),
2427 nextOffset += FrameOffset;
2428 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2430 // Store third word : arguments given in registers
2431 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2432 MachinePointerInfo(SV, nextOffset),
2437 #include "PPCGenCallingConv.inc"
2439 // Function whose sole purpose is to kill compiler warnings
2440 // stemming from unused functions included from PPCGenCallingConv.inc.
2441 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2442 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2445 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2446 CCValAssign::LocInfo &LocInfo,
2447 ISD::ArgFlagsTy &ArgFlags,
2452 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2454 CCValAssign::LocInfo &LocInfo,
2455 ISD::ArgFlagsTy &ArgFlags,
2457 static const MCPhysReg ArgRegs[] = {
2458 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2459 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2461 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2463 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2465 // Skip one register if the first unallocated register has an even register
2466 // number and there are still argument registers available which have not been
2467 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2468 // need to skip a register if RegNum is odd.
2469 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2470 State.AllocateReg(ArgRegs[RegNum]);
2473 // Always return false here, as this function only makes sure that the first
2474 // unallocated register has an odd register number and does not actually
2475 // allocate a register for the current argument.
2479 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2481 CCValAssign::LocInfo &LocInfo,
2482 ISD::ArgFlagsTy &ArgFlags,
2484 static const MCPhysReg ArgRegs[] = {
2485 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2489 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2491 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2493 // If there is only one Floating-point register left we need to put both f64
2494 // values of a split ppc_fp128 value on the stack.
2495 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2496 State.AllocateReg(ArgRegs[RegNum]);
2499 // Always return false here, as this function only makes sure that the two f64
2500 // values a ppc_fp128 value is split into are both passed in registers or both
2501 // passed on the stack and does not actually allocate a register for the
2502 // current argument.
2506 /// FPR - The set of FP registers that should be allocated for arguments,
2508 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2509 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2510 PPC::F11, PPC::F12, PPC::F13};
2512 /// QFPR - The set of QPX registers that should be allocated for arguments.
2513 static const MCPhysReg QFPR[] = {
2514 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2515 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2517 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2519 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2520 unsigned PtrByteSize) {
2521 unsigned ArgSize = ArgVT.getStoreSize();
2522 if (Flags.isByVal())
2523 ArgSize = Flags.getByValSize();
2525 // Round up to multiples of the pointer size, except for array members,
2526 // which are always packed.
2527 if (!Flags.isInConsecutiveRegs())
2528 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2533 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2535 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2536 ISD::ArgFlagsTy Flags,
2537 unsigned PtrByteSize) {
2538 unsigned Align = PtrByteSize;
2540 // Altivec parameters are padded to a 16 byte boundary.
2541 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2542 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2543 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2544 ArgVT == MVT::v1i128)
2546 // QPX vector types stored in double-precision are padded to a 32 byte
2548 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2551 // ByVal parameters are aligned as requested.
2552 if (Flags.isByVal()) {
2553 unsigned BVAlign = Flags.getByValAlign();
2554 if (BVAlign > PtrByteSize) {
2555 if (BVAlign % PtrByteSize != 0)
2557 "ByVal alignment is not a multiple of the pointer size");
2563 // Array members are always packed to their original alignment.
2564 if (Flags.isInConsecutiveRegs()) {
2565 // If the array member was split into multiple registers, the first
2566 // needs to be aligned to the size of the full type. (Except for
2567 // ppcf128, which is only aligned as its f64 components.)
2568 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2569 Align = OrigVT.getStoreSize();
2571 Align = ArgVT.getStoreSize();
2577 /// CalculateStackSlotUsed - Return whether this argument will use its
2578 /// stack slot (instead of being passed in registers). ArgOffset,
2579 /// AvailableFPRs, and AvailableVRs must hold the current argument
2580 /// position, and will be updated to account for this argument.
2581 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2582 ISD::ArgFlagsTy Flags,
2583 unsigned PtrByteSize,
2584 unsigned LinkageSize,
2585 unsigned ParamAreaSize,
2586 unsigned &ArgOffset,
2587 unsigned &AvailableFPRs,
2588 unsigned &AvailableVRs, bool HasQPX) {
2589 bool UseMemory = false;
2591 // Respect alignment of argument on the stack.
2593 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2594 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2595 // If there's no space left in the argument save area, we must
2596 // use memory (this check also catches zero-sized arguments).
2597 if (ArgOffset >= LinkageSize + ParamAreaSize)
2600 // Allocate argument on the stack.
2601 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2602 if (Flags.isInConsecutiveRegsLast())
2603 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2604 // If we overran the argument save area, we must use memory
2605 // (this check catches arguments passed partially in memory)
2606 if (ArgOffset > LinkageSize + ParamAreaSize)
2609 // However, if the argument is actually passed in an FPR or a VR,
2610 // we don't use memory after all.
2611 if (!Flags.isByVal()) {
2612 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2613 // QPX registers overlap with the scalar FP registers.
2614 (HasQPX && (ArgVT == MVT::v4f32 ||
2615 ArgVT == MVT::v4f64 ||
2616 ArgVT == MVT::v4i1)))
2617 if (AvailableFPRs > 0) {
2621 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2622 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2623 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2624 ArgVT == MVT::v1i128)
2625 if (AvailableVRs > 0) {
2634 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2635 /// ensure minimum alignment required for target.
2636 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2637 unsigned NumBytes) {
2638 unsigned TargetAlign = Lowering->getStackAlignment();
2639 unsigned AlignMask = TargetAlign - 1;
2640 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2645 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2646 CallingConv::ID CallConv, bool isVarArg,
2647 const SmallVectorImpl<ISD::InputArg>
2649 SDLoc dl, SelectionDAG &DAG,
2650 SmallVectorImpl<SDValue> &InVals)
2652 if (Subtarget.isSVR4ABI()) {
2653 if (Subtarget.isPPC64())
2654 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2657 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2660 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2666 PPCTargetLowering::LowerFormalArguments_32SVR4(
2668 CallingConv::ID CallConv, bool isVarArg,
2669 const SmallVectorImpl<ISD::InputArg>
2671 SDLoc dl, SelectionDAG &DAG,
2672 SmallVectorImpl<SDValue> &InVals) const {
2674 // 32-bit SVR4 ABI Stack Frame Layout:
2675 // +-----------------------------------+
2676 // +--> | Back chain |
2677 // | +-----------------------------------+
2678 // | | Floating-point register save area |
2679 // | +-----------------------------------+
2680 // | | General register save area |
2681 // | +-----------------------------------+
2682 // | | CR save word |
2683 // | +-----------------------------------+
2684 // | | VRSAVE save word |
2685 // | +-----------------------------------+
2686 // | | Alignment padding |
2687 // | +-----------------------------------+
2688 // | | Vector register save area |
2689 // | +-----------------------------------+
2690 // | | Local variable space |
2691 // | +-----------------------------------+
2692 // | | Parameter list area |
2693 // | +-----------------------------------+
2694 // | | LR save word |
2695 // | +-----------------------------------+
2696 // SP--> +--- | Back chain |
2697 // +-----------------------------------+
2700 // System V Application Binary Interface PowerPC Processor Supplement
2701 // AltiVec Technology Programming Interface Manual
2703 MachineFunction &MF = DAG.getMachineFunction();
2704 MachineFrameInfo *MFI = MF.getFrameInfo();
2705 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2707 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2708 // Potential tail calls could cause overwriting of argument stack slots.
2709 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2710 (CallConv == CallingConv::Fast));
2711 unsigned PtrByteSize = 4;
2713 // Assign locations to all of the incoming arguments.
2714 SmallVector<CCValAssign, 16> ArgLocs;
2715 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2718 // Reserve space for the linkage area on the stack.
2719 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2720 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2722 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2724 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2725 CCValAssign &VA = ArgLocs[i];
2727 // Arguments stored in registers.
2728 if (VA.isRegLoc()) {
2729 const TargetRegisterClass *RC;
2730 EVT ValVT = VA.getValVT();
2732 switch (ValVT.getSimpleVT().SimpleTy) {
2734 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2737 RC = &PPC::GPRCRegClass;
2740 if (Subtarget.hasP8Vector())
2741 RC = &PPC::VSSRCRegClass;
2743 RC = &PPC::F4RCRegClass;
2746 if (Subtarget.hasVSX())
2747 RC = &PPC::VSFRCRegClass;
2749 RC = &PPC::F8RCRegClass;
2754 RC = &PPC::VRRCRegClass;
2757 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2761 RC = &PPC::VSHRCRegClass;
2764 RC = &PPC::QFRCRegClass;
2767 RC = &PPC::QBRCRegClass;
2771 // Transform the arguments stored in physical registers into virtual ones.
2772 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2773 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2774 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2776 if (ValVT == MVT::i1)
2777 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2779 InVals.push_back(ArgValue);
2781 // Argument stored in memory.
2782 assert(VA.isMemLoc());
2784 unsigned ArgSize = VA.getLocVT().getStoreSize();
2785 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2788 // Create load nodes to retrieve arguments from the stack.
2789 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2790 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2791 MachinePointerInfo(),
2792 false, false, false, 0));
2796 // Assign locations to all of the incoming aggregate by value arguments.
2797 // Aggregates passed by value are stored in the local variable space of the
2798 // caller's stack frame, right above the parameter list area.
2799 SmallVector<CCValAssign, 16> ByValArgLocs;
2800 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2801 ByValArgLocs, *DAG.getContext());
2803 // Reserve stack space for the allocations in CCInfo.
2804 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2806 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2808 // Area that is at least reserved in the caller of this function.
2809 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2810 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2812 // Set the size that is at least reserved in caller of this function. Tail
2813 // call optimized function's reserved stack space needs to be aligned so that
2814 // taking the difference between two stack areas will result in an aligned
2817 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2818 FuncInfo->setMinReservedArea(MinReservedArea);
2820 SmallVector<SDValue, 8> MemOps;
2822 // If the function takes variable number of arguments, make a frame index for
2823 // the start of the first vararg value... for expansion of llvm.va_start.
2825 static const MCPhysReg GPArgRegs[] = {
2826 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2827 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2829 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2831 static const MCPhysReg FPArgRegs[] = {
2832 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2835 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2836 if (DisablePPCFloatInVariadic)
2839 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2840 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2842 // Make room for NumGPArgRegs and NumFPArgRegs.
2843 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2844 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2846 FuncInfo->setVarArgsStackOffset(
2847 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2848 CCInfo.getNextStackOffset(), true));
2850 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2851 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2853 // The fixed integer arguments of a variadic function are stored to the
2854 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2855 // the result of va_next.
2856 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2857 // Get an existing live-in vreg, or add a new one.
2858 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2860 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2862 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2863 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2864 MachinePointerInfo(), false, false, 0);
2865 MemOps.push_back(Store);
2866 // Increment the address by four for the next argument to store
2867 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2868 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2871 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2873 // The double arguments are stored to the VarArgsFrameIndex
2875 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2876 // Get an existing live-in vreg, or add a new one.
2877 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2879 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2881 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2882 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2883 MachinePointerInfo(), false, false, 0);
2884 MemOps.push_back(Store);
2885 // Increment the address by eight for the next argument to store
2886 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2888 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2892 if (!MemOps.empty())
2893 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2898 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2899 // value to MVT::i64 and then truncate to the correct register size.
2901 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2902 SelectionDAG &DAG, SDValue ArgVal,
2905 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2906 DAG.getValueType(ObjectVT));
2907 else if (Flags.isZExt())
2908 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2909 DAG.getValueType(ObjectVT));
2911 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2915 PPCTargetLowering::LowerFormalArguments_64SVR4(
2917 CallingConv::ID CallConv, bool isVarArg,
2918 const SmallVectorImpl<ISD::InputArg>
2920 SDLoc dl, SelectionDAG &DAG,
2921 SmallVectorImpl<SDValue> &InVals) const {
2922 // TODO: add description of PPC stack frame format, or at least some docs.
2924 bool isELFv2ABI = Subtarget.isELFv2ABI();
2925 bool isLittleEndian = Subtarget.isLittleEndian();
2926 MachineFunction &MF = DAG.getMachineFunction();
2927 MachineFrameInfo *MFI = MF.getFrameInfo();
2928 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2930 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2931 "fastcc not supported on varargs functions");
2933 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2934 // Potential tail calls could cause overwriting of argument stack slots.
2935 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2936 (CallConv == CallingConv::Fast));
2937 unsigned PtrByteSize = 8;
2938 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2940 static const MCPhysReg GPR[] = {
2941 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2942 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2944 static const MCPhysReg VR[] = {
2945 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2946 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2948 static const MCPhysReg VSRH[] = {
2949 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2950 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2953 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2954 const unsigned Num_FPR_Regs = 13;
2955 const unsigned Num_VR_Regs = array_lengthof(VR);
2956 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2958 // Do a first pass over the arguments to determine whether the ABI
2959 // guarantees that our caller has allocated the parameter save area
2960 // on its stack frame. In the ELFv1 ABI, this is always the case;
2961 // in the ELFv2 ABI, it is true if this is a vararg function or if
2962 // any parameter is located in a stack slot.
2964 bool HasParameterArea = !isELFv2ABI || isVarArg;
2965 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2966 unsigned NumBytes = LinkageSize;
2967 unsigned AvailableFPRs = Num_FPR_Regs;
2968 unsigned AvailableVRs = Num_VR_Regs;
2969 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2970 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2971 PtrByteSize, LinkageSize, ParamAreaSize,
2972 NumBytes, AvailableFPRs, AvailableVRs,
2973 Subtarget.hasQPX()))
2974 HasParameterArea = true;
2976 // Add DAG nodes to load the arguments or copy them out of registers. On
2977 // entry to a function on PPC, the arguments start after the linkage area,
2978 // although the first ones are often in registers.
2980 unsigned ArgOffset = LinkageSize;
2981 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2982 unsigned &QFPR_idx = FPR_idx;
2983 SmallVector<SDValue, 8> MemOps;
2984 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2985 unsigned CurArgIdx = 0;
2986 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2988 bool needsLoad = false;
2989 EVT ObjectVT = Ins[ArgNo].VT;
2990 EVT OrigVT = Ins[ArgNo].ArgVT;
2991 unsigned ObjSize = ObjectVT.getStoreSize();
2992 unsigned ArgSize = ObjSize;
2993 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2994 if (Ins[ArgNo].isOrigArg()) {
2995 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2996 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2998 // We re-align the argument offset for each argument, except when using the
2999 // fast calling convention, when we need to make sure we do that only when
3000 // we'll actually use a stack slot.
3001 unsigned CurArgOffset, Align;
3002 auto ComputeArgOffset = [&]() {
3003 /* Respect alignment of argument on the stack. */
3004 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3005 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3006 CurArgOffset = ArgOffset;
3009 if (CallConv != CallingConv::Fast) {
3012 /* Compute GPR index associated with argument offset. */
3013 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3014 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3017 // FIXME the codegen can be much improved in some cases.
3018 // We do not have to keep everything in memory.
3019 if (Flags.isByVal()) {
3020 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3022 if (CallConv == CallingConv::Fast)
3025 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3026 ObjSize = Flags.getByValSize();
3027 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3028 // Empty aggregate parameters do not take up registers. Examples:
3032 // etc. However, we have to provide a place-holder in InVals, so
3033 // pretend we have an 8-byte item at the current address for that
3036 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3037 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3038 InVals.push_back(FIN);
3042 // Create a stack object covering all stack doublewords occupied
3043 // by the argument. If the argument is (fully or partially) on
3044 // the stack, or if the argument is fully in registers but the
3045 // caller has allocated the parameter save anyway, we can refer
3046 // directly to the caller's stack frame. Otherwise, create a
3047 // local copy in our own frame.
3049 if (HasParameterArea ||
3050 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3051 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3053 FI = MFI->CreateStackObject(ArgSize, Align, false);
3054 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3056 // Handle aggregates smaller than 8 bytes.
3057 if (ObjSize < PtrByteSize) {
3058 // The value of the object is its address, which differs from the
3059 // address of the enclosing doubleword on big-endian systems.
3061 if (!isLittleEndian) {
3062 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3063 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3065 InVals.push_back(Arg);
3067 if (GPR_idx != Num_GPR_Regs) {
3068 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3069 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3072 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3073 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3074 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3075 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3076 MachinePointerInfo(FuncArg),
3077 ObjType, false, false, 0);
3079 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3080 // store the whole register as-is to the parameter save area
3082 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3083 MachinePointerInfo(FuncArg),
3087 MemOps.push_back(Store);
3089 // Whether we copied from a register or not, advance the offset
3090 // into the parameter save area by a full doubleword.
3091 ArgOffset += PtrByteSize;
3095 // The value of the object is its address, which is the address of
3096 // its first stack doubleword.
3097 InVals.push_back(FIN);
3099 // Store whatever pieces of the object are in registers to memory.
3100 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3101 if (GPR_idx == Num_GPR_Regs)
3104 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3105 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3108 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3109 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3111 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3112 MachinePointerInfo(FuncArg, j),
3114 MemOps.push_back(Store);
3117 ArgOffset += ArgSize;
3121 switch (ObjectVT.getSimpleVT().SimpleTy) {
3122 default: llvm_unreachable("Unhandled argument type!");
3126 // These can be scalar arguments or elements of an integer array type
3127 // passed directly. Clang may use those instead of "byval" aggregate
3128 // types to avoid forcing arguments to memory unnecessarily.
3129 if (GPR_idx != Num_GPR_Regs) {
3130 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3131 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3133 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3134 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3135 // value to MVT::i64 and then truncate to the correct register size.
3136 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3138 if (CallConv == CallingConv::Fast)
3142 ArgSize = PtrByteSize;
3144 if (CallConv != CallingConv::Fast || needsLoad)
3150 // These can be scalar arguments or elements of a float array type
3151 // passed directly. The latter are used to implement ELFv2 homogenous
3152 // float aggregates.
3153 if (FPR_idx != Num_FPR_Regs) {
3156 if (ObjectVT == MVT::f32)
3157 VReg = MF.addLiveIn(FPR[FPR_idx],
3158 Subtarget.hasP8Vector()
3159 ? &PPC::VSSRCRegClass
3160 : &PPC::F4RCRegClass);
3162 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3163 ? &PPC::VSFRCRegClass
3164 : &PPC::F8RCRegClass);
3166 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3168 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3169 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3170 // once we support fp <-> gpr moves.
3172 // This can only ever happen in the presence of f32 array types,
3173 // since otherwise we never run out of FPRs before running out
3175 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3176 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3178 if (ObjectVT == MVT::f32) {
3179 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3180 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3181 DAG.getConstant(32, dl, MVT::i32));
3182 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3185 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3187 if (CallConv == CallingConv::Fast)
3193 // When passing an array of floats, the array occupies consecutive
3194 // space in the argument area; only round up to the next doubleword
3195 // at the end of the array. Otherwise, each float takes 8 bytes.
3196 if (CallConv != CallingConv::Fast || needsLoad) {
3197 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3198 ArgOffset += ArgSize;
3199 if (Flags.isInConsecutiveRegsLast())
3200 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3210 if (!Subtarget.hasQPX()) {
3211 // These can be scalar arguments or elements of a vector array type
3212 // passed directly. The latter are used to implement ELFv2 homogenous
3213 // vector aggregates.
3214 if (VR_idx != Num_VR_Regs) {
3215 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3216 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3217 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3218 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3221 if (CallConv == CallingConv::Fast)
3226 if (CallConv != CallingConv::Fast || needsLoad)
3231 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3232 "Invalid QPX parameter type");
3237 // QPX vectors are treated like their scalar floating-point subregisters
3238 // (except that they're larger).
3239 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3240 if (QFPR_idx != Num_QFPR_Regs) {
3241 const TargetRegisterClass *RC;
3242 switch (ObjectVT.getSimpleVT().SimpleTy) {
3243 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3244 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3245 default: RC = &PPC::QBRCRegClass; break;
3248 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3249 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3252 if (CallConv == CallingConv::Fast)
3256 if (CallConv != CallingConv::Fast || needsLoad)
3261 // We need to load the argument to a virtual register if we determined
3262 // above that we ran out of physical registers of the appropriate type.
3264 if (ObjSize < ArgSize && !isLittleEndian)
3265 CurArgOffset += ArgSize - ObjSize;
3266 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3267 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3268 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3269 false, false, false, 0);
3272 InVals.push_back(ArgVal);
3275 // Area that is at least reserved in the caller of this function.
3276 unsigned MinReservedArea;
3277 if (HasParameterArea)
3278 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3280 MinReservedArea = LinkageSize;
3282 // Set the size that is at least reserved in caller of this function. Tail
3283 // call optimized functions' reserved stack space needs to be aligned so that
3284 // taking the difference between two stack areas will result in an aligned
3287 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3288 FuncInfo->setMinReservedArea(MinReservedArea);
3290 // If the function takes variable number of arguments, make a frame index for
3291 // the start of the first vararg value... for expansion of llvm.va_start.
3293 int Depth = ArgOffset;
3295 FuncInfo->setVarArgsFrameIndex(
3296 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3297 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3299 // If this function is vararg, store any remaining integer argument regs
3300 // to their spots on the stack so that they may be loaded by deferencing the
3301 // result of va_next.
3302 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3303 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3304 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3305 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3306 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3307 MachinePointerInfo(), false, false, 0);
3308 MemOps.push_back(Store);
3309 // Increment the address by four for the next argument to store
3310 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3311 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3315 if (!MemOps.empty())
3316 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3322 PPCTargetLowering::LowerFormalArguments_Darwin(
3324 CallingConv::ID CallConv, bool isVarArg,
3325 const SmallVectorImpl<ISD::InputArg>
3327 SDLoc dl, SelectionDAG &DAG,
3328 SmallVectorImpl<SDValue> &InVals) const {
3329 // TODO: add description of PPC stack frame format, or at least some docs.
3331 MachineFunction &MF = DAG.getMachineFunction();
3332 MachineFrameInfo *MFI = MF.getFrameInfo();
3333 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3335 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3336 bool isPPC64 = PtrVT == MVT::i64;
3337 // Potential tail calls could cause overwriting of argument stack slots.
3338 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3339 (CallConv == CallingConv::Fast));
3340 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3341 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3342 unsigned ArgOffset = LinkageSize;
3343 // Area that is at least reserved in caller of this function.
3344 unsigned MinReservedArea = ArgOffset;
3346 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3347 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3348 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3350 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3351 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3352 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3354 static const MCPhysReg VR[] = {
3355 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3356 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3359 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3360 const unsigned Num_FPR_Regs = 13;
3361 const unsigned Num_VR_Regs = array_lengthof( VR);
3363 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3365 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3367 // In 32-bit non-varargs functions, the stack space for vectors is after the
3368 // stack space for non-vectors. We do not use this space unless we have
3369 // too many vectors to fit in registers, something that only occurs in
3370 // constructed examples:), but we have to walk the arglist to figure
3371 // that out...for the pathological case, compute VecArgOffset as the
3372 // start of the vector parameter area. Computing VecArgOffset is the
3373 // entire point of the following loop.
3374 unsigned VecArgOffset = ArgOffset;
3375 if (!isVarArg && !isPPC64) {
3376 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3378 EVT ObjectVT = Ins[ArgNo].VT;
3379 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3381 if (Flags.isByVal()) {
3382 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3383 unsigned ObjSize = Flags.getByValSize();
3385 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3386 VecArgOffset += ArgSize;
3390 switch(ObjectVT.getSimpleVT().SimpleTy) {
3391 default: llvm_unreachable("Unhandled argument type!");
3397 case MVT::i64: // PPC64
3399 // FIXME: We are guaranteed to be !isPPC64 at this point.
3400 // Does MVT::i64 apply?
3407 // Nothing to do, we're only looking at Nonvector args here.
3412 // We've found where the vector parameter area in memory is. Skip the
3413 // first 12 parameters; these don't use that memory.
3414 VecArgOffset = ((VecArgOffset+15)/16)*16;
3415 VecArgOffset += 12*16;
3417 // Add DAG nodes to load the arguments or copy them out of registers. On
3418 // entry to a function on PPC, the arguments start after the linkage area,
3419 // although the first ones are often in registers.
3421 SmallVector<SDValue, 8> MemOps;
3422 unsigned nAltivecParamsAtEnd = 0;
3423 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3424 unsigned CurArgIdx = 0;
3425 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3427 bool needsLoad = false;
3428 EVT ObjectVT = Ins[ArgNo].VT;
3429 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3430 unsigned ArgSize = ObjSize;
3431 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3432 if (Ins[ArgNo].isOrigArg()) {
3433 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3434 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3436 unsigned CurArgOffset = ArgOffset;
3438 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3439 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3440 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3441 if (isVarArg || isPPC64) {
3442 MinReservedArea = ((MinReservedArea+15)/16)*16;
3443 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3446 } else nAltivecParamsAtEnd++;
3448 // Calculate min reserved area.
3449 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3453 // FIXME the codegen can be much improved in some cases.
3454 // We do not have to keep everything in memory.
3455 if (Flags.isByVal()) {
3456 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3458 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3459 ObjSize = Flags.getByValSize();
3460 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3461 // Objects of size 1 and 2 are right justified, everything else is
3462 // left justified. This means the memory address is adjusted forwards.
3463 if (ObjSize==1 || ObjSize==2) {
3464 CurArgOffset = CurArgOffset + (4 - ObjSize);
3466 // The value of the object is its address.
3467 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3468 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3469 InVals.push_back(FIN);
3470 if (ObjSize==1 || ObjSize==2) {
3471 if (GPR_idx != Num_GPR_Regs) {
3474 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3476 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3477 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3478 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3479 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3480 MachinePointerInfo(FuncArg),
3481 ObjType, false, false, 0);
3482 MemOps.push_back(Store);
3486 ArgOffset += PtrByteSize;
3490 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3491 // Store whatever pieces of the object are in registers
3492 // to memory. ArgOffset will be the address of the beginning
3494 if (GPR_idx != Num_GPR_Regs) {
3497 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3499 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3500 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3501 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3502 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3503 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3504 MachinePointerInfo(FuncArg, j),
3506 MemOps.push_back(Store);
3508 ArgOffset += PtrByteSize;
3510 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3517 switch (ObjectVT.getSimpleVT().SimpleTy) {
3518 default: llvm_unreachable("Unhandled argument type!");
3522 if (GPR_idx != Num_GPR_Regs) {
3523 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3524 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3526 if (ObjectVT == MVT::i1)
3527 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3532 ArgSize = PtrByteSize;
3534 // All int arguments reserve stack space in the Darwin ABI.
3535 ArgOffset += PtrByteSize;
3539 case MVT::i64: // PPC64
3540 if (GPR_idx != Num_GPR_Regs) {
3541 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3542 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3544 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3545 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3546 // value to MVT::i64 and then truncate to the correct register size.
3547 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3552 ArgSize = PtrByteSize;
3554 // All int arguments reserve stack space in the Darwin ABI.
3560 // Every 4 bytes of argument space consumes one of the GPRs available for
3561 // argument passing.
3562 if (GPR_idx != Num_GPR_Regs) {
3564 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3567 if (FPR_idx != Num_FPR_Regs) {
3570 if (ObjectVT == MVT::f32)
3571 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3573 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3575 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3581 // All FP arguments reserve stack space in the Darwin ABI.
3582 ArgOffset += isPPC64 ? 8 : ObjSize;
3588 // Note that vector arguments in registers don't reserve stack space,
3589 // except in varargs functions.
3590 if (VR_idx != Num_VR_Regs) {
3591 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3592 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3594 while ((ArgOffset % 16) != 0) {
3595 ArgOffset += PtrByteSize;
3596 if (GPR_idx != Num_GPR_Regs)
3600 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3604 if (!isVarArg && !isPPC64) {
3605 // Vectors go after all the nonvectors.
3606 CurArgOffset = VecArgOffset;
3609 // Vectors are aligned.
3610 ArgOffset = ((ArgOffset+15)/16)*16;
3611 CurArgOffset = ArgOffset;
3619 // We need to load the argument to a virtual register if we determined above
3620 // that we ran out of physical registers of the appropriate type.
3622 int FI = MFI->CreateFixedObject(ObjSize,
3623 CurArgOffset + (ArgSize - ObjSize),
3625 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3626 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3627 false, false, false, 0);
3630 InVals.push_back(ArgVal);
3633 // Allow for Altivec parameters at the end, if needed.
3634 if (nAltivecParamsAtEnd) {
3635 MinReservedArea = ((MinReservedArea+15)/16)*16;
3636 MinReservedArea += 16*nAltivecParamsAtEnd;
3639 // Area that is at least reserved in the caller of this function.
3640 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3642 // Set the size that is at least reserved in caller of this function. Tail
3643 // call optimized functions' reserved stack space needs to be aligned so that
3644 // taking the difference between two stack areas will result in an aligned
3647 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3648 FuncInfo->setMinReservedArea(MinReservedArea);
3650 // If the function takes variable number of arguments, make a frame index for
3651 // the start of the first vararg value... for expansion of llvm.va_start.
3653 int Depth = ArgOffset;
3655 FuncInfo->setVarArgsFrameIndex(
3656 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3658 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3660 // If this function is vararg, store any remaining integer argument regs
3661 // to their spots on the stack so that they may be loaded by deferencing the
3662 // result of va_next.
3663 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3667 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3669 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3671 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3672 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3673 MachinePointerInfo(), false, false, 0);
3674 MemOps.push_back(Store);
3675 // Increment the address by four for the next argument to store
3676 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3677 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3681 if (!MemOps.empty())
3682 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3687 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3688 /// adjusted to accommodate the arguments for the tailcall.
3689 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3690 unsigned ParamSize) {
3692 if (!isTailCall) return 0;
3694 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3695 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3696 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3697 // Remember only if the new adjustement is bigger.
3698 if (SPDiff < FI->getTailCallSPDelta())
3699 FI->setTailCallSPDelta(SPDiff);
3704 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3705 /// for tail call optimization. Targets which want to do tail call
3706 /// optimization should implement this function.
3708 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3709 CallingConv::ID CalleeCC,
3711 const SmallVectorImpl<ISD::InputArg> &Ins,
3712 SelectionDAG& DAG) const {
3713 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3716 // Variable argument functions are not supported.
3720 MachineFunction &MF = DAG.getMachineFunction();
3721 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3722 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3723 // Functions containing by val parameters are not supported.
3724 for (unsigned i = 0; i != Ins.size(); i++) {
3725 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3726 if (Flags.isByVal()) return false;
3729 // Non-PIC/GOT tail calls are supported.
3730 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3733 // At the moment we can only do local tail calls (in same module, hidden
3734 // or protected) if we are generating PIC.
3735 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3736 return G->getGlobal()->hasHiddenVisibility()
3737 || G->getGlobal()->hasProtectedVisibility();
3743 /// isCallCompatibleAddress - Return the immediate to use if the specified
3744 /// 32-bit value is representable in the immediate field of a BxA instruction.
3745 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3746 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3747 if (!C) return nullptr;
3749 int Addr = C->getZExtValue();
3750 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3751 SignExtend32<26>(Addr) != Addr)
3752 return nullptr; // Top 6 bits have to be sext of immediate.
3754 return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3755 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3760 struct TailCallArgumentInfo {
3765 TailCallArgumentInfo() : FrameIdx(0) {}
3770 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3772 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3774 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3775 SmallVectorImpl<SDValue> &MemOpChains,
3777 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3778 SDValue Arg = TailCallArgs[i].Arg;
3779 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3780 int FI = TailCallArgs[i].FrameIdx;
3781 // Store relative to framepointer.
3782 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3783 MachinePointerInfo::getFixedStack(FI),
3788 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3789 /// the appropriate stack slot for the tail call optimized function call.
3790 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3791 MachineFunction &MF,
3800 // Calculate the new stack slot for the return address.
3801 int SlotSize = isPPC64 ? 8 : 4;
3802 const PPCFrameLowering *FL =
3803 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3804 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3805 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3806 NewRetAddrLoc, true);
3807 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3808 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3809 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3810 MachinePointerInfo::getFixedStack(NewRetAddr),
3813 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3814 // slot as the FP is never overwritten.
3816 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3817 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3819 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3820 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3821 MachinePointerInfo::getFixedStack(NewFPIdx),
3828 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3829 /// the position of the argument.
3831 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3832 SDValue Arg, int SPDiff, unsigned ArgOffset,
3833 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3834 int Offset = ArgOffset + SPDiff;
3835 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3836 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3837 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3838 SDValue FIN = DAG.getFrameIndex(FI, VT);
3839 TailCallArgumentInfo Info;
3841 Info.FrameIdxOp = FIN;
3843 TailCallArguments.push_back(Info);
3846 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3847 /// stack slot. Returns the chain as result and the loaded frame pointers in
3848 /// LROpOut/FPOpout. Used when tail calling.
3849 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3857 // Load the LR and FP stack slot for later adjusting.
3858 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3859 LROpOut = getReturnAddrFrameIndex(DAG);
3860 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3861 false, false, false, 0);
3862 Chain = SDValue(LROpOut.getNode(), 1);
3864 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3865 // slot as the FP is never overwritten.
3867 FPOpOut = getFramePointerFrameIndex(DAG);
3868 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3869 false, false, false, 0);
3870 Chain = SDValue(FPOpOut.getNode(), 1);
3876 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3877 /// by "Src" to address "Dst" of size "Size". Alignment information is
3878 /// specified by the specific parameter attribute. The copy will be passed as
3879 /// a byval function parameter.
3880 /// Sometimes what we are copying is the end of a larger object, the part that
3881 /// does not fit in registers.
3883 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3884 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3886 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3887 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3888 false, false, false, MachinePointerInfo(),
3889 MachinePointerInfo());
3892 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3895 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3896 SDValue Arg, SDValue PtrOff, int SPDiff,
3897 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3898 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3899 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3901 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3906 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3908 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3909 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3910 DAG.getConstant(ArgOffset, dl, PtrVT));
3912 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3913 MachinePointerInfo(), false, false, 0));
3914 // Calculate and remember argument location.
3915 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3920 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3921 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3922 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3923 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3924 MachineFunction &MF = DAG.getMachineFunction();
3926 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3927 // might overwrite each other in case of tail call optimization.
3928 SmallVector<SDValue, 8> MemOpChains2;
3929 // Do not flag preceding copytoreg stuff together with the following stuff.
3931 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3933 if (!MemOpChains2.empty())
3934 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3936 // Store the return address to the appropriate stack slot.
3937 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3938 isPPC64, isDarwinABI, dl);
3940 // Emit callseq_end just before tailcall node.
3941 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
3942 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3943 InFlag = Chain.getValue(1);
3946 // Is this global address that of a function that can be called by name? (as
3947 // opposed to something that must hold a descriptor for an indirect call).
3948 static bool isFunctionGlobalAddress(SDValue Callee) {
3949 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3950 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3951 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3954 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3961 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3962 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3963 bool isTailCall, bool IsPatchPoint,
3964 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3965 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3966 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3968 bool isPPC64 = Subtarget.isPPC64();
3969 bool isSVR4ABI = Subtarget.isSVR4ABI();
3970 bool isELFv2ABI = Subtarget.isELFv2ABI();
3972 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3973 NodeTys.push_back(MVT::Other); // Returns a chain
3974 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3976 unsigned CallOpc = PPCISD::CALL;
3978 bool needIndirectCall = true;
3979 if (!isSVR4ABI || !isPPC64)
3980 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3981 // If this is an absolute destination address, use the munged value.
3982 Callee = SDValue(Dest, 0);
3983 needIndirectCall = false;
3986 if (isFunctionGlobalAddress(Callee)) {
3987 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3988 // A call to a TLS address is actually an indirect call to a
3989 // thread-specific pointer.
3990 unsigned OpFlags = 0;
3991 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3992 (Subtarget.getTargetTriple().isMacOSX() &&
3993 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3994 (G->getGlobal()->isDeclaration() ||
3995 G->getGlobal()->isWeakForLinker())) ||
3996 (Subtarget.isTargetELF() && !isPPC64 &&
3997 !G->getGlobal()->hasLocalLinkage() &&
3998 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3999 // PC-relative references to external symbols should go through $stub,
4000 // unless we're building with the leopard linker or later, which
4001 // automatically synthesizes these stubs.
4002 OpFlags = PPCII::MO_PLT_OR_STUB;
4005 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4006 // every direct call is) turn it into a TargetGlobalAddress /
4007 // TargetExternalSymbol node so that legalize doesn't hack it.
4008 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4009 Callee.getValueType(), 0, OpFlags);
4010 needIndirectCall = false;
4013 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4014 unsigned char OpFlags = 0;
4016 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4017 (Subtarget.getTargetTriple().isMacOSX() &&
4018 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4019 (Subtarget.isTargetELF() && !isPPC64 &&
4020 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4021 // PC-relative references to external symbols should go through $stub,
4022 // unless we're building with the leopard linker or later, which
4023 // automatically synthesizes these stubs.
4024 OpFlags = PPCII::MO_PLT_OR_STUB;
4027 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4029 needIndirectCall = false;
4033 // We'll form an invalid direct call when lowering a patchpoint; the full
4034 // sequence for an indirect call is complicated, and many of the
4035 // instructions introduced might have side effects (and, thus, can't be
4036 // removed later). The call itself will be removed as soon as the
4037 // argument/return lowering is complete, so the fact that it has the wrong
4038 // kind of operands should not really matter.
4039 needIndirectCall = false;
4042 if (needIndirectCall) {
4043 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4044 // to do the call, we can't use PPCISD::CALL.
4045 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4047 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4048 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4049 // entry point, but to the function descriptor (the function entry point
4050 // address is part of the function descriptor though).
4051 // The function descriptor is a three doubleword structure with the
4052 // following fields: function entry point, TOC base address and
4053 // environment pointer.
4054 // Thus for a call through a function pointer, the following actions need
4056 // 1. Save the TOC of the caller in the TOC save area of its stack
4057 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4058 // 2. Load the address of the function entry point from the function
4060 // 3. Load the TOC of the callee from the function descriptor into r2.
4061 // 4. Load the environment pointer from the function descriptor into
4063 // 5. Branch to the function entry point address.
4064 // 6. On return of the callee, the TOC of the caller needs to be
4065 // restored (this is done in FinishCall()).
4067 // The loads are scheduled at the beginning of the call sequence, and the
4068 // register copies are flagged together to ensure that no other
4069 // operations can be scheduled in between. E.g. without flagging the
4070 // copies together, a TOC access in the caller could be scheduled between
4071 // the assignment of the callee TOC and the branch to the callee, which
4072 // results in the TOC access going through the TOC of the callee instead
4073 // of going through the TOC of the caller, which leads to incorrect code.
4075 // Load the address of the function entry point from the function
4077 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4078 if (LDChain.getValueType() == MVT::Glue)
4079 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4081 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4083 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4084 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4085 false, false, LoadsInv, 8);
4087 // Load environment pointer into r11.
4088 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4089 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4090 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4091 MPI.getWithOffset(16), false, false,
4094 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4095 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4096 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4097 MPI.getWithOffset(8), false, false,
4100 setUsesTOCBasePtr(DAG);
4101 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4103 Chain = TOCVal.getValue(0);
4104 InFlag = TOCVal.getValue(1);
4106 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4109 Chain = EnvVal.getValue(0);
4110 InFlag = EnvVal.getValue(1);
4112 MTCTROps[0] = Chain;
4113 MTCTROps[1] = LoadFuncPtr;
4114 MTCTROps[2] = InFlag;
4117 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4118 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4119 InFlag = Chain.getValue(1);
4122 NodeTys.push_back(MVT::Other);
4123 NodeTys.push_back(MVT::Glue);
4124 Ops.push_back(Chain);
4125 CallOpc = PPCISD::BCTRL;
4126 Callee.setNode(nullptr);
4127 // Add use of X11 (holding environment pointer)
4128 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4129 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4130 // Add CTR register as callee so a bctr can be emitted later.
4132 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4135 // If this is a direct call, pass the chain and the callee.
4136 if (Callee.getNode()) {
4137 Ops.push_back(Chain);
4138 Ops.push_back(Callee);
4140 // If this is a tail call add stack pointer delta.
4142 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4144 // Add argument registers to the end of the list so that they are known live
4146 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4147 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4148 RegsToPass[i].second.getValueType()));
4150 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4152 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4153 setUsesTOCBasePtr(DAG);
4154 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4161 bool isLocalCall(const SDValue &Callee)
4163 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4164 return !G->getGlobal()->isDeclaration() &&
4165 !G->getGlobal()->isWeakForLinker();
4170 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4171 CallingConv::ID CallConv, bool isVarArg,
4172 const SmallVectorImpl<ISD::InputArg> &Ins,
4173 SDLoc dl, SelectionDAG &DAG,
4174 SmallVectorImpl<SDValue> &InVals) const {
4176 SmallVector<CCValAssign, 16> RVLocs;
4177 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4179 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4181 // Copy all of the result registers out of their specified physreg.
4182 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4183 CCValAssign &VA = RVLocs[i];
4184 assert(VA.isRegLoc() && "Can only return in registers!");
4186 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4187 VA.getLocReg(), VA.getLocVT(), InFlag);
4188 Chain = Val.getValue(1);
4189 InFlag = Val.getValue(2);
4191 switch (VA.getLocInfo()) {
4192 default: llvm_unreachable("Unknown loc info!");
4193 case CCValAssign::Full: break;
4194 case CCValAssign::AExt:
4195 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4197 case CCValAssign::ZExt:
4198 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4199 DAG.getValueType(VA.getValVT()));
4200 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4202 case CCValAssign::SExt:
4203 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4204 DAG.getValueType(VA.getValVT()));
4205 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4209 InVals.push_back(Val);
4216 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4217 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4219 SmallVector<std::pair<unsigned, SDValue>, 8>
4221 SDValue InFlag, SDValue Chain,
4222 SDValue CallSeqStart, SDValue &Callee,
4223 int SPDiff, unsigned NumBytes,
4224 const SmallVectorImpl<ISD::InputArg> &Ins,
4225 SmallVectorImpl<SDValue> &InVals,
4226 ImmutableCallSite *CS) const {
4228 std::vector<EVT> NodeTys;
4229 SmallVector<SDValue, 8> Ops;
4230 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4231 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4232 Ops, NodeTys, CS, Subtarget);
4234 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4235 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4236 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4238 // When performing tail call optimization the callee pops its arguments off
4239 // the stack. Account for this here so these bytes can be pushed back on in
4240 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4241 int BytesCalleePops =
4242 (CallConv == CallingConv::Fast &&
4243 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4245 // Add a register mask operand representing the call-preserved registers.
4246 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4247 const uint32_t *Mask =
4248 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4249 assert(Mask && "Missing call preserved mask for calling convention");
4250 Ops.push_back(DAG.getRegisterMask(Mask));
4252 if (InFlag.getNode())
4253 Ops.push_back(InFlag);
4257 assert(((Callee.getOpcode() == ISD::Register &&
4258 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4259 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4260 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4261 isa<ConstantSDNode>(Callee)) &&
4262 "Expecting an global address, external symbol, absolute value or register");
4264 DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4265 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4268 // Add a NOP immediately after the branch instruction when using the 64-bit
4269 // SVR4 ABI. At link time, if caller and callee are in a different module and
4270 // thus have a different TOC, the call will be replaced with a call to a stub
4271 // function which saves the current TOC, loads the TOC of the callee and
4272 // branches to the callee. The NOP will be replaced with a load instruction
4273 // which restores the TOC of the caller from the TOC save slot of the current
4274 // stack frame. If caller and callee belong to the same module (and have the
4275 // same TOC), the NOP will remain unchanged.
4277 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4279 if (CallOpc == PPCISD::BCTRL) {
4280 // This is a call through a function pointer.
4281 // Restore the caller TOC from the save area into R2.
4282 // See PrepareCall() for more information about calls through function
4283 // pointers in the 64-bit SVR4 ABI.
4284 // We are using a target-specific load with r2 hard coded, because the
4285 // result of a target-independent load would never go directly into r2,
4286 // since r2 is a reserved register (which prevents the register allocator
4287 // from allocating it), resulting in an additional register being
4288 // allocated and an unnecessary move instruction being generated.
4289 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4291 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4292 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4293 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4294 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4295 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4297 // The address needs to go after the chain input but before the flag (or
4298 // any other variadic arguments).
4299 Ops.insert(std::next(Ops.begin()), AddTOC);
4300 } else if ((CallOpc == PPCISD::CALL) &&
4301 (!isLocalCall(Callee) ||
4302 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4303 // Otherwise insert NOP for non-local calls.
4304 CallOpc = PPCISD::CALL_NOP;
4307 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4308 InFlag = Chain.getValue(1);
4310 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4311 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4314 InFlag = Chain.getValue(1);
4316 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4317 Ins, dl, DAG, InVals);
4321 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4322 SmallVectorImpl<SDValue> &InVals) const {
4323 SelectionDAG &DAG = CLI.DAG;
4325 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4326 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4327 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4328 SDValue Chain = CLI.Chain;
4329 SDValue Callee = CLI.Callee;
4330 bool &isTailCall = CLI.IsTailCall;
4331 CallingConv::ID CallConv = CLI.CallConv;
4332 bool isVarArg = CLI.IsVarArg;
4333 bool IsPatchPoint = CLI.IsPatchPoint;
4334 ImmutableCallSite *CS = CLI.CS;
4337 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4340 if (!isTailCall && CS && CS->isMustTailCall())
4341 report_fatal_error("failed to perform tail call elimination on a call "
4342 "site marked musttail");
4344 if (Subtarget.isSVR4ABI()) {
4345 if (Subtarget.isPPC64())
4346 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4347 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4348 dl, DAG, InVals, CS);
4350 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4351 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4352 dl, DAG, InVals, CS);
4355 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4356 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4357 dl, DAG, InVals, CS);
4361 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4362 CallingConv::ID CallConv, bool isVarArg,
4363 bool isTailCall, bool IsPatchPoint,
4364 const SmallVectorImpl<ISD::OutputArg> &Outs,
4365 const SmallVectorImpl<SDValue> &OutVals,
4366 const SmallVectorImpl<ISD::InputArg> &Ins,
4367 SDLoc dl, SelectionDAG &DAG,
4368 SmallVectorImpl<SDValue> &InVals,
4369 ImmutableCallSite *CS) const {
4370 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4371 // of the 32-bit SVR4 ABI stack frame layout.
4373 assert((CallConv == CallingConv::C ||
4374 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4376 unsigned PtrByteSize = 4;
4378 MachineFunction &MF = DAG.getMachineFunction();
4380 // Mark this function as potentially containing a function that contains a
4381 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4382 // and restoring the callers stack pointer in this functions epilog. This is
4383 // done because by tail calling the called function might overwrite the value
4384 // in this function's (MF) stack pointer stack slot 0(SP).
4385 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4386 CallConv == CallingConv::Fast)
4387 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4389 // Count how many bytes are to be pushed on the stack, including the linkage
4390 // area, parameter list area and the part of the local variable space which
4391 // contains copies of aggregates which are passed by value.
4393 // Assign locations to all of the outgoing arguments.
4394 SmallVector<CCValAssign, 16> ArgLocs;
4395 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4398 // Reserve space for the linkage area on the stack.
4399 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4403 // Handle fixed and variable vector arguments differently.
4404 // Fixed vector arguments go into registers as long as registers are
4405 // available. Variable vector arguments always go into memory.
4406 unsigned NumArgs = Outs.size();
4408 for (unsigned i = 0; i != NumArgs; ++i) {
4409 MVT ArgVT = Outs[i].VT;
4410 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4413 if (Outs[i].IsFixed) {
4414 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4417 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4423 errs() << "Call operand #" << i << " has unhandled type "
4424 << EVT(ArgVT).getEVTString() << "\n";
4426 llvm_unreachable(nullptr);
4430 // All arguments are treated the same.
4431 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4434 // Assign locations to all of the outgoing aggregate by value arguments.
4435 SmallVector<CCValAssign, 16> ByValArgLocs;
4436 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4437 ByValArgLocs, *DAG.getContext());
4439 // Reserve stack space for the allocations in CCInfo.
4440 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4442 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4444 // Size of the linkage area, parameter list area and the part of the local
4445 // space variable where copies of aggregates which are passed by value are
4447 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4449 // Calculate by how many bytes the stack has to be adjusted in case of tail
4450 // call optimization.
4451 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4453 // Adjust the stack pointer for the new arguments...
4454 // These operations are automatically eliminated by the prolog/epilog pass
4455 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4457 SDValue CallSeqStart = Chain;
4459 // Load the return address and frame pointer so it can be moved somewhere else
4462 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4465 // Set up a copy of the stack pointer for use loading and storing any
4466 // arguments that may not fit in the registers available for argument
4468 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4470 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4471 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4472 SmallVector<SDValue, 8> MemOpChains;
4474 bool seenFloatArg = false;
4475 // Walk the register/memloc assignments, inserting copies/loads.
4476 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4479 CCValAssign &VA = ArgLocs[i];
4480 SDValue Arg = OutVals[i];
4481 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4483 if (Flags.isByVal()) {
4484 // Argument is an aggregate which is passed by value, thus we need to
4485 // create a copy of it in the local variable space of the current stack
4486 // frame (which is the stack frame of the caller) and pass the address of
4487 // this copy to the callee.
4488 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4489 CCValAssign &ByValVA = ByValArgLocs[j++];
4490 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4492 // Memory reserved in the local variable space of the callers stack frame.
4493 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4495 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4496 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4498 // Create a copy of the argument in the local area of the current
4500 SDValue MemcpyCall =
4501 CreateCopyOfByValArgument(Arg, PtrOff,
4502 CallSeqStart.getNode()->getOperand(0),
4505 // This must go outside the CALLSEQ_START..END.
4506 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4507 CallSeqStart.getNode()->getOperand(1),
4509 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4510 NewCallSeqStart.getNode());
4511 Chain = CallSeqStart = NewCallSeqStart;
4513 // Pass the address of the aggregate copy on the stack either in a
4514 // physical register or in the parameter list area of the current stack
4515 // frame to the callee.
4519 if (VA.isRegLoc()) {
4520 if (Arg.getValueType() == MVT::i1)
4521 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4523 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4524 // Put argument in a physical register.
4525 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4527 // Put argument in the parameter list area of the current stack frame.
4528 assert(VA.isMemLoc());
4529 unsigned LocMemOffset = VA.getLocMemOffset();
4532 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4533 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4535 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4536 MachinePointerInfo(),
4539 // Calculate and remember argument location.
4540 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4546 if (!MemOpChains.empty())
4547 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4549 // Build a sequence of copy-to-reg nodes chained together with token chain
4550 // and flag operands which copy the outgoing args into the appropriate regs.
4552 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4553 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4554 RegsToPass[i].second, InFlag);
4555 InFlag = Chain.getValue(1);
4558 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4561 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4562 SDValue Ops[] = { Chain, InFlag };
4564 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4565 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4567 InFlag = Chain.getValue(1);
4571 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4572 false, TailCallArguments);
4574 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4575 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4576 NumBytes, Ins, InVals, CS);
4579 // Copy an argument into memory, being careful to do this outside the
4580 // call sequence for the call to which the argument belongs.
4582 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4583 SDValue CallSeqStart,
4584 ISD::ArgFlagsTy Flags,
4587 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4588 CallSeqStart.getNode()->getOperand(0),
4590 // The MEMCPY must go outside the CALLSEQ_START..END.
4591 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4592 CallSeqStart.getNode()->getOperand(1),
4594 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4595 NewCallSeqStart.getNode());
4596 return NewCallSeqStart;
4600 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4601 CallingConv::ID CallConv, bool isVarArg,
4602 bool isTailCall, bool IsPatchPoint,
4603 const SmallVectorImpl<ISD::OutputArg> &Outs,
4604 const SmallVectorImpl<SDValue> &OutVals,
4605 const SmallVectorImpl<ISD::InputArg> &Ins,
4606 SDLoc dl, SelectionDAG &DAG,
4607 SmallVectorImpl<SDValue> &InVals,
4608 ImmutableCallSite *CS) const {
4610 bool isELFv2ABI = Subtarget.isELFv2ABI();
4611 bool isLittleEndian = Subtarget.isLittleEndian();
4612 unsigned NumOps = Outs.size();
4614 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4615 unsigned PtrByteSize = 8;
4617 MachineFunction &MF = DAG.getMachineFunction();
4619 // Mark this function as potentially containing a function that contains a
4620 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4621 // and restoring the callers stack pointer in this functions epilog. This is
4622 // done because by tail calling the called function might overwrite the value
4623 // in this function's (MF) stack pointer stack slot 0(SP).
4624 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4625 CallConv == CallingConv::Fast)
4626 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4628 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4629 "fastcc not supported on varargs functions");
4631 // Count how many bytes are to be pushed on the stack, including the linkage
4632 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4633 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4634 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4635 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4636 unsigned NumBytes = LinkageSize;
4637 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4638 unsigned &QFPR_idx = FPR_idx;
4640 static const MCPhysReg GPR[] = {
4641 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4642 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4644 static const MCPhysReg VR[] = {
4645 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4646 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4648 static const MCPhysReg VSRH[] = {
4649 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4650 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4653 const unsigned NumGPRs = array_lengthof(GPR);
4654 const unsigned NumFPRs = 13;
4655 const unsigned NumVRs = array_lengthof(VR);
4656 const unsigned NumQFPRs = NumFPRs;
4658 // When using the fast calling convention, we don't provide backing for
4659 // arguments that will be in registers.
4660 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4662 // Add up all the space actually used.
4663 for (unsigned i = 0; i != NumOps; ++i) {
4664 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4665 EVT ArgVT = Outs[i].VT;
4666 EVT OrigVT = Outs[i].ArgVT;
4668 if (CallConv == CallingConv::Fast) {
4669 if (Flags.isByVal())
4670 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4672 switch (ArgVT.getSimpleVT().SimpleTy) {
4673 default: llvm_unreachable("Unexpected ValueType for argument!");
4677 if (++NumGPRsUsed <= NumGPRs)
4686 if (++NumVRsUsed <= NumVRs)
4690 // When using QPX, this is handled like a FP register, otherwise, it
4691 // is an Altivec register.
4692 if (Subtarget.hasQPX()) {
4693 if (++NumFPRsUsed <= NumFPRs)
4696 if (++NumVRsUsed <= NumVRs)
4702 case MVT::v4f64: // QPX
4703 case MVT::v4i1: // QPX
4704 if (++NumFPRsUsed <= NumFPRs)
4710 /* Respect alignment of argument on the stack. */
4712 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4713 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4715 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4716 if (Flags.isInConsecutiveRegsLast())
4717 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4720 unsigned NumBytesActuallyUsed = NumBytes;
4722 // The prolog code of the callee may store up to 8 GPR argument registers to
4723 // the stack, allowing va_start to index over them in memory if its varargs.
4724 // Because we cannot tell if this is needed on the caller side, we have to
4725 // conservatively assume that it is needed. As such, make sure we have at
4726 // least enough stack space for the caller to store the 8 GPRs.
4727 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4728 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4730 // Tail call needs the stack to be aligned.
4731 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4732 CallConv == CallingConv::Fast)
4733 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4735 // Calculate by how many bytes the stack has to be adjusted in case of tail
4736 // call optimization.
4737 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4739 // To protect arguments on the stack from being clobbered in a tail call,
4740 // force all the loads to happen before doing any other lowering.
4742 Chain = DAG.getStackArgumentTokenFactor(Chain);
4744 // Adjust the stack pointer for the new arguments...
4745 // These operations are automatically eliminated by the prolog/epilog pass
4746 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4748 SDValue CallSeqStart = Chain;
4750 // Load the return address and frame pointer so it can be move somewhere else
4753 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4756 // Set up a copy of the stack pointer for use loading and storing any
4757 // arguments that may not fit in the registers available for argument
4759 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4761 // Figure out which arguments are going to go in registers, and which in
4762 // memory. Also, if this is a vararg function, floating point operations
4763 // must be stored to our stack, and loaded into integer regs as well, if
4764 // any integer regs are available for argument passing.
4765 unsigned ArgOffset = LinkageSize;
4767 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4768 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4770 SmallVector<SDValue, 8> MemOpChains;
4771 for (unsigned i = 0; i != NumOps; ++i) {
4772 SDValue Arg = OutVals[i];
4773 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4774 EVT ArgVT = Outs[i].VT;
4775 EVT OrigVT = Outs[i].ArgVT;
4777 // PtrOff will be used to store the current argument to the stack if a
4778 // register cannot be found for it.
4781 // We re-align the argument offset for each argument, except when using the
4782 // fast calling convention, when we need to make sure we do that only when
4783 // we'll actually use a stack slot.
4784 auto ComputePtrOff = [&]() {
4785 /* Respect alignment of argument on the stack. */
4787 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4788 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4790 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4792 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4795 if (CallConv != CallingConv::Fast) {
4798 /* Compute GPR index associated with argument offset. */
4799 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4800 GPR_idx = std::min(GPR_idx, NumGPRs);
4803 // Promote integers to 64-bit values.
4804 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4805 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4806 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4807 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4810 // FIXME memcpy is used way more than necessary. Correctness first.
4811 // Note: "by value" is code for passing a structure by value, not
4813 if (Flags.isByVal()) {
4814 // Note: Size includes alignment padding, so
4815 // struct x { short a; char b; }
4816 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4817 // These are the proper values we need for right-justifying the
4818 // aggregate in a parameter register.
4819 unsigned Size = Flags.getByValSize();
4821 // An empty aggregate parameter takes up no storage and no
4826 if (CallConv == CallingConv::Fast)
4829 // All aggregates smaller than 8 bytes must be passed right-justified.
4830 if (Size==1 || Size==2 || Size==4) {
4831 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4832 if (GPR_idx != NumGPRs) {
4833 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4834 MachinePointerInfo(), VT,
4835 false, false, false, 0);
4836 MemOpChains.push_back(Load.getValue(1));
4837 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4839 ArgOffset += PtrByteSize;
4844 if (GPR_idx == NumGPRs && Size < 8) {
4845 SDValue AddPtr = PtrOff;
4846 if (!isLittleEndian) {
4847 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4848 PtrOff.getValueType());
4849 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4851 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4854 ArgOffset += PtrByteSize;
4857 // Copy entire object into memory. There are cases where gcc-generated
4858 // code assumes it is there, even if it could be put entirely into
4859 // registers. (This is not what the doc says.)
4861 // FIXME: The above statement is likely due to a misunderstanding of the
4862 // documents. All arguments must be copied into the parameter area BY
4863 // THE CALLEE in the event that the callee takes the address of any
4864 // formal argument. That has not yet been implemented. However, it is
4865 // reasonable to use the stack area as a staging area for the register
4868 // Skip this for small aggregates, as we will use the same slot for a
4869 // right-justified copy, below.
4871 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4875 // When a register is available, pass a small aggregate right-justified.
4876 if (Size < 8 && GPR_idx != NumGPRs) {
4877 // The easiest way to get this right-justified in a register
4878 // is to copy the structure into the rightmost portion of a
4879 // local variable slot, then load the whole slot into the
4881 // FIXME: The memcpy seems to produce pretty awful code for
4882 // small aggregates, particularly for packed ones.
4883 // FIXME: It would be preferable to use the slot in the
4884 // parameter save area instead of a new local variable.
4885 SDValue AddPtr = PtrOff;
4886 if (!isLittleEndian) {
4887 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
4888 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4890 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4894 // Load the slot into the register.
4895 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4896 MachinePointerInfo(),
4897 false, false, false, 0);
4898 MemOpChains.push_back(Load.getValue(1));
4899 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4901 // Done with this argument.
4902 ArgOffset += PtrByteSize;
4906 // For aggregates larger than PtrByteSize, copy the pieces of the
4907 // object that fit into registers from the parameter save area.
4908 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4909 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
4910 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4911 if (GPR_idx != NumGPRs) {
4912 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4913 MachinePointerInfo(),
4914 false, false, false, 0);
4915 MemOpChains.push_back(Load.getValue(1));
4916 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4917 ArgOffset += PtrByteSize;
4919 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4926 switch (Arg.getSimpleValueType().SimpleTy) {
4927 default: llvm_unreachable("Unexpected ValueType for argument!");
4931 // These can be scalar arguments or elements of an integer array type
4932 // passed directly. Clang may use those instead of "byval" aggregate
4933 // types to avoid forcing arguments to memory unnecessarily.
4934 if (GPR_idx != NumGPRs) {
4935 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4937 if (CallConv == CallingConv::Fast)
4940 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4941 true, isTailCall, false, MemOpChains,
4942 TailCallArguments, dl);
4943 if (CallConv == CallingConv::Fast)
4944 ArgOffset += PtrByteSize;
4946 if (CallConv != CallingConv::Fast)
4947 ArgOffset += PtrByteSize;
4951 // These can be scalar arguments or elements of a float array type
4952 // passed directly. The latter are used to implement ELFv2 homogenous
4953 // float aggregates.
4955 // Named arguments go into FPRs first, and once they overflow, the
4956 // remaining arguments go into GPRs and then the parameter save area.
4957 // Unnamed arguments for vararg functions always go to GPRs and
4958 // then the parameter save area. For now, put all arguments to vararg
4959 // routines always in both locations (FPR *and* GPR or stack slot).
4960 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4961 bool NeededLoad = false;
4963 // First load the argument into the next available FPR.
4964 if (FPR_idx != NumFPRs)
4965 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4967 // Next, load the argument into GPR or stack slot if needed.
4968 if (!NeedGPROrStack)
4970 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4971 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4972 // once we support fp <-> gpr moves.
4974 // In the non-vararg case, this can only ever happen in the
4975 // presence of f32 array types, since otherwise we never run
4976 // out of FPRs before running out of GPRs.
4979 // Double values are always passed in a single GPR.
4980 if (Arg.getValueType() != MVT::f32) {
4981 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4983 // Non-array float values are extended and passed in a GPR.
4984 } else if (!Flags.isInConsecutiveRegs()) {
4985 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4986 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4988 // If we have an array of floats, we collect every odd element
4989 // together with its predecessor into one GPR.
4990 } else if (ArgOffset % PtrByteSize != 0) {
4992 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4993 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4994 if (!isLittleEndian)
4996 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4998 // The final element, if even, goes into the first half of a GPR.
4999 } else if (Flags.isInConsecutiveRegsLast()) {
5000 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5001 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5002 if (!isLittleEndian)
5003 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5004 DAG.getConstant(32, dl, MVT::i32));
5006 // Non-final even elements are skipped; they will be handled
5007 // together the with subsequent argument on the next go-around.
5011 if (ArgVal.getNode())
5012 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5014 if (CallConv == CallingConv::Fast)
5017 // Single-precision floating-point values are mapped to the
5018 // second (rightmost) word of the stack doubleword.
5019 if (Arg.getValueType() == MVT::f32 &&
5020 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5021 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5022 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5025 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5026 true, isTailCall, false, MemOpChains,
5027 TailCallArguments, dl);
5031 // When passing an array of floats, the array occupies consecutive
5032 // space in the argument area; only round up to the next doubleword
5033 // at the end of the array. Otherwise, each float takes 8 bytes.
5034 if (CallConv != CallingConv::Fast || NeededLoad) {
5035 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5036 Flags.isInConsecutiveRegs()) ? 4 : 8;
5037 if (Flags.isInConsecutiveRegsLast())
5038 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5049 if (!Subtarget.hasQPX()) {
5050 // These can be scalar arguments or elements of a vector array type
5051 // passed directly. The latter are used to implement ELFv2 homogenous
5052 // vector aggregates.
5054 // For a varargs call, named arguments go into VRs or on the stack as
5055 // usual; unnamed arguments always go to the stack or the corresponding
5056 // GPRs when within range. For now, we always put the value in both
5057 // locations (or even all three).
5059 // We could elide this store in the case where the object fits
5060 // entirely in R registers. Maybe later.
5061 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5062 MachinePointerInfo(), false, false, 0);
5063 MemOpChains.push_back(Store);
5064 if (VR_idx != NumVRs) {
5065 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5066 MachinePointerInfo(),
5067 false, false, false, 0);
5068 MemOpChains.push_back(Load.getValue(1));
5070 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5071 Arg.getSimpleValueType() == MVT::v2i64) ?
5072 VSRH[VR_idx] : VR[VR_idx];
5075 RegsToPass.push_back(std::make_pair(VReg, Load));
5078 for (unsigned i=0; i<16; i+=PtrByteSize) {
5079 if (GPR_idx == NumGPRs)
5081 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5082 DAG.getConstant(i, dl, PtrVT));
5083 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5084 false, false, false, 0);
5085 MemOpChains.push_back(Load.getValue(1));
5086 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5091 // Non-varargs Altivec params go into VRs or on the stack.
5092 if (VR_idx != NumVRs) {
5093 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5094 Arg.getSimpleValueType() == MVT::v2i64) ?
5095 VSRH[VR_idx] : VR[VR_idx];
5098 RegsToPass.push_back(std::make_pair(VReg, Arg));
5100 if (CallConv == CallingConv::Fast)
5103 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5104 true, isTailCall, true, MemOpChains,
5105 TailCallArguments, dl);
5106 if (CallConv == CallingConv::Fast)
5110 if (CallConv != CallingConv::Fast)
5115 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5116 "Invalid QPX parameter type");
5121 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5123 // We could elide this store in the case where the object fits
5124 // entirely in R registers. Maybe later.
5125 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5126 MachinePointerInfo(), false, false, 0);
5127 MemOpChains.push_back(Store);
5128 if (QFPR_idx != NumQFPRs) {
5129 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5130 Store, PtrOff, MachinePointerInfo(),
5131 false, false, false, 0);
5132 MemOpChains.push_back(Load.getValue(1));
5133 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5135 ArgOffset += (IsF32 ? 16 : 32);
5136 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5137 if (GPR_idx == NumGPRs)
5139 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5140 DAG.getConstant(i, dl, PtrVT));
5141 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5142 false, false, false, 0);
5143 MemOpChains.push_back(Load.getValue(1));
5144 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5149 // Non-varargs QPX params go into registers or on the stack.
5150 if (QFPR_idx != NumQFPRs) {
5151 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5153 if (CallConv == CallingConv::Fast)
5156 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5157 true, isTailCall, true, MemOpChains,
5158 TailCallArguments, dl);
5159 if (CallConv == CallingConv::Fast)
5160 ArgOffset += (IsF32 ? 16 : 32);
5163 if (CallConv != CallingConv::Fast)
5164 ArgOffset += (IsF32 ? 16 : 32);
5170 assert(NumBytesActuallyUsed == ArgOffset);
5171 (void)NumBytesActuallyUsed;
5173 if (!MemOpChains.empty())
5174 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5176 // Check if this is an indirect call (MTCTR/BCTRL).
5177 // See PrepareCall() for more information about calls through function
5178 // pointers in the 64-bit SVR4 ABI.
5179 if (!isTailCall && !IsPatchPoint &&
5180 !isFunctionGlobalAddress(Callee) &&
5181 !isa<ExternalSymbolSDNode>(Callee)) {
5182 // Load r2 into a virtual register and store it to the TOC save area.
5183 setUsesTOCBasePtr(DAG);
5184 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5185 // TOC save area offset.
5186 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5187 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5188 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5189 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5190 MachinePointerInfo::getStack(TOCSaveOffset),
5192 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5193 // This does not mean the MTCTR instruction must use R12; it's easier
5194 // to model this as an extra parameter, so do that.
5195 if (isELFv2ABI && !IsPatchPoint)
5196 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5199 // Build a sequence of copy-to-reg nodes chained together with token chain
5200 // and flag operands which copy the outgoing args into the appropriate regs.
5202 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5203 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5204 RegsToPass[i].second, InFlag);
5205 InFlag = Chain.getValue(1);
5209 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5210 FPOp, true, TailCallArguments);
5212 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5213 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5214 NumBytes, Ins, InVals, CS);
5218 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5219 CallingConv::ID CallConv, bool isVarArg,
5220 bool isTailCall, bool IsPatchPoint,
5221 const SmallVectorImpl<ISD::OutputArg> &Outs,
5222 const SmallVectorImpl<SDValue> &OutVals,
5223 const SmallVectorImpl<ISD::InputArg> &Ins,
5224 SDLoc dl, SelectionDAG &DAG,
5225 SmallVectorImpl<SDValue> &InVals,
5226 ImmutableCallSite *CS) const {
5228 unsigned NumOps = Outs.size();
5230 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5231 bool isPPC64 = PtrVT == MVT::i64;
5232 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5234 MachineFunction &MF = DAG.getMachineFunction();
5236 // Mark this function as potentially containing a function that contains a
5237 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5238 // and restoring the callers stack pointer in this functions epilog. This is
5239 // done because by tail calling the called function might overwrite the value
5240 // in this function's (MF) stack pointer stack slot 0(SP).
5241 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5242 CallConv == CallingConv::Fast)
5243 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5245 // Count how many bytes are to be pushed on the stack, including the linkage
5246 // area, and parameter passing area. We start with 24/48 bytes, which is
5247 // prereserved space for [SP][CR][LR][3 x unused].
5248 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5249 unsigned NumBytes = LinkageSize;
5251 // Add up all the space actually used.
5252 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5253 // they all go in registers, but we must reserve stack space for them for
5254 // possible use by the caller. In varargs or 64-bit calls, parameters are
5255 // assigned stack space in order, with padding so Altivec parameters are
5257 unsigned nAltivecParamsAtEnd = 0;
5258 for (unsigned i = 0; i != NumOps; ++i) {
5259 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5260 EVT ArgVT = Outs[i].VT;
5261 // Varargs Altivec parameters are padded to a 16 byte boundary.
5262 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5263 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5264 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5265 if (!isVarArg && !isPPC64) {
5266 // Non-varargs Altivec parameters go after all the non-Altivec
5267 // parameters; handle those later so we know how much padding we need.
5268 nAltivecParamsAtEnd++;
5271 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5272 NumBytes = ((NumBytes+15)/16)*16;
5274 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5277 // Allow for Altivec parameters at the end, if needed.
5278 if (nAltivecParamsAtEnd) {
5279 NumBytes = ((NumBytes+15)/16)*16;
5280 NumBytes += 16*nAltivecParamsAtEnd;
5283 // The prolog code of the callee may store up to 8 GPR argument registers to
5284 // the stack, allowing va_start to index over them in memory if its varargs.
5285 // Because we cannot tell if this is needed on the caller side, we have to
5286 // conservatively assume that it is needed. As such, make sure we have at
5287 // least enough stack space for the caller to store the 8 GPRs.
5288 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5290 // Tail call needs the stack to be aligned.
5291 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5292 CallConv == CallingConv::Fast)
5293 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5295 // Calculate by how many bytes the stack has to be adjusted in case of tail
5296 // call optimization.
5297 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5299 // To protect arguments on the stack from being clobbered in a tail call,
5300 // force all the loads to happen before doing any other lowering.
5302 Chain = DAG.getStackArgumentTokenFactor(Chain);
5304 // Adjust the stack pointer for the new arguments...
5305 // These operations are automatically eliminated by the prolog/epilog pass
5306 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5308 SDValue CallSeqStart = Chain;
5310 // Load the return address and frame pointer so it can be move somewhere else
5313 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5316 // Set up a copy of the stack pointer for use loading and storing any
5317 // arguments that may not fit in the registers available for argument
5321 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5323 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5325 // Figure out which arguments are going to go in registers, and which in
5326 // memory. Also, if this is a vararg function, floating point operations
5327 // must be stored to our stack, and loaded into integer regs as well, if
5328 // any integer regs are available for argument passing.
5329 unsigned ArgOffset = LinkageSize;
5330 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5332 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5333 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5334 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5336 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5337 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5338 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5340 static const MCPhysReg VR[] = {
5341 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5342 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5344 const unsigned NumGPRs = array_lengthof(GPR_32);
5345 const unsigned NumFPRs = 13;
5346 const unsigned NumVRs = array_lengthof(VR);
5348 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5350 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5351 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5353 SmallVector<SDValue, 8> MemOpChains;
5354 for (unsigned i = 0; i != NumOps; ++i) {
5355 SDValue Arg = OutVals[i];
5356 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5358 // PtrOff will be used to store the current argument to the stack if a
5359 // register cannot be found for it.
5362 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5364 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5366 // On PPC64, promote integers to 64-bit values.
5367 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5368 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5369 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5370 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5373 // FIXME memcpy is used way more than necessary. Correctness first.
5374 // Note: "by value" is code for passing a structure by value, not
5376 if (Flags.isByVal()) {
5377 unsigned Size = Flags.getByValSize();
5378 // Very small objects are passed right-justified. Everything else is
5379 // passed left-justified.
5380 if (Size==1 || Size==2) {
5381 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5382 if (GPR_idx != NumGPRs) {
5383 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5384 MachinePointerInfo(), VT,
5385 false, false, false, 0);
5386 MemOpChains.push_back(Load.getValue(1));
5387 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5389 ArgOffset += PtrByteSize;
5391 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5392 PtrOff.getValueType());
5393 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5394 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5397 ArgOffset += PtrByteSize;
5401 // Copy entire object into memory. There are cases where gcc-generated
5402 // code assumes it is there, even if it could be put entirely into
5403 // registers. (This is not what the doc says.)
5404 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5408 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5409 // copy the pieces of the object that fit into registers from the
5410 // parameter save area.
5411 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5412 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5413 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5414 if (GPR_idx != NumGPRs) {
5415 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5416 MachinePointerInfo(),
5417 false, false, false, 0);
5418 MemOpChains.push_back(Load.getValue(1));
5419 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5420 ArgOffset += PtrByteSize;
5422 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5429 switch (Arg.getSimpleValueType().SimpleTy) {
5430 default: llvm_unreachable("Unexpected ValueType for argument!");
5434 if (GPR_idx != NumGPRs) {
5435 if (Arg.getValueType() == MVT::i1)
5436 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5438 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5440 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5441 isPPC64, isTailCall, false, MemOpChains,
5442 TailCallArguments, dl);
5444 ArgOffset += PtrByteSize;
5448 if (FPR_idx != NumFPRs) {
5449 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5452 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5453 MachinePointerInfo(), false, false, 0);
5454 MemOpChains.push_back(Store);
5456 // Float varargs are always shadowed in available integer registers
5457 if (GPR_idx != NumGPRs) {
5458 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5459 MachinePointerInfo(), false, false,
5461 MemOpChains.push_back(Load.getValue(1));
5462 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5464 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5465 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5466 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5467 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5468 MachinePointerInfo(),
5469 false, false, false, 0);
5470 MemOpChains.push_back(Load.getValue(1));
5471 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5474 // If we have any FPRs remaining, we may also have GPRs remaining.
5475 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5477 if (GPR_idx != NumGPRs)
5479 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5480 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5484 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5485 isPPC64, isTailCall, false, MemOpChains,
5486 TailCallArguments, dl);
5490 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5497 // These go aligned on the stack, or in the corresponding R registers
5498 // when within range. The Darwin PPC ABI doc claims they also go in
5499 // V registers; in fact gcc does this only for arguments that are
5500 // prototyped, not for those that match the ... We do it for all
5501 // arguments, seems to work.
5502 while (ArgOffset % 16 !=0) {
5503 ArgOffset += PtrByteSize;
5504 if (GPR_idx != NumGPRs)
5507 // We could elide this store in the case where the object fits
5508 // entirely in R registers. Maybe later.
5509 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5510 DAG.getConstant(ArgOffset, dl, PtrVT));
5511 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5512 MachinePointerInfo(), false, false, 0);
5513 MemOpChains.push_back(Store);
5514 if (VR_idx != NumVRs) {
5515 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5516 MachinePointerInfo(),
5517 false, false, false, 0);
5518 MemOpChains.push_back(Load.getValue(1));
5519 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5522 for (unsigned i=0; i<16; i+=PtrByteSize) {
5523 if (GPR_idx == NumGPRs)
5525 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5526 DAG.getConstant(i, dl, PtrVT));
5527 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5528 false, false, false, 0);
5529 MemOpChains.push_back(Load.getValue(1));
5530 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5535 // Non-varargs Altivec params generally go in registers, but have
5536 // stack space allocated at the end.
5537 if (VR_idx != NumVRs) {
5538 // Doesn't have GPR space allocated.
5539 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5540 } else if (nAltivecParamsAtEnd==0) {
5541 // We are emitting Altivec params in order.
5542 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5543 isPPC64, isTailCall, true, MemOpChains,
5544 TailCallArguments, dl);
5550 // If all Altivec parameters fit in registers, as they usually do,
5551 // they get stack space following the non-Altivec parameters. We
5552 // don't track this here because nobody below needs it.
5553 // If there are more Altivec parameters than fit in registers emit
5555 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5557 // Offset is aligned; skip 1st 12 params which go in V registers.
5558 ArgOffset = ((ArgOffset+15)/16)*16;
5560 for (unsigned i = 0; i != NumOps; ++i) {
5561 SDValue Arg = OutVals[i];
5562 EVT ArgType = Outs[i].VT;
5563 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5564 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5567 // We are emitting Altivec params in order.
5568 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5569 isPPC64, isTailCall, true, MemOpChains,
5570 TailCallArguments, dl);
5577 if (!MemOpChains.empty())
5578 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5580 // On Darwin, R12 must contain the address of an indirect callee. This does
5581 // not mean the MTCTR instruction must use R12; it's easier to model this as
5582 // an extra parameter, so do that.
5584 !isFunctionGlobalAddress(Callee) &&
5585 !isa<ExternalSymbolSDNode>(Callee) &&
5586 !isBLACompatibleAddress(Callee, DAG))
5587 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5588 PPC::R12), Callee));
5590 // Build a sequence of copy-to-reg nodes chained together with token chain
5591 // and flag operands which copy the outgoing args into the appropriate regs.
5593 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5594 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5595 RegsToPass[i].second, InFlag);
5596 InFlag = Chain.getValue(1);
5600 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5601 FPOp, true, TailCallArguments);
5603 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5604 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5605 NumBytes, Ins, InVals, CS);
5609 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5610 MachineFunction &MF, bool isVarArg,
5611 const SmallVectorImpl<ISD::OutputArg> &Outs,
5612 LLVMContext &Context) const {
5613 SmallVector<CCValAssign, 16> RVLocs;
5614 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5615 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5619 PPCTargetLowering::LowerReturn(SDValue Chain,
5620 CallingConv::ID CallConv, bool isVarArg,
5621 const SmallVectorImpl<ISD::OutputArg> &Outs,
5622 const SmallVectorImpl<SDValue> &OutVals,
5623 SDLoc dl, SelectionDAG &DAG) const {
5625 SmallVector<CCValAssign, 16> RVLocs;
5626 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5628 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5631 SmallVector<SDValue, 4> RetOps(1, Chain);
5633 // Copy the result values into the output registers.
5634 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5635 CCValAssign &VA = RVLocs[i];
5636 assert(VA.isRegLoc() && "Can only return in registers!");
5638 SDValue Arg = OutVals[i];
5640 switch (VA.getLocInfo()) {
5641 default: llvm_unreachable("Unknown loc info!");
5642 case CCValAssign::Full: break;
5643 case CCValAssign::AExt:
5644 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5646 case CCValAssign::ZExt:
5647 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5649 case CCValAssign::SExt:
5650 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5654 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5655 Flag = Chain.getValue(1);
5656 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5659 RetOps[0] = Chain; // Update chain.
5661 // Add the flag if we have it.
5663 RetOps.push_back(Flag);
5665 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5668 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5669 const PPCSubtarget &Subtarget) const {
5670 // When we pop the dynamic allocation we need to restore the SP link.
5673 // Get the corect type for pointers.
5674 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5676 // Construct the stack pointer operand.
5677 bool isPPC64 = Subtarget.isPPC64();
5678 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5679 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5681 // Get the operands for the STACKRESTORE.
5682 SDValue Chain = Op.getOperand(0);
5683 SDValue SaveSP = Op.getOperand(1);
5685 // Load the old link SP.
5686 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5687 MachinePointerInfo(),
5688 false, false, false, 0);
5690 // Restore the stack pointer.
5691 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5693 // Store the old link SP.
5694 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5701 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5702 MachineFunction &MF = DAG.getMachineFunction();
5703 bool isPPC64 = Subtarget.isPPC64();
5704 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5706 // Get current frame pointer save index. The users of this index will be
5707 // primarily DYNALLOC instructions.
5708 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5709 int RASI = FI->getReturnAddrSaveIndex();
5711 // If the frame pointer save index hasn't been defined yet.
5713 // Find out what the fix offset of the frame pointer save area.
5714 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5715 // Allocate the frame index for frame pointer save area.
5716 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5718 FI->setReturnAddrSaveIndex(RASI);
5720 return DAG.getFrameIndex(RASI, PtrVT);
5724 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5725 MachineFunction &MF = DAG.getMachineFunction();
5726 bool isPPC64 = Subtarget.isPPC64();
5727 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5729 // Get current frame pointer save index. The users of this index will be
5730 // primarily DYNALLOC instructions.
5731 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5732 int FPSI = FI->getFramePointerSaveIndex();
5734 // If the frame pointer save index hasn't been defined yet.
5736 // Find out what the fix offset of the frame pointer save area.
5737 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5738 // Allocate the frame index for frame pointer save area.
5739 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5741 FI->setFramePointerSaveIndex(FPSI);
5743 return DAG.getFrameIndex(FPSI, PtrVT);
5746 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5748 const PPCSubtarget &Subtarget) const {
5750 SDValue Chain = Op.getOperand(0);
5751 SDValue Size = Op.getOperand(1);
5754 // Get the corect type for pointers.
5755 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5757 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5758 DAG.getConstant(0, dl, PtrVT), Size);
5759 // Construct a node for the frame pointer save index.
5760 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5761 // Build a DYNALLOC node.
5762 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5763 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5764 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5767 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5768 SelectionDAG &DAG) const {
5770 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5771 DAG.getVTList(MVT::i32, MVT::Other),
5772 Op.getOperand(0), Op.getOperand(1));
5775 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5776 SelectionDAG &DAG) const {
5778 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5779 Op.getOperand(0), Op.getOperand(1));
5782 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5783 if (Op.getValueType().isVector())
5784 return LowerVectorLoad(Op, DAG);
5786 assert(Op.getValueType() == MVT::i1 &&
5787 "Custom lowering only for i1 loads");
5789 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5792 LoadSDNode *LD = cast<LoadSDNode>(Op);
5794 SDValue Chain = LD->getChain();
5795 SDValue BasePtr = LD->getBasePtr();
5796 MachineMemOperand *MMO = LD->getMemOperand();
5798 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5799 BasePtr, MVT::i8, MMO);
5800 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5802 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5803 return DAG.getMergeValues(Ops, dl);
5806 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5807 if (Op.getOperand(1).getValueType().isVector())
5808 return LowerVectorStore(Op, DAG);
5810 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5811 "Custom lowering only for i1 stores");
5813 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5816 StoreSDNode *ST = cast<StoreSDNode>(Op);
5818 SDValue Chain = ST->getChain();
5819 SDValue BasePtr = ST->getBasePtr();
5820 SDValue Value = ST->getValue();
5821 MachineMemOperand *MMO = ST->getMemOperand();
5823 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5824 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5827 // FIXME: Remove this once the ANDI glue bug is fixed:
5828 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5829 assert(Op.getValueType() == MVT::i1 &&
5830 "Custom lowering only for i1 results");
5833 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5837 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5839 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5840 // Not FP? Not a fsel.
5841 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5842 !Op.getOperand(2).getValueType().isFloatingPoint())
5845 // We might be able to do better than this under some circumstances, but in
5846 // general, fsel-based lowering of select is a finite-math-only optimization.
5847 // For more information, see section F.3 of the 2.06 ISA specification.
5848 if (!DAG.getTarget().Options.NoInfsFPMath ||
5849 !DAG.getTarget().Options.NoNaNsFPMath)
5852 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5854 EVT ResVT = Op.getValueType();
5855 EVT CmpVT = Op.getOperand(0).getValueType();
5856 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5857 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5860 // If the RHS of the comparison is a 0.0, we don't need to do the
5861 // subtraction at all.
5863 if (isFloatingPointZero(RHS))
5865 default: break; // SETUO etc aren't handled by fsel.
5869 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5870 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5871 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5872 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5873 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5874 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5875 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5878 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5881 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5882 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5883 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5886 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5889 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5890 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5891 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5892 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5897 default: break; // SETUO etc aren't handled by fsel.
5901 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5902 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5903 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5904 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5905 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5906 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5907 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5908 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5911 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5912 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5913 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5914 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5917 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5918 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5919 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5920 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5923 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5924 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5925 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5926 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5929 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5930 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5931 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5932 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5937 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5940 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5941 SDValue Src = Op.getOperand(0);
5942 if (Src.getValueType() == MVT::f32)
5943 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5946 switch (Op.getSimpleValueType().SimpleTy) {
5947 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5950 Op.getOpcode() == ISD::FP_TO_SINT
5952 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5956 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5957 "i64 FP_TO_UINT is supported only with FPCVT");
5958 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5964 // Convert the FP value to an int value through memory.
5965 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5966 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5967 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5968 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5969 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5971 // Emit a store to the stack slot.
5974 MachineFunction &MF = DAG.getMachineFunction();
5975 MachineMemOperand *MMO =
5976 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5977 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5978 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5979 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5981 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5982 MPI, false, false, 0);
5984 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5986 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5987 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5988 DAG.getConstant(4, dl, FIPtr.getValueType()));
5989 MPI = MPI.getWithOffset(4);
5997 /// \brief Custom lowers floating point to integer conversions to use
5998 /// the direct move instructions available in ISA 2.07 to avoid the
5999 /// need for load/store combinations.
6000 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6003 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6004 SDValue Src = Op.getOperand(0);
6006 if (Src.getValueType() == MVT::f32)
6007 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6010 switch (Op.getSimpleValueType().SimpleTy) {
6011 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6014 Op.getOpcode() == ISD::FP_TO_SINT
6016 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6018 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6021 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6022 "i64 FP_TO_UINT is supported only with FPCVT");
6023 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6026 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6032 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6034 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6035 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6038 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6040 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6041 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6045 // We're trying to insert a regular store, S, and then a load, L. If the
6046 // incoming value, O, is a load, we might just be able to have our load use the
6047 // address used by O. However, we don't know if anything else will store to
6048 // that address before we can load from it. To prevent this situation, we need
6049 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6050 // the same chain operand as O, we create a token factor from the chain results
6051 // of O and L, and we replace all uses of O's chain result with that token
6052 // factor (see spliceIntoChain below for this last part).
6053 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6056 ISD::LoadExtType ET) const {
6058 if (ET == ISD::NON_EXTLOAD &&
6059 (Op.getOpcode() == ISD::FP_TO_UINT ||
6060 Op.getOpcode() == ISD::FP_TO_SINT) &&
6061 isOperationLegalOrCustom(Op.getOpcode(),
6062 Op.getOperand(0).getValueType())) {
6064 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6068 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6069 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6070 LD->isNonTemporal())
6072 if (LD->getMemoryVT() != MemVT)
6075 RLI.Ptr = LD->getBasePtr();
6076 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6077 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6078 "Non-pre-inc AM on PPC?");
6079 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6083 RLI.Chain = LD->getChain();
6084 RLI.MPI = LD->getPointerInfo();
6085 RLI.IsInvariant = LD->isInvariant();
6086 RLI.Alignment = LD->getAlignment();
6087 RLI.AAInfo = LD->getAAInfo();
6088 RLI.Ranges = LD->getRanges();
6090 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6094 // Given the head of the old chain, ResChain, insert a token factor containing
6095 // it and NewResChain, and make users of ResChain now be users of that token
6097 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6098 SDValue NewResChain,
6099 SelectionDAG &DAG) const {
6103 SDLoc dl(NewResChain);
6105 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6106 NewResChain, DAG.getUNDEF(MVT::Other));
6107 assert(TF.getNode() != NewResChain.getNode() &&
6108 "A new TF really is required here");
6110 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6111 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6114 /// \brief Custom lowers integer to floating point conversions to use
6115 /// the direct move instructions available in ISA 2.07 to avoid the
6116 /// need for load/store combinations.
6117 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6120 assert((Op.getValueType() == MVT::f32 ||
6121 Op.getValueType() == MVT::f64) &&
6122 "Invalid floating point type as target of conversion");
6123 assert(Subtarget.hasFPCVT() &&
6124 "Int to FP conversions with direct moves require FPCVT");
6126 SDValue Src = Op.getOperand(0);
6127 bool SinglePrec = Op.getValueType() == MVT::f32;
6128 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6129 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6130 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6131 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6134 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6136 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6139 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6140 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6146 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6147 SelectionDAG &DAG) const {
6150 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6151 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6154 SDValue Value = Op.getOperand(0);
6155 // The values are now known to be -1 (false) or 1 (true). To convert this
6156 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6157 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6158 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6160 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6161 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6162 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6164 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6166 if (Op.getValueType() != MVT::v4f64)
6167 Value = DAG.getNode(ISD::FP_ROUND, dl,
6168 Op.getValueType(), Value,
6169 DAG.getIntPtrConstant(1, dl));
6173 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6174 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6177 if (Op.getOperand(0).getValueType() == MVT::i1)
6178 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6179 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6180 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6182 // If we have direct moves, we can do all the conversion, skip the store/load
6183 // however, without FPCVT we can't do most conversions.
6184 if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6185 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6187 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6188 "UINT_TO_FP is supported only with FPCVT");
6190 // If we have FCFIDS, then use it when converting to single-precision.
6191 // Otherwise, convert to double-precision and then round.
6192 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6193 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6195 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6197 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6201 if (Op.getOperand(0).getValueType() == MVT::i64) {
6202 SDValue SINT = Op.getOperand(0);
6203 // When converting to single-precision, we actually need to convert
6204 // to double-precision first and then round to single-precision.
6205 // To avoid double-rounding effects during that operation, we have
6206 // to prepare the input operand. Bits that might be truncated when
6207 // converting to double-precision are replaced by a bit that won't
6208 // be lost at this stage, but is below the single-precision rounding
6211 // However, if -enable-unsafe-fp-math is in effect, accept double
6212 // rounding to avoid the extra overhead.
6213 if (Op.getValueType() == MVT::f32 &&
6214 !Subtarget.hasFPCVT() &&
6215 !DAG.getTarget().Options.UnsafeFPMath) {
6217 // Twiddle input to make sure the low 11 bits are zero. (If this
6218 // is the case, we are guaranteed the value will fit into the 53 bit
6219 // mantissa of an IEEE double-precision value without rounding.)
6220 // If any of those low 11 bits were not zero originally, make sure
6221 // bit 12 (value 2048) is set instead, so that the final rounding
6222 // to single-precision gets the correct result.
6223 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6224 SINT, DAG.getConstant(2047, dl, MVT::i64));
6225 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6226 Round, DAG.getConstant(2047, dl, MVT::i64));
6227 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6228 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6229 Round, DAG.getConstant(-2048, dl, MVT::i64));
6231 // However, we cannot use that value unconditionally: if the magnitude
6232 // of the input value is small, the bit-twiddling we did above might
6233 // end up visibly changing the output. Fortunately, in that case, we
6234 // don't need to twiddle bits since the original input will convert
6235 // exactly to double-precision floating-point already. Therefore,
6236 // construct a conditional to use the original value if the top 11
6237 // bits are all sign-bit copies, and use the rounded value computed
6239 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6240 SINT, DAG.getConstant(53, dl, MVT::i32));
6241 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6242 Cond, DAG.getConstant(1, dl, MVT::i64));
6243 Cond = DAG.getSetCC(dl, MVT::i32,
6244 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6246 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6252 MachineFunction &MF = DAG.getMachineFunction();
6253 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6254 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6255 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6257 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6258 } else if (Subtarget.hasLFIWAX() &&
6259 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6260 MachineMemOperand *MMO =
6261 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6262 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6263 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6264 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6265 DAG.getVTList(MVT::f64, MVT::Other),
6266 Ops, MVT::i32, MMO);
6267 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6268 } else if (Subtarget.hasFPCVT() &&
6269 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6270 MachineMemOperand *MMO =
6271 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6272 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6273 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6274 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6275 DAG.getVTList(MVT::f64, MVT::Other),
6276 Ops, MVT::i32, MMO);
6277 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6278 } else if (((Subtarget.hasLFIWAX() &&
6279 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6280 (Subtarget.hasFPCVT() &&
6281 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6282 SINT.getOperand(0).getValueType() == MVT::i32) {
6283 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6284 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6286 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6287 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6290 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6291 MachinePointerInfo::getFixedStack(FrameIdx),
6294 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6295 "Expected an i32 store");
6299 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6302 MachineMemOperand *MMO =
6303 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6304 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6305 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6306 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6307 PPCISD::LFIWZX : PPCISD::LFIWAX,
6308 dl, DAG.getVTList(MVT::f64, MVT::Other),
6309 Ops, MVT::i32, MMO);
6311 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6313 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6315 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6316 FP = DAG.getNode(ISD::FP_ROUND, dl,
6317 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6321 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6322 "Unhandled INT_TO_FP type in custom expander!");
6323 // Since we only generate this in 64-bit mode, we can take advantage of
6324 // 64-bit registers. In particular, sign extend the input value into the
6325 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6326 // then lfd it and fcfid it.
6327 MachineFunction &MF = DAG.getMachineFunction();
6328 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6329 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6332 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6335 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6337 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6338 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6340 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6341 MachinePointerInfo::getFixedStack(FrameIdx),
6344 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6345 "Expected an i32 store");
6349 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6353 MachineMemOperand *MMO =
6354 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6355 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6356 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6357 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6358 PPCISD::LFIWZX : PPCISD::LFIWAX,
6359 dl, DAG.getVTList(MVT::f64, MVT::Other),
6360 Ops, MVT::i32, MMO);
6362 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6364 assert(Subtarget.isPPC64() &&
6365 "i32->FP without LFIWAX supported only on PPC64");
6367 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6368 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6370 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6373 // STD the extended value into the stack slot.
6374 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6375 MachinePointerInfo::getFixedStack(FrameIdx),
6378 // Load the value as a double.
6379 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6380 MachinePointerInfo::getFixedStack(FrameIdx),
6381 false, false, false, 0);
6384 // FCFID it and return it.
6385 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6386 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6387 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6388 DAG.getIntPtrConstant(0, dl));
6392 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6393 SelectionDAG &DAG) const {
6396 The rounding mode is in bits 30:31 of FPSR, and has the following
6403 FLT_ROUNDS, on the other hand, expects the following:
6410 To perform the conversion, we do:
6411 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6414 MachineFunction &MF = DAG.getMachineFunction();
6415 EVT VT = Op.getValueType();
6416 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6418 // Save FP Control Word to register
6420 MVT::f64, // return register
6421 MVT::Glue // unused in this context
6423 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6425 // Save FP register to stack slot
6426 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6427 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6428 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6429 StackSlot, MachinePointerInfo(), false, false,0);
6431 // Load FP Control Word from low 32 bits of stack slot.
6432 SDValue Four = DAG.getConstant(4, dl, PtrVT);
6433 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6434 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6435 false, false, false, 0);
6437 // Transform as necessary
6439 DAG.getNode(ISD::AND, dl, MVT::i32,
6440 CWD, DAG.getConstant(3, dl, MVT::i32));
6442 DAG.getNode(ISD::SRL, dl, MVT::i32,
6443 DAG.getNode(ISD::AND, dl, MVT::i32,
6444 DAG.getNode(ISD::XOR, dl, MVT::i32,
6445 CWD, DAG.getConstant(3, dl, MVT::i32)),
6446 DAG.getConstant(3, dl, MVT::i32)),
6447 DAG.getConstant(1, dl, MVT::i32));
6450 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6452 return DAG.getNode((VT.getSizeInBits() < 16 ?
6453 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6456 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6457 EVT VT = Op.getValueType();
6458 unsigned BitWidth = VT.getSizeInBits();
6460 assert(Op.getNumOperands() == 3 &&
6461 VT == Op.getOperand(1).getValueType() &&
6464 // Expand into a bunch of logical ops. Note that these ops
6465 // depend on the PPC behavior for oversized shift amounts.
6466 SDValue Lo = Op.getOperand(0);
6467 SDValue Hi = Op.getOperand(1);
6468 SDValue Amt = Op.getOperand(2);
6469 EVT AmtVT = Amt.getValueType();
6471 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6472 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6473 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6474 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6475 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6476 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6477 DAG.getConstant(-BitWidth, dl, AmtVT));
6478 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6479 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6480 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6481 SDValue OutOps[] = { OutLo, OutHi };
6482 return DAG.getMergeValues(OutOps, dl);
6485 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6486 EVT VT = Op.getValueType();
6488 unsigned BitWidth = VT.getSizeInBits();
6489 assert(Op.getNumOperands() == 3 &&
6490 VT == Op.getOperand(1).getValueType() &&
6493 // Expand into a bunch of logical ops. Note that these ops
6494 // depend on the PPC behavior for oversized shift amounts.
6495 SDValue Lo = Op.getOperand(0);
6496 SDValue Hi = Op.getOperand(1);
6497 SDValue Amt = Op.getOperand(2);
6498 EVT AmtVT = Amt.getValueType();
6500 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6501 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6502 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6503 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6504 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6505 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6506 DAG.getConstant(-BitWidth, dl, AmtVT));
6507 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6508 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6509 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6510 SDValue OutOps[] = { OutLo, OutHi };
6511 return DAG.getMergeValues(OutOps, dl);
6514 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6516 EVT VT = Op.getValueType();
6517 unsigned BitWidth = VT.getSizeInBits();
6518 assert(Op.getNumOperands() == 3 &&
6519 VT == Op.getOperand(1).getValueType() &&
6522 // Expand into a bunch of logical ops, followed by a select_cc.
6523 SDValue Lo = Op.getOperand(0);
6524 SDValue Hi = Op.getOperand(1);
6525 SDValue Amt = Op.getOperand(2);
6526 EVT AmtVT = Amt.getValueType();
6528 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6529 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6530 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6531 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6532 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6533 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6534 DAG.getConstant(-BitWidth, dl, AmtVT));
6535 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6536 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6537 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6538 Tmp4, Tmp6, ISD::SETLE);
6539 SDValue OutOps[] = { OutLo, OutHi };
6540 return DAG.getMergeValues(OutOps, dl);
6543 //===----------------------------------------------------------------------===//
6544 // Vector related lowering.
6547 /// BuildSplatI - Build a canonical splati of Val with an element size of
6548 /// SplatSize. Cast the result to VT.
6549 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6550 SelectionDAG &DAG, SDLoc dl) {
6551 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6553 static const MVT VTys[] = { // canonical VT to use for each size.
6554 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6557 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6559 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6563 EVT CanonicalVT = VTys[SplatSize-1];
6565 // Build a canonical splat for this value.
6566 SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6567 SmallVector<SDValue, 8> Ops;
6568 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6569 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6570 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6573 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6574 /// specified intrinsic ID.
6575 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6576 SelectionDAG &DAG, SDLoc dl,
6577 EVT DestVT = MVT::Other) {
6578 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6579 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6580 DAG.getConstant(IID, dl, MVT::i32), Op);
6583 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6584 /// specified intrinsic ID.
6585 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6586 SelectionDAG &DAG, SDLoc dl,
6587 EVT DestVT = MVT::Other) {
6588 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6589 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6590 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6593 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6594 /// specified intrinsic ID.
6595 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6596 SDValue Op2, SelectionDAG &DAG,
6597 SDLoc dl, EVT DestVT = MVT::Other) {
6598 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6599 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6600 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6604 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6605 /// amount. The result has the specified value type.
6606 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6607 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6608 // Force LHS/RHS to be the right type.
6609 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6610 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6613 for (unsigned i = 0; i != 16; ++i)
6615 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6616 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6619 // If this is a case we can't handle, return null and let the default
6620 // expansion code take care of it. If we CAN select this case, and if it
6621 // selects to a single instruction, return Op. Otherwise, if we can codegen
6622 // this case more efficiently than a constant pool load, lower it to the
6623 // sequence of ops that should be used.
6624 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6625 SelectionDAG &DAG) const {
6627 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6628 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6630 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6631 // We first build an i32 vector, load it into a QPX register,
6632 // then convert it to a floating-point vector and compare it
6633 // to a zero vector to get the boolean result.
6634 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6635 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6636 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6637 EVT PtrVT = getPointerTy();
6638 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6640 assert(BVN->getNumOperands() == 4 &&
6641 "BUILD_VECTOR for v4i1 does not have 4 operands");
6643 bool IsConst = true;
6644 for (unsigned i = 0; i < 4; ++i) {
6645 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6646 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6654 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6656 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6658 SmallVector<Constant*, 4> CV(4, NegOne);
6659 for (unsigned i = 0; i < 4; ++i) {
6660 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6661 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6662 else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6663 getConstantIntValue()->isZero())
6669 Constant *CP = ConstantVector::get(CV);
6670 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6671 16 /* alignment */);
6673 SmallVector<SDValue, 2> Ops;
6674 Ops.push_back(DAG.getEntryNode());
6675 Ops.push_back(CPIdx);
6677 SmallVector<EVT, 2> ValueVTs;
6678 ValueVTs.push_back(MVT::v4i1);
6679 ValueVTs.push_back(MVT::Other); // chain
6680 SDVTList VTs = DAG.getVTList(ValueVTs);
6682 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6683 dl, VTs, Ops, MVT::v4f32,
6684 MachinePointerInfo::getConstantPool());
6687 SmallVector<SDValue, 4> Stores;
6688 for (unsigned i = 0; i < 4; ++i) {
6689 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6691 unsigned Offset = 4*i;
6692 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6693 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6695 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6696 if (StoreSize > 4) {
6697 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6698 BVN->getOperand(i), Idx,
6699 PtrInfo.getWithOffset(Offset),
6700 MVT::i32, false, false, 0));
6702 SDValue StoreValue = BVN->getOperand(i);
6704 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6706 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6708 PtrInfo.getWithOffset(Offset),
6714 if (!Stores.empty())
6715 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6717 StoreChain = DAG.getEntryNode();
6719 // Now load from v4i32 into the QPX register; this will extend it to
6720 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6721 // is typed as v4f64 because the QPX register integer states are not
6722 // explicitly represented.
6724 SmallVector<SDValue, 2> Ops;
6725 Ops.push_back(StoreChain);
6726 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6727 Ops.push_back(FIdx);
6729 SmallVector<EVT, 2> ValueVTs;
6730 ValueVTs.push_back(MVT::v4f64);
6731 ValueVTs.push_back(MVT::Other); // chain
6732 SDVTList VTs = DAG.getVTList(ValueVTs);
6734 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6735 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6736 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6737 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6740 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6741 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6742 FPZeros, FPZeros, FPZeros, FPZeros);
6744 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6747 // All other QPX vectors are handled by generic code.
6748 if (Subtarget.hasQPX())
6751 // Check if this is a splat of a constant value.
6752 APInt APSplatBits, APSplatUndef;
6753 unsigned SplatBitSize;
6755 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6756 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6760 unsigned SplatBits = APSplatBits.getZExtValue();
6761 unsigned SplatUndef = APSplatUndef.getZExtValue();
6762 unsigned SplatSize = SplatBitSize / 8;
6764 // First, handle single instruction cases.
6767 if (SplatBits == 0) {
6768 // Canonicalize all zero vectors to be v4i32.
6769 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6770 SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6771 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6772 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6777 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6778 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6780 if (SextVal >= -16 && SextVal <= 15)
6781 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6784 // Two instruction sequences.
6786 // If this value is in the range [-32,30] and is even, use:
6787 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6788 // If this value is in the range [17,31] and is odd, use:
6789 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6790 // If this value is in the range [-31,-17] and is odd, use:
6791 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6792 // Note the last two are three-instruction sequences.
6793 if (SextVal >= -32 && SextVal <= 31) {
6794 // To avoid having these optimizations undone by constant folding,
6795 // we convert to a pseudo that will be expanded later into one of
6797 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6798 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6799 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6800 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6801 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6802 if (VT == Op.getValueType())
6805 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6808 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6809 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6811 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6812 // Make -1 and vspltisw -1:
6813 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6815 // Make the VSLW intrinsic, computing 0x8000_0000.
6816 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6819 // xor by OnesV to invert it.
6820 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6821 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6824 // Check to see if this is a wide variety of vsplti*, binop self cases.
6825 static const signed char SplatCsts[] = {
6826 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6827 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6830 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6831 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6832 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6833 int i = SplatCsts[idx];
6835 // Figure out what shift amount will be used by altivec if shifted by i in
6837 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6839 // vsplti + shl self.
6840 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6841 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6842 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6843 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6844 Intrinsic::ppc_altivec_vslw
6846 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6847 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6850 // vsplti + srl self.
6851 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6852 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6853 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6854 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6855 Intrinsic::ppc_altivec_vsrw
6857 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6858 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6861 // vsplti + sra self.
6862 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6863 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6864 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6865 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6866 Intrinsic::ppc_altivec_vsraw
6868 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6869 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6872 // vsplti + rol self.
6873 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6874 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6875 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6876 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6877 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6878 Intrinsic::ppc_altivec_vrlw
6880 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6881 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6884 // t = vsplti c, result = vsldoi t, t, 1
6885 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6886 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6887 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6889 // t = vsplti c, result = vsldoi t, t, 2
6890 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6891 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6892 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6894 // t = vsplti c, result = vsldoi t, t, 3
6895 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6896 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6897 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6904 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6905 /// the specified operations to build the shuffle.
6906 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6907 SDValue RHS, SelectionDAG &DAG,
6909 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6910 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6911 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6914 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6926 if (OpNum == OP_COPY) {
6927 if (LHSID == (1*9+2)*9+3) return LHS;
6928 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6932 SDValue OpLHS, OpRHS;
6933 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6934 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6938 default: llvm_unreachable("Unknown i32 permute!");
6940 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6941 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6942 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6943 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6946 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6947 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6948 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6949 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6952 for (unsigned i = 0; i != 16; ++i)
6953 ShufIdxs[i] = (i&3)+0;
6956 for (unsigned i = 0; i != 16; ++i)
6957 ShufIdxs[i] = (i&3)+4;
6960 for (unsigned i = 0; i != 16; ++i)
6961 ShufIdxs[i] = (i&3)+8;
6964 for (unsigned i = 0; i != 16; ++i)
6965 ShufIdxs[i] = (i&3)+12;
6968 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6970 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6972 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6974 EVT VT = OpLHS.getValueType();
6975 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6976 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6977 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6978 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6981 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6982 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6983 /// return the code it can be lowered into. Worst case, it can always be
6984 /// lowered into a vperm.
6985 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6986 SelectionDAG &DAG) const {
6988 SDValue V1 = Op.getOperand(0);
6989 SDValue V2 = Op.getOperand(1);
6990 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6991 EVT VT = Op.getValueType();
6992 bool isLittleEndian = Subtarget.isLittleEndian();
6994 if (Subtarget.hasQPX()) {
6995 if (VT.getVectorNumElements() != 4)
6998 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7000 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7001 if (AlignIdx != -1) {
7002 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7003 DAG.getConstant(AlignIdx, dl, MVT::i32));
7004 } else if (SVOp->isSplat()) {
7005 int SplatIdx = SVOp->getSplatIndex();
7006 if (SplatIdx >= 4) {
7011 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7014 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7015 DAG.getConstant(SplatIdx, dl, MVT::i32));
7018 // Lower this into a qvgpci/qvfperm pair.
7020 // Compute the qvgpci literal
7022 for (unsigned i = 0; i < 4; ++i) {
7023 int m = SVOp->getMaskElt(i);
7024 unsigned mm = m >= 0 ? (unsigned) m : i;
7025 idx |= mm << (3-i)*3;
7028 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7029 DAG.getConstant(idx, dl, MVT::i32));
7030 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7033 // Cases that are handled by instructions that take permute immediates
7034 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7035 // selected by the instruction selector.
7036 if (V2.getOpcode() == ISD::UNDEF) {
7037 if (PPC::isSplatShuffleMask(SVOp, 1) ||
7038 PPC::isSplatShuffleMask(SVOp, 2) ||
7039 PPC::isSplatShuffleMask(SVOp, 4) ||
7040 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7041 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7042 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7043 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7044 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7045 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7046 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7047 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7048 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7049 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
7054 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7055 // and produce a fixed permutation. If any of these match, do not lower to
7057 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7058 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7059 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7060 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7061 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7062 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7063 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7064 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7065 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7066 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7067 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
7070 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7071 // perfect shuffle table to emit an optimal matching sequence.
7072 ArrayRef<int> PermMask = SVOp->getMask();
7074 unsigned PFIndexes[4];
7075 bool isFourElementShuffle = true;
7076 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7077 unsigned EltNo = 8; // Start out undef.
7078 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7079 if (PermMask[i*4+j] < 0)
7080 continue; // Undef, ignore it.
7082 unsigned ByteSource = PermMask[i*4+j];
7083 if ((ByteSource & 3) != j) {
7084 isFourElementShuffle = false;
7089 EltNo = ByteSource/4;
7090 } else if (EltNo != ByteSource/4) {
7091 isFourElementShuffle = false;
7095 PFIndexes[i] = EltNo;
7098 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7099 // perfect shuffle vector to determine if it is cost effective to do this as
7100 // discrete instructions, or whether we should use a vperm.
7101 // For now, we skip this for little endian until such time as we have a
7102 // little-endian perfect shuffle table.
7103 if (isFourElementShuffle && !isLittleEndian) {
7104 // Compute the index in the perfect shuffle table.
7105 unsigned PFTableIndex =
7106 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7108 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7109 unsigned Cost = (PFEntry >> 30);
7111 // Determining when to avoid vperm is tricky. Many things affect the cost
7112 // of vperm, particularly how many times the perm mask needs to be computed.
7113 // For example, if the perm mask can be hoisted out of a loop or is already
7114 // used (perhaps because there are multiple permutes with the same shuffle
7115 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7116 // the loop requires an extra register.
7118 // As a compromise, we only emit discrete instructions if the shuffle can be
7119 // generated in 3 or fewer operations. When we have loop information
7120 // available, if this block is within a loop, we should avoid using vperm
7121 // for 3-operation perms and use a constant pool load instead.
7123 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7126 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7127 // vector that will get spilled to the constant pool.
7128 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7130 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7131 // that it is in input element units, not in bytes. Convert now.
7133 // For little endian, the order of the input vectors is reversed, and
7134 // the permutation mask is complemented with respect to 31. This is
7135 // necessary to produce proper semantics with the big-endian-biased vperm
7137 EVT EltVT = V1.getValueType().getVectorElementType();
7138 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7140 SmallVector<SDValue, 16> ResultMask;
7141 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7142 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7144 for (unsigned j = 0; j != BytesPerElement; ++j)
7146 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7149 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7153 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7156 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7159 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7163 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7164 /// altivec comparison. If it is, return true and fill in Opc/isDot with
7165 /// information about the intrinsic.
7166 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7167 bool &isDot, const PPCSubtarget &Subtarget) {
7168 unsigned IntrinsicID =
7169 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7172 switch (IntrinsicID) {
7173 default: return false;
7174 // Comparison predicates.
7175 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7176 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7177 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7178 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7179 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7180 case Intrinsic::ppc_altivec_vcmpequd_p:
7181 if (Subtarget.hasP8Altivec()) {
7189 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7190 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7191 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7192 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7193 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7194 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7195 if (Subtarget.hasP8Altivec()) {
7203 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7204 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7205 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7206 case Intrinsic::ppc_altivec_vcmpgtud_p:
7207 if (Subtarget.hasP8Altivec()) {
7216 // Normal Comparisons.
7217 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7218 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7219 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7220 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7221 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7222 case Intrinsic::ppc_altivec_vcmpequd:
7223 if (Subtarget.hasP8Altivec()) {
7231 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7232 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7233 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7234 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7235 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7236 case Intrinsic::ppc_altivec_vcmpgtsd:
7237 if (Subtarget.hasP8Altivec()) {
7245 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7246 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7247 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7248 case Intrinsic::ppc_altivec_vcmpgtud:
7249 if (Subtarget.hasP8Altivec()) {
7261 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7262 /// lower, do it, otherwise return null.
7263 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7264 SelectionDAG &DAG) const {
7265 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7266 // opcode number of the comparison.
7270 if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7271 return SDValue(); // Don't custom lower most intrinsics.
7273 // If this is a non-dot comparison, make the VCMP node and we are done.
7275 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7276 Op.getOperand(1), Op.getOperand(2),
7277 DAG.getConstant(CompareOpc, dl, MVT::i32));
7278 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7281 // Create the PPCISD altivec 'dot' comparison node.
7283 Op.getOperand(2), // LHS
7284 Op.getOperand(3), // RHS
7285 DAG.getConstant(CompareOpc, dl, MVT::i32)
7287 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7288 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7290 // Now that we have the comparison, emit a copy from the CR to a GPR.
7291 // This is flagged to the above dot comparison.
7292 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7293 DAG.getRegister(PPC::CR6, MVT::i32),
7294 CompNode.getValue(1));
7296 // Unpack the result based on how the target uses it.
7297 unsigned BitNo; // Bit # of CR6.
7298 bool InvertBit; // Invert result?
7299 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7300 default: // Can't happen, don't crash on invalid number though.
7301 case 0: // Return the value of the EQ bit of CR6.
7302 BitNo = 0; InvertBit = false;
7304 case 1: // Return the inverted value of the EQ bit of CR6.
7305 BitNo = 0; InvertBit = true;
7307 case 2: // Return the value of the LT bit of CR6.
7308 BitNo = 2; InvertBit = false;
7310 case 3: // Return the inverted value of the LT bit of CR6.
7311 BitNo = 2; InvertBit = true;
7315 // Shift the bit into the low position.
7316 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7317 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7319 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7320 DAG.getConstant(1, dl, MVT::i32));
7322 // If we are supposed to, toggle the bit.
7324 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7325 DAG.getConstant(1, dl, MVT::i32));
7329 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7330 SelectionDAG &DAG) const {
7332 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7333 // instructions), but for smaller types, we need to first extend up to v2i32
7334 // before doing going farther.
7335 if (Op.getValueType() == MVT::v2i64) {
7336 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7337 if (ExtVT != MVT::v2i32) {
7338 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7339 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7340 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7341 ExtVT.getVectorElementType(), 4)));
7342 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7343 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7344 DAG.getValueType(MVT::v2i32));
7353 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7354 SelectionDAG &DAG) const {
7356 // Create a stack slot that is 16-byte aligned.
7357 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7358 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7359 EVT PtrVT = getPointerTy();
7360 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7362 // Store the input value into Value#0 of the stack slot.
7363 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7364 Op.getOperand(0), FIdx, MachinePointerInfo(),
7367 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7368 false, false, false, 0);
7371 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7372 SelectionDAG &DAG) const {
7374 SDNode *N = Op.getNode();
7376 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7377 "Unknown extract_vector_elt type");
7379 SDValue Value = N->getOperand(0);
7381 // The first part of this is like the store lowering except that we don't
7382 // need to track the chain.
7384 // The values are now known to be -1 (false) or 1 (true). To convert this
7385 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7386 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7387 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7389 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7390 // understand how to form the extending load.
7391 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7392 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7393 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7395 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7397 // Now convert to an integer and store.
7398 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7399 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7402 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7403 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7404 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7405 EVT PtrVT = getPointerTy();
7406 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7408 SDValue StoreChain = DAG.getEntryNode();
7409 SmallVector<SDValue, 2> Ops;
7410 Ops.push_back(StoreChain);
7411 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7412 Ops.push_back(Value);
7413 Ops.push_back(FIdx);
7415 SmallVector<EVT, 2> ValueVTs;
7416 ValueVTs.push_back(MVT::Other); // chain
7417 SDVTList VTs = DAG.getVTList(ValueVTs);
7419 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7420 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7422 // Extract the value requested.
7423 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7424 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7425 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7427 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7428 PtrInfo.getWithOffset(Offset),
7429 false, false, false, 0);
7431 if (!Subtarget.useCRBits())
7434 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7437 /// Lowering for QPX v4i1 loads
7438 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7439 SelectionDAG &DAG) const {
7441 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7442 SDValue LoadChain = LN->getChain();
7443 SDValue BasePtr = LN->getBasePtr();
7445 if (Op.getValueType() == MVT::v4f64 ||
7446 Op.getValueType() == MVT::v4f32) {
7447 EVT MemVT = LN->getMemoryVT();
7448 unsigned Alignment = LN->getAlignment();
7450 // If this load is properly aligned, then it is legal.
7451 if (Alignment >= MemVT.getStoreSize())
7454 EVT ScalarVT = Op.getValueType().getScalarType(),
7455 ScalarMemVT = MemVT.getScalarType();
7456 unsigned Stride = ScalarMemVT.getStoreSize();
7458 SmallVector<SDValue, 8> Vals, LoadChains;
7459 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7461 if (ScalarVT != ScalarMemVT)
7463 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7465 LN->getPointerInfo().getWithOffset(Idx*Stride),
7466 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7467 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7471 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7472 LN->getPointerInfo().getWithOffset(Idx*Stride),
7473 LN->isVolatile(), LN->isNonTemporal(),
7474 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7477 if (Idx == 0 && LN->isIndexed()) {
7478 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7479 "Unknown addressing mode on vector load");
7480 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7481 LN->getAddressingMode());
7484 Vals.push_back(Load);
7485 LoadChains.push_back(Load.getValue(1));
7487 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7488 DAG.getConstant(Stride, dl,
7489 BasePtr.getValueType()));
7492 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7493 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7494 Op.getValueType(), Vals);
7496 if (LN->isIndexed()) {
7497 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7498 return DAG.getMergeValues(RetOps, dl);
7501 SDValue RetOps[] = { Value, TF };
7502 return DAG.getMergeValues(RetOps, dl);
7505 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7506 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7508 // To lower v4i1 from a byte array, we load the byte elements of the
7509 // vector and then reuse the BUILD_VECTOR logic.
7511 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7512 for (unsigned i = 0; i < 4; ++i) {
7513 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7514 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7516 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7517 dl, MVT::i32, LoadChain, Idx,
7518 LN->getPointerInfo().getWithOffset(i),
7519 MVT::i8 /* memory type */,
7520 LN->isVolatile(), LN->isNonTemporal(),
7522 1 /* alignment */, LN->getAAInfo()));
7523 VectElmtChains.push_back(VectElmts[i].getValue(1));
7526 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7527 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7529 SDValue RVals[] = { Value, LoadChain };
7530 return DAG.getMergeValues(RVals, dl);
7533 /// Lowering for QPX v4i1 stores
7534 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7535 SelectionDAG &DAG) const {
7537 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7538 SDValue StoreChain = SN->getChain();
7539 SDValue BasePtr = SN->getBasePtr();
7540 SDValue Value = SN->getValue();
7542 if (Value.getValueType() == MVT::v4f64 ||
7543 Value.getValueType() == MVT::v4f32) {
7544 EVT MemVT = SN->getMemoryVT();
7545 unsigned Alignment = SN->getAlignment();
7547 // If this store is properly aligned, then it is legal.
7548 if (Alignment >= MemVT.getStoreSize())
7551 EVT ScalarVT = Value.getValueType().getScalarType(),
7552 ScalarMemVT = MemVT.getScalarType();
7553 unsigned Stride = ScalarMemVT.getStoreSize();
7555 SmallVector<SDValue, 8> Stores;
7556 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7558 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7559 DAG.getConstant(Idx, dl, getVectorIdxTy()));
7561 if (ScalarVT != ScalarMemVT)
7563 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7564 SN->getPointerInfo().getWithOffset(Idx*Stride),
7565 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7566 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7569 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7570 SN->getPointerInfo().getWithOffset(Idx*Stride),
7571 SN->isVolatile(), SN->isNonTemporal(),
7572 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7574 if (Idx == 0 && SN->isIndexed()) {
7575 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7576 "Unknown addressing mode on vector store");
7577 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7578 SN->getAddressingMode());
7581 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7582 DAG.getConstant(Stride, dl,
7583 BasePtr.getValueType()));
7584 Stores.push_back(Store);
7587 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7589 if (SN->isIndexed()) {
7590 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7591 return DAG.getMergeValues(RetOps, dl);
7597 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7598 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7600 // The values are now known to be -1 (false) or 1 (true). To convert this
7601 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7602 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7603 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7605 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7606 // understand how to form the extending load.
7607 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7608 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7609 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7611 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7613 // Now convert to an integer and store.
7614 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7615 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7618 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7619 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7620 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7621 EVT PtrVT = getPointerTy();
7622 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7624 SmallVector<SDValue, 2> Ops;
7625 Ops.push_back(StoreChain);
7626 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7627 Ops.push_back(Value);
7628 Ops.push_back(FIdx);
7630 SmallVector<EVT, 2> ValueVTs;
7631 ValueVTs.push_back(MVT::Other); // chain
7632 SDVTList VTs = DAG.getVTList(ValueVTs);
7634 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7635 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7637 // Move data into the byte array.
7638 SmallVector<SDValue, 4> Loads, LoadChains;
7639 for (unsigned i = 0; i < 4; ++i) {
7640 unsigned Offset = 4*i;
7641 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7642 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7644 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7645 PtrInfo.getWithOffset(Offset),
7646 false, false, false, 0));
7647 LoadChains.push_back(Loads[i].getValue(1));
7650 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7652 SmallVector<SDValue, 4> Stores;
7653 for (unsigned i = 0; i < 4; ++i) {
7654 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7655 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7657 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7658 SN->getPointerInfo().getWithOffset(i),
7659 MVT::i8 /* memory type */,
7660 SN->isNonTemporal(), SN->isVolatile(),
7661 1 /* alignment */, SN->getAAInfo()));
7664 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7669 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7671 if (Op.getValueType() == MVT::v4i32) {
7672 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7674 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7675 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7677 SDValue RHSSwap = // = vrlw RHS, 16
7678 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7680 // Shrinkify inputs to v8i16.
7681 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7682 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7683 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7685 // Low parts multiplied together, generating 32-bit results (we ignore the
7687 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7688 LHS, RHS, DAG, dl, MVT::v4i32);
7690 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7691 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7692 // Shift the high parts up 16 bits.
7693 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7695 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7696 } else if (Op.getValueType() == MVT::v8i16) {
7697 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7699 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7701 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7702 LHS, RHS, Zero, DAG, dl);
7703 } else if (Op.getValueType() == MVT::v16i8) {
7704 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7705 bool isLittleEndian = Subtarget.isLittleEndian();
7707 // Multiply the even 8-bit parts, producing 16-bit sums.
7708 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7709 LHS, RHS, DAG, dl, MVT::v8i16);
7710 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7712 // Multiply the odd 8-bit parts, producing 16-bit sums.
7713 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7714 LHS, RHS, DAG, dl, MVT::v8i16);
7715 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7717 // Merge the results together. Because vmuleub and vmuloub are
7718 // instructions with a big-endian bias, we must reverse the
7719 // element numbering and reverse the meaning of "odd" and "even"
7720 // when generating little endian code.
7722 for (unsigned i = 0; i != 8; ++i) {
7723 if (isLittleEndian) {
7725 Ops[i*2+1] = 2*i+16;
7728 Ops[i*2+1] = 2*i+1+16;
7732 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7734 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7736 llvm_unreachable("Unknown mul to lower!");
7740 /// LowerOperation - Provide custom lowering hooks for some operations.
7742 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7743 switch (Op.getOpcode()) {
7744 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7745 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7746 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7747 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7748 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7749 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7750 case ISD::SETCC: return LowerSETCC(Op, DAG);
7751 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7752 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7754 return LowerVASTART(Op, DAG, Subtarget);
7757 return LowerVAARG(Op, DAG, Subtarget);
7760 return LowerVACOPY(Op, DAG, Subtarget);
7762 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7763 case ISD::DYNAMIC_STACKALLOC:
7764 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7766 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7767 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7769 case ISD::LOAD: return LowerLOAD(Op, DAG);
7770 case ISD::STORE: return LowerSTORE(Op, DAG);
7771 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7772 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7773 case ISD::FP_TO_UINT:
7774 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7776 case ISD::UINT_TO_FP:
7777 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7778 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7780 // Lower 64-bit shifts.
7781 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7782 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7783 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7785 // Vector-related lowering.
7786 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7787 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7788 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7789 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7790 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7791 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7792 case ISD::MUL: return LowerMUL(Op, DAG);
7794 // For counter-based loop handling.
7795 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7797 // Frame & Return address.
7798 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7799 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7803 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7804 SmallVectorImpl<SDValue>&Results,
7805 SelectionDAG &DAG) const {
7807 switch (N->getOpcode()) {
7809 llvm_unreachable("Do not know how to custom type legalize this operation!");
7810 case ISD::READCYCLECOUNTER: {
7811 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7812 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7814 Results.push_back(RTB);
7815 Results.push_back(RTB.getValue(1));
7816 Results.push_back(RTB.getValue(2));
7819 case ISD::INTRINSIC_W_CHAIN: {
7820 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7821 Intrinsic::ppc_is_decremented_ctr_nonzero)
7824 assert(N->getValueType(0) == MVT::i1 &&
7825 "Unexpected result type for CTR decrement intrinsic");
7826 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7827 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7828 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7831 Results.push_back(NewInt);
7832 Results.push_back(NewInt.getValue(1));
7836 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7839 EVT VT = N->getValueType(0);
7841 if (VT == MVT::i64) {
7842 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7844 Results.push_back(NewNode);
7845 Results.push_back(NewNode.getValue(1));
7849 case ISD::FP_ROUND_INREG: {
7850 assert(N->getValueType(0) == MVT::ppcf128);
7851 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7852 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7853 MVT::f64, N->getOperand(0),
7854 DAG.getIntPtrConstant(0, dl));
7855 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7856 MVT::f64, N->getOperand(0),
7857 DAG.getIntPtrConstant(1, dl));
7859 // Add the two halves of the long double in round-to-zero mode.
7860 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7862 // We know the low half is about to be thrown away, so just use something
7864 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7868 case ISD::FP_TO_SINT:
7869 case ISD::FP_TO_UINT:
7870 // LowerFP_TO_INT() can only handle f32 and f64.
7871 if (N->getOperand(0).getValueType() == MVT::ppcf128)
7873 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7879 //===----------------------------------------------------------------------===//
7880 // Other Lowering Code
7881 //===----------------------------------------------------------------------===//
7883 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7884 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7885 Function *Func = Intrinsic::getDeclaration(M, Id);
7886 return Builder.CreateCall(Func, {});
7889 // The mappings for emitLeading/TrailingFence is taken from
7890 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7891 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7892 AtomicOrdering Ord, bool IsStore,
7893 bool IsLoad) const {
7894 if (Ord == SequentiallyConsistent)
7895 return callIntrinsic(Builder, Intrinsic::ppc_sync);
7896 if (isAtLeastRelease(Ord))
7897 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7901 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7902 AtomicOrdering Ord, bool IsStore,
7903 bool IsLoad) const {
7904 if (IsLoad && isAtLeastAcquire(Ord))
7905 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7906 // FIXME: this is too conservative, a dependent branch + isync is enough.
7907 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7908 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7909 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7914 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7915 unsigned AtomicSize,
7916 unsigned BinOpcode) const {
7917 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7918 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7920 auto LoadMnemonic = PPC::LDARX;
7921 auto StoreMnemonic = PPC::STDCX;
7922 switch (AtomicSize) {
7924 llvm_unreachable("Unexpected size of atomic entity");
7926 LoadMnemonic = PPC::LBARX;
7927 StoreMnemonic = PPC::STBCX;
7928 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7931 LoadMnemonic = PPC::LHARX;
7932 StoreMnemonic = PPC::STHCX;
7933 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7936 LoadMnemonic = PPC::LWARX;
7937 StoreMnemonic = PPC::STWCX;
7940 LoadMnemonic = PPC::LDARX;
7941 StoreMnemonic = PPC::STDCX;
7945 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7946 MachineFunction *F = BB->getParent();
7947 MachineFunction::iterator It = BB;
7950 unsigned dest = MI->getOperand(0).getReg();
7951 unsigned ptrA = MI->getOperand(1).getReg();
7952 unsigned ptrB = MI->getOperand(2).getReg();
7953 unsigned incr = MI->getOperand(3).getReg();
7954 DebugLoc dl = MI->getDebugLoc();
7956 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7957 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7958 F->insert(It, loopMBB);
7959 F->insert(It, exitMBB);
7960 exitMBB->splice(exitMBB->begin(), BB,
7961 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7962 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7964 MachineRegisterInfo &RegInfo = F->getRegInfo();
7965 unsigned TmpReg = (!BinOpcode) ? incr :
7966 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7967 : &PPC::GPRCRegClass);
7971 // fallthrough --> loopMBB
7972 BB->addSuccessor(loopMBB);
7975 // l[wd]arx dest, ptr
7976 // add r0, dest, incr
7977 // st[wd]cx. r0, ptr
7979 // fallthrough --> exitMBB
7981 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7982 .addReg(ptrA).addReg(ptrB);
7984 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7985 BuildMI(BB, dl, TII->get(StoreMnemonic))
7986 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7987 BuildMI(BB, dl, TII->get(PPC::BCC))
7988 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7989 BB->addSuccessor(loopMBB);
7990 BB->addSuccessor(exitMBB);
7999 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8000 MachineBasicBlock *BB,
8001 bool is8bit, // operation
8002 unsigned BinOpcode) const {
8003 // If we support part-word atomic mnemonics, just use them
8004 if (Subtarget.hasPartwordAtomics())
8005 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8007 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8008 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8009 // In 64 bit mode we have to use 64 bits for addresses, even though the
8010 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
8011 // registers without caring whether they're 32 or 64, but here we're
8012 // doing actual arithmetic on the addresses.
8013 bool is64bit = Subtarget.isPPC64();
8014 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8016 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8017 MachineFunction *F = BB->getParent();
8018 MachineFunction::iterator It = BB;
8021 unsigned dest = MI->getOperand(0).getReg();
8022 unsigned ptrA = MI->getOperand(1).getReg();
8023 unsigned ptrB = MI->getOperand(2).getReg();
8024 unsigned incr = MI->getOperand(3).getReg();
8025 DebugLoc dl = MI->getDebugLoc();
8027 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8028 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8029 F->insert(It, loopMBB);
8030 F->insert(It, exitMBB);
8031 exitMBB->splice(exitMBB->begin(), BB,
8032 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8033 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8035 MachineRegisterInfo &RegInfo = F->getRegInfo();
8036 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8037 : &PPC::GPRCRegClass;
8038 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8039 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8040 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8041 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8042 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8043 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8044 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8045 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8046 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8047 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8048 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8050 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8054 // fallthrough --> loopMBB
8055 BB->addSuccessor(loopMBB);
8057 // The 4-byte load must be aligned, while a char or short may be
8058 // anywhere in the word. Hence all this nasty bookkeeping code.
8059 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8060 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8061 // xori shift, shift1, 24 [16]
8062 // rlwinm ptr, ptr1, 0, 0, 29
8063 // slw incr2, incr, shift
8064 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8065 // slw mask, mask2, shift
8067 // lwarx tmpDest, ptr
8068 // add tmp, tmpDest, incr2
8069 // andc tmp2, tmpDest, mask
8070 // and tmp3, tmp, mask
8071 // or tmp4, tmp3, tmp2
8074 // fallthrough --> exitMBB
8075 // srw dest, tmpDest, shift
8076 if (ptrA != ZeroReg) {
8077 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8078 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8079 .addReg(ptrA).addReg(ptrB);
8083 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8084 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8085 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8086 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8088 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8089 .addReg(Ptr1Reg).addImm(0).addImm(61);
8091 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8092 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8093 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8094 .addReg(incr).addReg(ShiftReg);
8096 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8098 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8099 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8101 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8102 .addReg(Mask2Reg).addReg(ShiftReg);
8105 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8106 .addReg(ZeroReg).addReg(PtrReg);
8108 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8109 .addReg(Incr2Reg).addReg(TmpDestReg);
8110 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8111 .addReg(TmpDestReg).addReg(MaskReg);
8112 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8113 .addReg(TmpReg).addReg(MaskReg);
8114 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8115 .addReg(Tmp3Reg).addReg(Tmp2Reg);
8116 BuildMI(BB, dl, TII->get(PPC::STWCX))
8117 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8118 BuildMI(BB, dl, TII->get(PPC::BCC))
8119 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8120 BB->addSuccessor(loopMBB);
8121 BB->addSuccessor(exitMBB);
8126 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8131 llvm::MachineBasicBlock*
8132 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8133 MachineBasicBlock *MBB) const {
8134 DebugLoc DL = MI->getDebugLoc();
8135 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8137 MachineFunction *MF = MBB->getParent();
8138 MachineRegisterInfo &MRI = MF->getRegInfo();
8140 const BasicBlock *BB = MBB->getBasicBlock();
8141 MachineFunction::iterator I = MBB;
8145 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8146 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8148 unsigned DstReg = MI->getOperand(0).getReg();
8149 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8150 assert(RC->hasType(MVT::i32) && "Invalid destination!");
8151 unsigned mainDstReg = MRI.createVirtualRegister(RC);
8152 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8154 MVT PVT = getPointerTy();
8155 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8156 "Invalid Pointer Size!");
8157 // For v = setjmp(buf), we generate
8160 // SjLjSetup mainMBB
8166 // buf[LabelOffset] = LR
8170 // v = phi(main, restore)
8173 MachineBasicBlock *thisMBB = MBB;
8174 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8175 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8176 MF->insert(I, mainMBB);
8177 MF->insert(I, sinkMBB);
8179 MachineInstrBuilder MIB;
8181 // Transfer the remainder of BB and its successor edges to sinkMBB.
8182 sinkMBB->splice(sinkMBB->begin(), MBB,
8183 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8184 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8186 // Note that the structure of the jmp_buf used here is not compatible
8187 // with that used by libc, and is not designed to be. Specifically, it
8188 // stores only those 'reserved' registers that LLVM does not otherwise
8189 // understand how to spill. Also, by convention, by the time this
8190 // intrinsic is called, Clang has already stored the frame address in the
8191 // first slot of the buffer and stack address in the third. Following the
8192 // X86 target code, we'll store the jump address in the second slot. We also
8193 // need to save the TOC pointer (R2) to handle jumps between shared
8194 // libraries, and that will be stored in the fourth slot. The thread
8195 // identifier (R13) is not affected.
8198 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8199 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8200 const int64_t BPOffset = 4 * PVT.getStoreSize();
8202 // Prepare IP either in reg.
8203 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8204 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8205 unsigned BufReg = MI->getOperand(1).getReg();
8207 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8208 setUsesTOCBasePtr(*MBB->getParent());
8209 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8213 MIB.setMemRefs(MMOBegin, MMOEnd);
8216 // Naked functions never have a base pointer, and so we use r1. For all
8217 // other functions, this decision must be delayed until during PEI.
8219 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8220 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8222 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8224 MIB = BuildMI(*thisMBB, MI, DL,
8225 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8229 MIB.setMemRefs(MMOBegin, MMOEnd);
8232 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8233 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8234 MIB.addRegMask(TRI->getNoPreservedMask());
8236 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8238 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8240 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8242 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8243 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8248 BuildMI(mainMBB, DL,
8249 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8252 if (Subtarget.isPPC64()) {
8253 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8255 .addImm(LabelOffset)
8258 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8260 .addImm(LabelOffset)
8264 MIB.setMemRefs(MMOBegin, MMOEnd);
8266 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8267 mainMBB->addSuccessor(sinkMBB);
8270 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8271 TII->get(PPC::PHI), DstReg)
8272 .addReg(mainDstReg).addMBB(mainMBB)
8273 .addReg(restoreDstReg).addMBB(thisMBB);
8275 MI->eraseFromParent();
8280 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8281 MachineBasicBlock *MBB) const {
8282 DebugLoc DL = MI->getDebugLoc();
8283 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8285 MachineFunction *MF = MBB->getParent();
8286 MachineRegisterInfo &MRI = MF->getRegInfo();
8289 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8290 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8292 MVT PVT = getPointerTy();
8293 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8294 "Invalid Pointer Size!");
8296 const TargetRegisterClass *RC =
8297 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8298 unsigned Tmp = MRI.createVirtualRegister(RC);
8299 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8300 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8301 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8305 : (Subtarget.isSVR4ABI() &&
8306 MF->getTarget().getRelocationModel() == Reloc::PIC_
8310 MachineInstrBuilder MIB;
8312 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8313 const int64_t SPOffset = 2 * PVT.getStoreSize();
8314 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8315 const int64_t BPOffset = 4 * PVT.getStoreSize();
8317 unsigned BufReg = MI->getOperand(0).getReg();
8319 // Reload FP (the jumped-to function may not have had a
8320 // frame pointer, and if so, then its r31 will be restored
8322 if (PVT == MVT::i64) {
8323 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8327 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8331 MIB.setMemRefs(MMOBegin, MMOEnd);
8334 if (PVT == MVT::i64) {
8335 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8336 .addImm(LabelOffset)
8339 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8340 .addImm(LabelOffset)
8343 MIB.setMemRefs(MMOBegin, MMOEnd);
8346 if (PVT == MVT::i64) {
8347 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8351 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8355 MIB.setMemRefs(MMOBegin, MMOEnd);
8358 if (PVT == MVT::i64) {
8359 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8363 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8367 MIB.setMemRefs(MMOBegin, MMOEnd);
8370 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8371 setUsesTOCBasePtr(*MBB->getParent());
8372 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8376 MIB.setMemRefs(MMOBegin, MMOEnd);
8380 BuildMI(*MBB, MI, DL,
8381 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8382 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8384 MI->eraseFromParent();
8389 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8390 MachineBasicBlock *BB) const {
8391 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8392 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8393 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8394 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8395 // Call lowering should have added an r2 operand to indicate a dependence
8396 // on the TOC base pointer value. It can't however, because there is no
8397 // way to mark the dependence as implicit there, and so the stackmap code
8398 // will confuse it with a regular operand. Instead, add the dependence
8400 setUsesTOCBasePtr(*BB->getParent());
8401 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8404 return emitPatchPoint(MI, BB);
8407 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8408 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8409 return emitEHSjLjSetJmp(MI, BB);
8410 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8411 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8412 return emitEHSjLjLongJmp(MI, BB);
8415 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8417 // To "insert" these instructions we actually have to insert their
8418 // control-flow patterns.
8419 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8420 MachineFunction::iterator It = BB;
8423 MachineFunction *F = BB->getParent();
8425 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8426 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8427 MI->getOpcode() == PPC::SELECT_I4 ||
8428 MI->getOpcode() == PPC::SELECT_I8)) {
8429 SmallVector<MachineOperand, 2> Cond;
8430 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8431 MI->getOpcode() == PPC::SELECT_CC_I8)
8432 Cond.push_back(MI->getOperand(4));
8434 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8435 Cond.push_back(MI->getOperand(1));
8437 DebugLoc dl = MI->getDebugLoc();
8438 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8439 Cond, MI->getOperand(2).getReg(),
8440 MI->getOperand(3).getReg());
8441 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8442 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8443 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8444 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8445 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8446 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8447 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8448 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8449 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8450 MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8451 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8452 MI->getOpcode() == PPC::SELECT_I4 ||
8453 MI->getOpcode() == PPC::SELECT_I8 ||
8454 MI->getOpcode() == PPC::SELECT_F4 ||
8455 MI->getOpcode() == PPC::SELECT_F8 ||
8456 MI->getOpcode() == PPC::SELECT_QFRC ||
8457 MI->getOpcode() == PPC::SELECT_QSRC ||
8458 MI->getOpcode() == PPC::SELECT_QBRC ||
8459 MI->getOpcode() == PPC::SELECT_VRRC ||
8460 MI->getOpcode() == PPC::SELECT_VSFRC ||
8461 MI->getOpcode() == PPC::SELECT_VSSRC ||
8462 MI->getOpcode() == PPC::SELECT_VSRC) {
8463 // The incoming instruction knows the destination vreg to set, the
8464 // condition code register to branch on, the true/false values to
8465 // select between, and a branch opcode to use.
8470 // cmpTY ccX, r1, r2
8472 // fallthrough --> copy0MBB
8473 MachineBasicBlock *thisMBB = BB;
8474 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8475 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8476 DebugLoc dl = MI->getDebugLoc();
8477 F->insert(It, copy0MBB);
8478 F->insert(It, sinkMBB);
8480 // Transfer the remainder of BB and its successor edges to sinkMBB.
8481 sinkMBB->splice(sinkMBB->begin(), BB,
8482 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8483 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8485 // Next, add the true and fallthrough blocks as its successors.
8486 BB->addSuccessor(copy0MBB);
8487 BB->addSuccessor(sinkMBB);
8489 if (MI->getOpcode() == PPC::SELECT_I4 ||
8490 MI->getOpcode() == PPC::SELECT_I8 ||
8491 MI->getOpcode() == PPC::SELECT_F4 ||
8492 MI->getOpcode() == PPC::SELECT_F8 ||
8493 MI->getOpcode() == PPC::SELECT_QFRC ||
8494 MI->getOpcode() == PPC::SELECT_QSRC ||
8495 MI->getOpcode() == PPC::SELECT_QBRC ||
8496 MI->getOpcode() == PPC::SELECT_VRRC ||
8497 MI->getOpcode() == PPC::SELECT_VSFRC ||
8498 MI->getOpcode() == PPC::SELECT_VSSRC ||
8499 MI->getOpcode() == PPC::SELECT_VSRC) {
8500 BuildMI(BB, dl, TII->get(PPC::BC))
8501 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8503 unsigned SelectPred = MI->getOperand(4).getImm();
8504 BuildMI(BB, dl, TII->get(PPC::BCC))
8505 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8509 // %FalseValue = ...
8510 // # fallthrough to sinkMBB
8513 // Update machine-CFG edges
8514 BB->addSuccessor(sinkMBB);
8517 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8520 BuildMI(*BB, BB->begin(), dl,
8521 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8522 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8523 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8524 } else if (MI->getOpcode() == PPC::ReadTB) {
8525 // To read the 64-bit time-base register on a 32-bit target, we read the
8526 // two halves. Should the counter have wrapped while it was being read, we
8527 // need to try again.
8530 // mfspr Rx,TBU # load from TBU
8531 // mfspr Ry,TB # load from TB
8532 // mfspr Rz,TBU # load from TBU
8533 // cmpw crX,Rx,Rz # check if ‘old’=’new’
8534 // bne readLoop # branch if they're not equal
8537 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8538 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8539 DebugLoc dl = MI->getDebugLoc();
8540 F->insert(It, readMBB);
8541 F->insert(It, sinkMBB);
8543 // Transfer the remainder of BB and its successor edges to sinkMBB.
8544 sinkMBB->splice(sinkMBB->begin(), BB,
8545 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8546 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8548 BB->addSuccessor(readMBB);
8551 MachineRegisterInfo &RegInfo = F->getRegInfo();
8552 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8553 unsigned LoReg = MI->getOperand(0).getReg();
8554 unsigned HiReg = MI->getOperand(1).getReg();
8556 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8557 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8558 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8560 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8562 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8563 .addReg(HiReg).addReg(ReadAgainReg);
8564 BuildMI(BB, dl, TII->get(PPC::BCC))
8565 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8567 BB->addSuccessor(readMBB);
8568 BB->addSuccessor(sinkMBB);
8570 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8571 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8572 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8573 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8574 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8575 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8576 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8577 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8579 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8580 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8581 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8582 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8583 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8584 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8585 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8586 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8588 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8589 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8590 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8591 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8592 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8593 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8594 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8595 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8597 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8598 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8599 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8600 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8601 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8602 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8603 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8604 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8606 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8607 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8608 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8609 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8610 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8611 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8612 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8613 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8615 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8616 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8617 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8618 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8619 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8620 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8621 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8622 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8624 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8625 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8626 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8627 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8628 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8629 BB = EmitAtomicBinary(MI, BB, 4, 0);
8630 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8631 BB = EmitAtomicBinary(MI, BB, 8, 0);
8633 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8634 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8635 (Subtarget.hasPartwordAtomics() &&
8636 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8637 (Subtarget.hasPartwordAtomics() &&
8638 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8639 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8641 auto LoadMnemonic = PPC::LDARX;
8642 auto StoreMnemonic = PPC::STDCX;
8643 switch(MI->getOpcode()) {
8645 llvm_unreachable("Compare and swap of unknown size");
8646 case PPC::ATOMIC_CMP_SWAP_I8:
8647 LoadMnemonic = PPC::LBARX;
8648 StoreMnemonic = PPC::STBCX;
8649 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8651 case PPC::ATOMIC_CMP_SWAP_I16:
8652 LoadMnemonic = PPC::LHARX;
8653 StoreMnemonic = PPC::STHCX;
8654 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8656 case PPC::ATOMIC_CMP_SWAP_I32:
8657 LoadMnemonic = PPC::LWARX;
8658 StoreMnemonic = PPC::STWCX;
8660 case PPC::ATOMIC_CMP_SWAP_I64:
8661 LoadMnemonic = PPC::LDARX;
8662 StoreMnemonic = PPC::STDCX;
8665 unsigned dest = MI->getOperand(0).getReg();
8666 unsigned ptrA = MI->getOperand(1).getReg();
8667 unsigned ptrB = MI->getOperand(2).getReg();
8668 unsigned oldval = MI->getOperand(3).getReg();
8669 unsigned newval = MI->getOperand(4).getReg();
8670 DebugLoc dl = MI->getDebugLoc();
8672 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8673 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8674 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8675 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8676 F->insert(It, loop1MBB);
8677 F->insert(It, loop2MBB);
8678 F->insert(It, midMBB);
8679 F->insert(It, exitMBB);
8680 exitMBB->splice(exitMBB->begin(), BB,
8681 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8682 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8686 // fallthrough --> loopMBB
8687 BB->addSuccessor(loop1MBB);
8690 // l[bhwd]arx dest, ptr
8691 // cmp[wd] dest, oldval
8694 // st[bhwd]cx. newval, ptr
8698 // st[bhwd]cx. dest, ptr
8701 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8702 .addReg(ptrA).addReg(ptrB);
8703 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8704 .addReg(oldval).addReg(dest);
8705 BuildMI(BB, dl, TII->get(PPC::BCC))
8706 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8707 BB->addSuccessor(loop2MBB);
8708 BB->addSuccessor(midMBB);
8711 BuildMI(BB, dl, TII->get(StoreMnemonic))
8712 .addReg(newval).addReg(ptrA).addReg(ptrB);
8713 BuildMI(BB, dl, TII->get(PPC::BCC))
8714 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8715 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8716 BB->addSuccessor(loop1MBB);
8717 BB->addSuccessor(exitMBB);
8720 BuildMI(BB, dl, TII->get(StoreMnemonic))
8721 .addReg(dest).addReg(ptrA).addReg(ptrB);
8722 BB->addSuccessor(exitMBB);
8727 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8728 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8729 // We must use 64-bit registers for addresses when targeting 64-bit,
8730 // since we're actually doing arithmetic on them. Other registers
8732 bool is64bit = Subtarget.isPPC64();
8733 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8735 unsigned dest = MI->getOperand(0).getReg();
8736 unsigned ptrA = MI->getOperand(1).getReg();
8737 unsigned ptrB = MI->getOperand(2).getReg();
8738 unsigned oldval = MI->getOperand(3).getReg();
8739 unsigned newval = MI->getOperand(4).getReg();
8740 DebugLoc dl = MI->getDebugLoc();
8742 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8743 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8744 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8745 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8746 F->insert(It, loop1MBB);
8747 F->insert(It, loop2MBB);
8748 F->insert(It, midMBB);
8749 F->insert(It, exitMBB);
8750 exitMBB->splice(exitMBB->begin(), BB,
8751 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8752 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8754 MachineRegisterInfo &RegInfo = F->getRegInfo();
8755 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8756 : &PPC::GPRCRegClass;
8757 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8758 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8759 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8760 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8761 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8762 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8763 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8764 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8765 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8766 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8767 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8768 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8769 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8771 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8772 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8775 // fallthrough --> loopMBB
8776 BB->addSuccessor(loop1MBB);
8778 // The 4-byte load must be aligned, while a char or short may be
8779 // anywhere in the word. Hence all this nasty bookkeeping code.
8780 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8781 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8782 // xori shift, shift1, 24 [16]
8783 // rlwinm ptr, ptr1, 0, 0, 29
8784 // slw newval2, newval, shift
8785 // slw oldval2, oldval,shift
8786 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8787 // slw mask, mask2, shift
8788 // and newval3, newval2, mask
8789 // and oldval3, oldval2, mask
8791 // lwarx tmpDest, ptr
8792 // and tmp, tmpDest, mask
8793 // cmpw tmp, oldval3
8796 // andc tmp2, tmpDest, mask
8797 // or tmp4, tmp2, newval3
8802 // stwcx. tmpDest, ptr
8804 // srw dest, tmpDest, shift
8805 if (ptrA != ZeroReg) {
8806 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8807 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8808 .addReg(ptrA).addReg(ptrB);
8812 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8813 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8814 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8815 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8817 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8818 .addReg(Ptr1Reg).addImm(0).addImm(61);
8820 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8821 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8822 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8823 .addReg(newval).addReg(ShiftReg);
8824 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8825 .addReg(oldval).addReg(ShiftReg);
8827 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8829 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8830 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8831 .addReg(Mask3Reg).addImm(65535);
8833 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8834 .addReg(Mask2Reg).addReg(ShiftReg);
8835 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8836 .addReg(NewVal2Reg).addReg(MaskReg);
8837 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8838 .addReg(OldVal2Reg).addReg(MaskReg);
8841 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8842 .addReg(ZeroReg).addReg(PtrReg);
8843 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8844 .addReg(TmpDestReg).addReg(MaskReg);
8845 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8846 .addReg(TmpReg).addReg(OldVal3Reg);
8847 BuildMI(BB, dl, TII->get(PPC::BCC))
8848 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8849 BB->addSuccessor(loop2MBB);
8850 BB->addSuccessor(midMBB);
8853 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8854 .addReg(TmpDestReg).addReg(MaskReg);
8855 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8856 .addReg(Tmp2Reg).addReg(NewVal3Reg);
8857 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8858 .addReg(ZeroReg).addReg(PtrReg);
8859 BuildMI(BB, dl, TII->get(PPC::BCC))
8860 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8861 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8862 BB->addSuccessor(loop1MBB);
8863 BB->addSuccessor(exitMBB);
8866 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8867 .addReg(ZeroReg).addReg(PtrReg);
8868 BB->addSuccessor(exitMBB);
8873 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8875 } else if (MI->getOpcode() == PPC::FADDrtz) {
8876 // This pseudo performs an FADD with rounding mode temporarily forced
8877 // to round-to-zero. We emit this via custom inserter since the FPSCR
8878 // is not modeled at the SelectionDAG level.
8879 unsigned Dest = MI->getOperand(0).getReg();
8880 unsigned Src1 = MI->getOperand(1).getReg();
8881 unsigned Src2 = MI->getOperand(2).getReg();
8882 DebugLoc dl = MI->getDebugLoc();
8884 MachineRegisterInfo &RegInfo = F->getRegInfo();
8885 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8887 // Save FPSCR value.
8888 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8890 // Set rounding mode to round-to-zero.
8891 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8892 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8894 // Perform addition.
8895 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8897 // Restore FPSCR value.
8898 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8899 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8900 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8901 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8902 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8903 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8904 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8905 PPC::ANDIo8 : PPC::ANDIo;
8906 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8907 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8909 MachineRegisterInfo &RegInfo = F->getRegInfo();
8910 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8911 &PPC::GPRCRegClass :
8912 &PPC::G8RCRegClass);
8914 DebugLoc dl = MI->getDebugLoc();
8915 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8916 .addReg(MI->getOperand(1).getReg()).addImm(1);
8917 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8918 MI->getOperand(0).getReg())
8919 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8920 } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8921 DebugLoc Dl = MI->getDebugLoc();
8922 MachineRegisterInfo &RegInfo = F->getRegInfo();
8923 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8924 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8927 llvm_unreachable("Unexpected instr type to insert");
8930 MI->eraseFromParent(); // The pseudo instruction is gone now.
8934 //===----------------------------------------------------------------------===//
8935 // Target Optimization Hooks
8936 //===----------------------------------------------------------------------===//
8938 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8939 DAGCombinerInfo &DCI,
8940 unsigned &RefinementSteps,
8941 bool &UseOneConstNR) const {
8942 EVT VT = Operand.getValueType();
8943 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8944 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8945 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8946 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8947 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8948 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8949 // Convergence is quadratic, so we essentially double the number of digits
8950 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8951 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8952 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8953 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8954 if (VT.getScalarType() == MVT::f64)
8956 UseOneConstNR = true;
8957 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8962 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8963 DAGCombinerInfo &DCI,
8964 unsigned &RefinementSteps) const {
8965 EVT VT = Operand.getValueType();
8966 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8967 (VT == MVT::f64 && Subtarget.hasFRE()) ||
8968 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8969 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8970 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8971 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8972 // Convergence is quadratic, so we essentially double the number of digits
8973 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8974 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8975 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8976 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8977 if (VT.getScalarType() == MVT::f64)
8979 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8984 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8985 // Note: This functionality is used only when unsafe-fp-math is enabled, and
8986 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8987 // enabled for division), this functionality is redundant with the default
8988 // combiner logic (once the division -> reciprocal/multiply transformation
8989 // has taken place). As a result, this matters more for older cores than for
8992 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8993 // reciprocal if there are two or more FDIVs (for embedded cores with only
8994 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8995 switch (Subtarget.getDarwinDirective()) {
8997 return NumUsers > 2;
9000 case PPC::DIR_E500mc:
9001 case PPC::DIR_E5500:
9002 return NumUsers > 1;
9006 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9007 unsigned Bytes, int Dist,
9008 SelectionDAG &DAG) {
9009 if (VT.getSizeInBits() / 8 != Bytes)
9012 SDValue BaseLoc = Base->getBasePtr();
9013 if (Loc.getOpcode() == ISD::FrameIndex) {
9014 if (BaseLoc.getOpcode() != ISD::FrameIndex)
9016 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9017 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
9018 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9019 int FS = MFI->getObjectSize(FI);
9020 int BFS = MFI->getObjectSize(BFI);
9021 if (FS != BFS || FS != (int)Bytes) return false;
9022 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9026 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
9027 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
9030 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9031 const GlobalValue *GV1 = nullptr;
9032 const GlobalValue *GV2 = nullptr;
9033 int64_t Offset1 = 0;
9034 int64_t Offset2 = 0;
9035 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9036 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9037 if (isGA1 && isGA2 && GV1 == GV2)
9038 return Offset1 == (Offset2 + Dist*Bytes);
9042 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9043 // not enforce equality of the chain operands.
9044 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9045 unsigned Bytes, int Dist,
9046 SelectionDAG &DAG) {
9047 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9048 EVT VT = LS->getMemoryVT();
9049 SDValue Loc = LS->getBasePtr();
9050 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9053 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9055 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9056 default: return false;
9057 case Intrinsic::ppc_qpx_qvlfd:
9058 case Intrinsic::ppc_qpx_qvlfda:
9061 case Intrinsic::ppc_qpx_qvlfs:
9062 case Intrinsic::ppc_qpx_qvlfsa:
9065 case Intrinsic::ppc_qpx_qvlfcd:
9066 case Intrinsic::ppc_qpx_qvlfcda:
9069 case Intrinsic::ppc_qpx_qvlfcs:
9070 case Intrinsic::ppc_qpx_qvlfcsa:
9073 case Intrinsic::ppc_qpx_qvlfiwa:
9074 case Intrinsic::ppc_qpx_qvlfiwz:
9075 case Intrinsic::ppc_altivec_lvx:
9076 case Intrinsic::ppc_altivec_lvxl:
9077 case Intrinsic::ppc_vsx_lxvw4x:
9080 case Intrinsic::ppc_vsx_lxvd2x:
9083 case Intrinsic::ppc_altivec_lvebx:
9086 case Intrinsic::ppc_altivec_lvehx:
9089 case Intrinsic::ppc_altivec_lvewx:
9094 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9097 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9099 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9100 default: return false;
9101 case Intrinsic::ppc_qpx_qvstfd:
9102 case Intrinsic::ppc_qpx_qvstfda:
9105 case Intrinsic::ppc_qpx_qvstfs:
9106 case Intrinsic::ppc_qpx_qvstfsa:
9109 case Intrinsic::ppc_qpx_qvstfcd:
9110 case Intrinsic::ppc_qpx_qvstfcda:
9113 case Intrinsic::ppc_qpx_qvstfcs:
9114 case Intrinsic::ppc_qpx_qvstfcsa:
9117 case Intrinsic::ppc_qpx_qvstfiw:
9118 case Intrinsic::ppc_qpx_qvstfiwa:
9119 case Intrinsic::ppc_altivec_stvx:
9120 case Intrinsic::ppc_altivec_stvxl:
9121 case Intrinsic::ppc_vsx_stxvw4x:
9124 case Intrinsic::ppc_vsx_stxvd2x:
9127 case Intrinsic::ppc_altivec_stvebx:
9130 case Intrinsic::ppc_altivec_stvehx:
9133 case Intrinsic::ppc_altivec_stvewx:
9138 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9144 // Return true is there is a nearyby consecutive load to the one provided
9145 // (regardless of alignment). We search up and down the chain, looking though
9146 // token factors and other loads (but nothing else). As a result, a true result
9147 // indicates that it is safe to create a new consecutive load adjacent to the
9149 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9150 SDValue Chain = LD->getChain();
9151 EVT VT = LD->getMemoryVT();
9153 SmallSet<SDNode *, 16> LoadRoots;
9154 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9155 SmallSet<SDNode *, 16> Visited;
9157 // First, search up the chain, branching to follow all token-factor operands.
9158 // If we find a consecutive load, then we're done, otherwise, record all
9159 // nodes just above the top-level loads and token factors.
9160 while (!Queue.empty()) {
9161 SDNode *ChainNext = Queue.pop_back_val();
9162 if (!Visited.insert(ChainNext).second)
9165 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9166 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9169 if (!Visited.count(ChainLD->getChain().getNode()))
9170 Queue.push_back(ChainLD->getChain().getNode());
9171 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9172 for (const SDUse &O : ChainNext->ops())
9173 if (!Visited.count(O.getNode()))
9174 Queue.push_back(O.getNode());
9176 LoadRoots.insert(ChainNext);
9179 // Second, search down the chain, starting from the top-level nodes recorded
9180 // in the first phase. These top-level nodes are the nodes just above all
9181 // loads and token factors. Starting with their uses, recursively look though
9182 // all loads (just the chain uses) and token factors to find a consecutive
9187 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9188 IE = LoadRoots.end(); I != IE; ++I) {
9189 Queue.push_back(*I);
9191 while (!Queue.empty()) {
9192 SDNode *LoadRoot = Queue.pop_back_val();
9193 if (!Visited.insert(LoadRoot).second)
9196 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9197 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9200 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9201 UE = LoadRoot->use_end(); UI != UE; ++UI)
9202 if (((isa<MemSDNode>(*UI) &&
9203 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9204 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9205 Queue.push_back(*UI);
9212 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9213 DAGCombinerInfo &DCI) const {
9214 SelectionDAG &DAG = DCI.DAG;
9217 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9218 // If we're tracking CR bits, we need to be careful that we don't have:
9219 // trunc(binary-ops(zext(x), zext(y)))
9221 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9222 // such that we're unnecessarily moving things into GPRs when it would be
9223 // better to keep them in CR bits.
9225 // Note that trunc here can be an actual i1 trunc, or can be the effective
9226 // truncation that comes from a setcc or select_cc.
9227 if (N->getOpcode() == ISD::TRUNCATE &&
9228 N->getValueType(0) != MVT::i1)
9231 if (N->getOperand(0).getValueType() != MVT::i32 &&
9232 N->getOperand(0).getValueType() != MVT::i64)
9235 if (N->getOpcode() == ISD::SETCC ||
9236 N->getOpcode() == ISD::SELECT_CC) {
9237 // If we're looking at a comparison, then we need to make sure that the
9238 // high bits (all except for the first) don't matter the result.
9240 cast<CondCodeSDNode>(N->getOperand(
9241 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9242 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9244 if (ISD::isSignedIntSetCC(CC)) {
9245 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9246 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9248 } else if (ISD::isUnsignedIntSetCC(CC)) {
9249 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9250 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9251 !DAG.MaskedValueIsZero(N->getOperand(1),
9252 APInt::getHighBitsSet(OpBits, OpBits-1)))
9255 // This is neither a signed nor an unsigned comparison, just make sure
9256 // that the high bits are equal.
9257 APInt Op1Zero, Op1One;
9258 APInt Op2Zero, Op2One;
9259 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9260 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9262 // We don't really care about what is known about the first bit (if
9263 // anything), so clear it in all masks prior to comparing them.
9264 Op1Zero.clearBit(0); Op1One.clearBit(0);
9265 Op2Zero.clearBit(0); Op2One.clearBit(0);
9267 if (Op1Zero != Op2Zero || Op1One != Op2One)
9272 // We now know that the higher-order bits are irrelevant, we just need to
9273 // make sure that all of the intermediate operations are bit operations, and
9274 // all inputs are extensions.
9275 if (N->getOperand(0).getOpcode() != ISD::AND &&
9276 N->getOperand(0).getOpcode() != ISD::OR &&
9277 N->getOperand(0).getOpcode() != ISD::XOR &&
9278 N->getOperand(0).getOpcode() != ISD::SELECT &&
9279 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9280 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9281 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9282 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9283 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9286 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9287 N->getOperand(1).getOpcode() != ISD::AND &&
9288 N->getOperand(1).getOpcode() != ISD::OR &&
9289 N->getOperand(1).getOpcode() != ISD::XOR &&
9290 N->getOperand(1).getOpcode() != ISD::SELECT &&
9291 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9292 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9293 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9294 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9295 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9298 SmallVector<SDValue, 4> Inputs;
9299 SmallVector<SDValue, 8> BinOps, PromOps;
9300 SmallPtrSet<SDNode *, 16> Visited;
9302 for (unsigned i = 0; i < 2; ++i) {
9303 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9304 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9305 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9306 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9307 isa<ConstantSDNode>(N->getOperand(i)))
9308 Inputs.push_back(N->getOperand(i));
9310 BinOps.push_back(N->getOperand(i));
9312 if (N->getOpcode() == ISD::TRUNCATE)
9316 // Visit all inputs, collect all binary operations (and, or, xor and
9317 // select) that are all fed by extensions.
9318 while (!BinOps.empty()) {
9319 SDValue BinOp = BinOps.back();
9322 if (!Visited.insert(BinOp.getNode()).second)
9325 PromOps.push_back(BinOp);
9327 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9328 // The condition of the select is not promoted.
9329 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9331 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9334 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9335 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9336 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9337 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9338 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9339 Inputs.push_back(BinOp.getOperand(i));
9340 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9341 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9342 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9343 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9344 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9345 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9346 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9347 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9348 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9349 BinOps.push_back(BinOp.getOperand(i));
9351 // We have an input that is not an extension or another binary
9352 // operation; we'll abort this transformation.
9358 // Make sure that this is a self-contained cluster of operations (which
9359 // is not quite the same thing as saying that everything has only one
9361 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9362 if (isa<ConstantSDNode>(Inputs[i]))
9365 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9366 UE = Inputs[i].getNode()->use_end();
9369 if (User != N && !Visited.count(User))
9372 // Make sure that we're not going to promote the non-output-value
9373 // operand(s) or SELECT or SELECT_CC.
9374 // FIXME: Although we could sometimes handle this, and it does occur in
9375 // practice that one of the condition inputs to the select is also one of
9376 // the outputs, we currently can't deal with this.
9377 if (User->getOpcode() == ISD::SELECT) {
9378 if (User->getOperand(0) == Inputs[i])
9380 } else if (User->getOpcode() == ISD::SELECT_CC) {
9381 if (User->getOperand(0) == Inputs[i] ||
9382 User->getOperand(1) == Inputs[i])
9388 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9389 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9390 UE = PromOps[i].getNode()->use_end();
9393 if (User != N && !Visited.count(User))
9396 // Make sure that we're not going to promote the non-output-value
9397 // operand(s) or SELECT or SELECT_CC.
9398 // FIXME: Although we could sometimes handle this, and it does occur in
9399 // practice that one of the condition inputs to the select is also one of
9400 // the outputs, we currently can't deal with this.
9401 if (User->getOpcode() == ISD::SELECT) {
9402 if (User->getOperand(0) == PromOps[i])
9404 } else if (User->getOpcode() == ISD::SELECT_CC) {
9405 if (User->getOperand(0) == PromOps[i] ||
9406 User->getOperand(1) == PromOps[i])
9412 // Replace all inputs with the extension operand.
9413 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9414 // Constants may have users outside the cluster of to-be-promoted nodes,
9415 // and so we need to replace those as we do the promotions.
9416 if (isa<ConstantSDNode>(Inputs[i]))
9419 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9422 // Replace all operations (these are all the same, but have a different
9423 // (i1) return type). DAG.getNode will validate that the types of
9424 // a binary operator match, so go through the list in reverse so that
9425 // we've likely promoted both operands first. Any intermediate truncations or
9426 // extensions disappear.
9427 while (!PromOps.empty()) {
9428 SDValue PromOp = PromOps.back();
9431 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9432 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9433 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9434 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9435 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9436 PromOp.getOperand(0).getValueType() != MVT::i1) {
9437 // The operand is not yet ready (see comment below).
9438 PromOps.insert(PromOps.begin(), PromOp);
9442 SDValue RepValue = PromOp.getOperand(0);
9443 if (isa<ConstantSDNode>(RepValue))
9444 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9446 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9451 switch (PromOp.getOpcode()) {
9452 default: C = 0; break;
9453 case ISD::SELECT: C = 1; break;
9454 case ISD::SELECT_CC: C = 2; break;
9457 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9458 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9459 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9460 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9461 // The to-be-promoted operands of this node have not yet been
9462 // promoted (this should be rare because we're going through the
9463 // list backward, but if one of the operands has several users in
9464 // this cluster of to-be-promoted nodes, it is possible).
9465 PromOps.insert(PromOps.begin(), PromOp);
9469 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9470 PromOp.getNode()->op_end());
9472 // If there are any constant inputs, make sure they're replaced now.
9473 for (unsigned i = 0; i < 2; ++i)
9474 if (isa<ConstantSDNode>(Ops[C+i]))
9475 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9477 DAG.ReplaceAllUsesOfValueWith(PromOp,
9478 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9481 // Now we're left with the initial truncation itself.
9482 if (N->getOpcode() == ISD::TRUNCATE)
9483 return N->getOperand(0);
9485 // Otherwise, this is a comparison. The operands to be compared have just
9486 // changed type (to i1), but everything else is the same.
9487 return SDValue(N, 0);
9490 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9491 DAGCombinerInfo &DCI) const {
9492 SelectionDAG &DAG = DCI.DAG;
9495 // If we're tracking CR bits, we need to be careful that we don't have:
9496 // zext(binary-ops(trunc(x), trunc(y)))
9498 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9499 // such that we're unnecessarily moving things into CR bits that can more
9500 // efficiently stay in GPRs. Note that if we're not certain that the high
9501 // bits are set as required by the final extension, we still may need to do
9502 // some masking to get the proper behavior.
9504 // This same functionality is important on PPC64 when dealing with
9505 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9506 // the return values of functions. Because it is so similar, it is handled
9509 if (N->getValueType(0) != MVT::i32 &&
9510 N->getValueType(0) != MVT::i64)
9513 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9514 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9517 if (N->getOperand(0).getOpcode() != ISD::AND &&
9518 N->getOperand(0).getOpcode() != ISD::OR &&
9519 N->getOperand(0).getOpcode() != ISD::XOR &&
9520 N->getOperand(0).getOpcode() != ISD::SELECT &&
9521 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9524 SmallVector<SDValue, 4> Inputs;
9525 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9526 SmallPtrSet<SDNode *, 16> Visited;
9528 // Visit all inputs, collect all binary operations (and, or, xor and
9529 // select) that are all fed by truncations.
9530 while (!BinOps.empty()) {
9531 SDValue BinOp = BinOps.back();
9534 if (!Visited.insert(BinOp.getNode()).second)
9537 PromOps.push_back(BinOp);
9539 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9540 // The condition of the select is not promoted.
9541 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9543 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9546 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9547 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9548 Inputs.push_back(BinOp.getOperand(i));
9549 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9550 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9551 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9552 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9553 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9554 BinOps.push_back(BinOp.getOperand(i));
9556 // We have an input that is not a truncation or another binary
9557 // operation; we'll abort this transformation.
9563 // The operands of a select that must be truncated when the select is
9564 // promoted because the operand is actually part of the to-be-promoted set.
9565 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9567 // Make sure that this is a self-contained cluster of operations (which
9568 // is not quite the same thing as saying that everything has only one
9570 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9571 if (isa<ConstantSDNode>(Inputs[i]))
9574 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9575 UE = Inputs[i].getNode()->use_end();
9578 if (User != N && !Visited.count(User))
9581 // If we're going to promote the non-output-value operand(s) or SELECT or
9582 // SELECT_CC, record them for truncation.
9583 if (User->getOpcode() == ISD::SELECT) {
9584 if (User->getOperand(0) == Inputs[i])
9585 SelectTruncOp[0].insert(std::make_pair(User,
9586 User->getOperand(0).getValueType()));
9587 } else if (User->getOpcode() == ISD::SELECT_CC) {
9588 if (User->getOperand(0) == Inputs[i])
9589 SelectTruncOp[0].insert(std::make_pair(User,
9590 User->getOperand(0).getValueType()));
9591 if (User->getOperand(1) == Inputs[i])
9592 SelectTruncOp[1].insert(std::make_pair(User,
9593 User->getOperand(1).getValueType()));
9598 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9599 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9600 UE = PromOps[i].getNode()->use_end();
9603 if (User != N && !Visited.count(User))
9606 // If we're going to promote the non-output-value operand(s) or SELECT or
9607 // SELECT_CC, record them for truncation.
9608 if (User->getOpcode() == ISD::SELECT) {
9609 if (User->getOperand(0) == PromOps[i])
9610 SelectTruncOp[0].insert(std::make_pair(User,
9611 User->getOperand(0).getValueType()));
9612 } else if (User->getOpcode() == ISD::SELECT_CC) {
9613 if (User->getOperand(0) == PromOps[i])
9614 SelectTruncOp[0].insert(std::make_pair(User,
9615 User->getOperand(0).getValueType()));
9616 if (User->getOperand(1) == PromOps[i])
9617 SelectTruncOp[1].insert(std::make_pair(User,
9618 User->getOperand(1).getValueType()));
9623 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9624 bool ReallyNeedsExt = false;
9625 if (N->getOpcode() != ISD::ANY_EXTEND) {
9626 // If all of the inputs are not already sign/zero extended, then
9627 // we'll still need to do that at the end.
9628 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9629 if (isa<ConstantSDNode>(Inputs[i]))
9633 Inputs[i].getOperand(0).getValueSizeInBits();
9634 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9636 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9637 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9638 APInt::getHighBitsSet(OpBits,
9639 OpBits-PromBits))) ||
9640 (N->getOpcode() == ISD::SIGN_EXTEND &&
9641 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9642 (OpBits-(PromBits-1)))) {
9643 ReallyNeedsExt = true;
9649 // Replace all inputs, either with the truncation operand, or a
9650 // truncation or extension to the final output type.
9651 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9652 // Constant inputs need to be replaced with the to-be-promoted nodes that
9653 // use them because they might have users outside of the cluster of
9655 if (isa<ConstantSDNode>(Inputs[i]))
9658 SDValue InSrc = Inputs[i].getOperand(0);
9659 if (Inputs[i].getValueType() == N->getValueType(0))
9660 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9661 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9662 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9663 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9664 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9665 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9666 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9668 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9669 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9672 // Replace all operations (these are all the same, but have a different
9673 // (promoted) return type). DAG.getNode will validate that the types of
9674 // a binary operator match, so go through the list in reverse so that
9675 // we've likely promoted both operands first.
9676 while (!PromOps.empty()) {
9677 SDValue PromOp = PromOps.back();
9681 switch (PromOp.getOpcode()) {
9682 default: C = 0; break;
9683 case ISD::SELECT: C = 1; break;
9684 case ISD::SELECT_CC: C = 2; break;
9687 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9688 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9689 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9690 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9691 // The to-be-promoted operands of this node have not yet been
9692 // promoted (this should be rare because we're going through the
9693 // list backward, but if one of the operands has several users in
9694 // this cluster of to-be-promoted nodes, it is possible).
9695 PromOps.insert(PromOps.begin(), PromOp);
9699 // For SELECT and SELECT_CC nodes, we do a similar check for any
9700 // to-be-promoted comparison inputs.
9701 if (PromOp.getOpcode() == ISD::SELECT ||
9702 PromOp.getOpcode() == ISD::SELECT_CC) {
9703 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9704 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9705 (SelectTruncOp[1].count(PromOp.getNode()) &&
9706 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9707 PromOps.insert(PromOps.begin(), PromOp);
9712 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9713 PromOp.getNode()->op_end());
9715 // If this node has constant inputs, then they'll need to be promoted here.
9716 for (unsigned i = 0; i < 2; ++i) {
9717 if (!isa<ConstantSDNode>(Ops[C+i]))
9719 if (Ops[C+i].getValueType() == N->getValueType(0))
9722 if (N->getOpcode() == ISD::SIGN_EXTEND)
9723 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9724 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9725 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9727 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9730 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9731 // truncate them again to the original value type.
9732 if (PromOp.getOpcode() == ISD::SELECT ||
9733 PromOp.getOpcode() == ISD::SELECT_CC) {
9734 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9735 if (SI0 != SelectTruncOp[0].end())
9736 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9737 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9738 if (SI1 != SelectTruncOp[1].end())
9739 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9742 DAG.ReplaceAllUsesOfValueWith(PromOp,
9743 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9746 // Now we're left with the initial extension itself.
9747 if (!ReallyNeedsExt)
9748 return N->getOperand(0);
9750 // To zero extend, just mask off everything except for the first bit (in the
9752 if (N->getOpcode() == ISD::ZERO_EXTEND)
9753 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9754 DAG.getConstant(APInt::getLowBitsSet(
9755 N->getValueSizeInBits(0), PromBits),
9756 dl, N->getValueType(0)));
9758 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9759 "Invalid extension type");
9760 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9762 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9763 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
9764 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9765 N->getOperand(0), ShiftCst), ShiftCst);
9768 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9769 DAGCombinerInfo &DCI) const {
9770 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9771 N->getOpcode() == ISD::UINT_TO_FP) &&
9772 "Need an int -> FP conversion node here");
9774 if (!Subtarget.has64BitSupport())
9777 SelectionDAG &DAG = DCI.DAG;
9781 // Don't handle ppc_fp128 here or i1 conversions.
9782 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9784 if (Op.getOperand(0).getValueType() == MVT::i1)
9787 // For i32 intermediate values, unfortunately, the conversion functions
9788 // leave the upper 32 bits of the value are undefined. Within the set of
9789 // scalar instructions, we have no method for zero- or sign-extending the
9790 // value. Thus, we cannot handle i32 intermediate values here.
9791 if (Op.getOperand(0).getValueType() == MVT::i32)
9794 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9795 "UINT_TO_FP is supported only with FPCVT");
9797 // If we have FCFIDS, then use it when converting to single-precision.
9798 // Otherwise, convert to double-precision and then round.
9799 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9800 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9802 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9804 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9808 // If we're converting from a float, to an int, and back to a float again,
9809 // then we don't need the store/load pair at all.
9810 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9811 Subtarget.hasFPCVT()) ||
9812 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9813 SDValue Src = Op.getOperand(0).getOperand(0);
9814 if (Src.getValueType() == MVT::f32) {
9815 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9816 DCI.AddToWorklist(Src.getNode());
9820 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9823 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9824 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9826 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9827 FP = DAG.getNode(ISD::FP_ROUND, dl,
9828 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
9829 DCI.AddToWorklist(FP.getNode());
9838 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9839 // builtins) into loads with swaps.
9840 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9841 DAGCombinerInfo &DCI) const {
9842 SelectionDAG &DAG = DCI.DAG;
9846 MachineMemOperand *MMO;
9848 switch (N->getOpcode()) {
9850 llvm_unreachable("Unexpected opcode for little endian VSX load");
9852 LoadSDNode *LD = cast<LoadSDNode>(N);
9853 Chain = LD->getChain();
9854 Base = LD->getBasePtr();
9855 MMO = LD->getMemOperand();
9856 // If the MMO suggests this isn't a load of a full vector, leave
9857 // things alone. For a built-in, we have to make the change for
9858 // correctness, so if there is a size problem that will be a bug.
9859 if (MMO->getSize() < 16)
9863 case ISD::INTRINSIC_W_CHAIN: {
9864 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9865 Chain = Intrin->getChain();
9866 Base = Intrin->getBasePtr();
9867 MMO = Intrin->getMemOperand();
9872 MVT VecTy = N->getValueType(0).getSimpleVT();
9873 SDValue LoadOps[] = { Chain, Base };
9874 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9875 DAG.getVTList(VecTy, MVT::Other),
9876 LoadOps, VecTy, MMO);
9877 DCI.AddToWorklist(Load.getNode());
9878 Chain = Load.getValue(1);
9879 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9880 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9881 DCI.AddToWorklist(Swap.getNode());
9885 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9886 // builtins) into stores with swaps.
9887 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9888 DAGCombinerInfo &DCI) const {
9889 SelectionDAG &DAG = DCI.DAG;
9894 MachineMemOperand *MMO;
9896 switch (N->getOpcode()) {
9898 llvm_unreachable("Unexpected opcode for little endian VSX store");
9900 StoreSDNode *ST = cast<StoreSDNode>(N);
9901 Chain = ST->getChain();
9902 Base = ST->getBasePtr();
9903 MMO = ST->getMemOperand();
9905 // If the MMO suggests this isn't a store of a full vector, leave
9906 // things alone. For a built-in, we have to make the change for
9907 // correctness, so if there is a size problem that will be a bug.
9908 if (MMO->getSize() < 16)
9912 case ISD::INTRINSIC_VOID: {
9913 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9914 Chain = Intrin->getChain();
9915 // Intrin->getBasePtr() oddly does not get what we want.
9916 Base = Intrin->getOperand(3);
9917 MMO = Intrin->getMemOperand();
9923 SDValue Src = N->getOperand(SrcOpnd);
9924 MVT VecTy = Src.getValueType().getSimpleVT();
9925 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9926 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9927 DCI.AddToWorklist(Swap.getNode());
9928 Chain = Swap.getValue(1);
9929 SDValue StoreOps[] = { Chain, Swap, Base };
9930 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9931 DAG.getVTList(MVT::Other),
9932 StoreOps, VecTy, MMO);
9933 DCI.AddToWorklist(Store.getNode());
9937 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9938 DAGCombinerInfo &DCI) const {
9939 SelectionDAG &DAG = DCI.DAG;
9941 switch (N->getOpcode()) {
9944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9945 if (C->isNullValue()) // 0 << V -> 0.
9946 return N->getOperand(0);
9950 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9951 if (C->isNullValue()) // 0 >>u V -> 0.
9952 return N->getOperand(0);
9956 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9957 if (C->isNullValue() || // 0 >>s V -> 0.
9958 C->isAllOnesValue()) // -1 >>s V -> -1.
9959 return N->getOperand(0);
9962 case ISD::SIGN_EXTEND:
9963 case ISD::ZERO_EXTEND:
9964 case ISD::ANY_EXTEND:
9965 return DAGCombineExtBoolTrunc(N, DCI);
9968 case ISD::SELECT_CC:
9969 return DAGCombineTruncBoolExt(N, DCI);
9970 case ISD::SINT_TO_FP:
9971 case ISD::UINT_TO_FP:
9972 return combineFPToIntToFP(N, DCI);
9974 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9975 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9976 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9977 N->getOperand(1).getValueType() == MVT::i32 &&
9978 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9979 SDValue Val = N->getOperand(1).getOperand(0);
9980 if (Val.getValueType() == MVT::f32) {
9981 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9982 DCI.AddToWorklist(Val.getNode());
9984 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9985 DCI.AddToWorklist(Val.getNode());
9988 N->getOperand(0), Val, N->getOperand(2),
9989 DAG.getValueType(N->getOperand(1).getValueType())
9992 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9993 DAG.getVTList(MVT::Other), Ops,
9994 cast<StoreSDNode>(N)->getMemoryVT(),
9995 cast<StoreSDNode>(N)->getMemOperand());
9996 DCI.AddToWorklist(Val.getNode());
10000 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10001 if (cast<StoreSDNode>(N)->isUnindexed() &&
10002 N->getOperand(1).getOpcode() == ISD::BSWAP &&
10003 N->getOperand(1).getNode()->hasOneUse() &&
10004 (N->getOperand(1).getValueType() == MVT::i32 ||
10005 N->getOperand(1).getValueType() == MVT::i16 ||
10006 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10007 N->getOperand(1).getValueType() == MVT::i64))) {
10008 SDValue BSwapOp = N->getOperand(1).getOperand(0);
10009 // Do an any-extend to 32-bits if this is a half-word input.
10010 if (BSwapOp.getValueType() == MVT::i16)
10011 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10014 N->getOperand(0), BSwapOp, N->getOperand(2),
10015 DAG.getValueType(N->getOperand(1).getValueType())
10018 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10019 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10020 cast<StoreSDNode>(N)->getMemOperand());
10023 // For little endian, VSX stores require generating xxswapd/lxvd2x.
10024 EVT VT = N->getOperand(1).getValueType();
10025 if (VT.isSimple()) {
10026 MVT StoreVT = VT.getSimpleVT();
10027 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10028 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10029 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10030 return expandVSXStoreForLE(N, DCI);
10035 LoadSDNode *LD = cast<LoadSDNode>(N);
10036 EVT VT = LD->getValueType(0);
10038 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10039 if (VT.isSimple()) {
10040 MVT LoadVT = VT.getSimpleVT();
10041 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10042 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10043 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10044 return expandVSXLoadForLE(N, DCI);
10047 EVT MemVT = LD->getMemoryVT();
10048 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10049 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
10050 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10051 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
10052 if (LD->isUnindexed() && VT.isVector() &&
10053 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10054 // P8 and later hardware should just use LOAD.
10055 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10056 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10057 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10058 LD->getAlignment() >= ScalarABIAlignment)) &&
10059 LD->getAlignment() < ABIAlignment) {
10060 // This is a type-legal unaligned Altivec or QPX load.
10061 SDValue Chain = LD->getChain();
10062 SDValue Ptr = LD->getBasePtr();
10063 bool isLittleEndian = Subtarget.isLittleEndian();
10065 // This implements the loading of unaligned vectors as described in
10066 // the venerable Apple Velocity Engine overview. Specifically:
10067 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10068 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10070 // The general idea is to expand a sequence of one or more unaligned
10071 // loads into an alignment-based permutation-control instruction (lvsl
10072 // or lvsr), a series of regular vector loads (which always truncate
10073 // their input address to an aligned address), and a series of
10074 // permutations. The results of these permutations are the requested
10075 // loaded values. The trick is that the last "extra" load is not taken
10076 // from the address you might suspect (sizeof(vector) bytes after the
10077 // last requested load), but rather sizeof(vector) - 1 bytes after the
10078 // last requested vector. The point of this is to avoid a page fault if
10079 // the base address happened to be aligned. This works because if the
10080 // base address is aligned, then adding less than a full vector length
10081 // will cause the last vector in the sequence to be (re)loaded.
10082 // Otherwise, the next vector will be fetched as you might suspect was
10085 // We might be able to reuse the permutation generation from
10086 // a different base address offset from this one by an aligned amount.
10087 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10088 // optimization later.
10089 Intrinsic::ID Intr, IntrLD, IntrPerm;
10090 MVT PermCntlTy, PermTy, LDTy;
10091 if (Subtarget.hasAltivec()) {
10092 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
10093 Intrinsic::ppc_altivec_lvsl;
10094 IntrLD = Intrinsic::ppc_altivec_lvx;
10095 IntrPerm = Intrinsic::ppc_altivec_vperm;
10096 PermCntlTy = MVT::v16i8;
10097 PermTy = MVT::v4i32;
10100 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10101 Intrinsic::ppc_qpx_qvlpcls;
10102 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10103 Intrinsic::ppc_qpx_qvlfs;
10104 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10105 PermCntlTy = MVT::v4f64;
10106 PermTy = MVT::v4f64;
10107 LDTy = MemVT.getSimpleVT();
10110 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10112 // Create the new MMO for the new base load. It is like the original MMO,
10113 // but represents an area in memory almost twice the vector size centered
10114 // on the original address. If the address is unaligned, we might start
10115 // reading up to (sizeof(vector)-1) bytes below the address of the
10116 // original unaligned load.
10117 MachineFunction &MF = DAG.getMachineFunction();
10118 MachineMemOperand *BaseMMO =
10119 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10120 2*MemVT.getStoreSize()-1);
10122 // Create the new base load.
10123 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, dl, getPointerTy());
10124 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10126 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10127 DAG.getVTList(PermTy, MVT::Other),
10128 BaseLoadOps, LDTy, BaseMMO);
10130 // Note that the value of IncOffset (which is provided to the next
10131 // load's pointer info offset value, and thus used to calculate the
10132 // alignment), and the value of IncValue (which is actually used to
10133 // increment the pointer value) are different! This is because we
10134 // require the next load to appear to be aligned, even though it
10135 // is actually offset from the base pointer by a lesser amount.
10136 int IncOffset = VT.getSizeInBits() / 8;
10137 int IncValue = IncOffset;
10139 // Walk (both up and down) the chain looking for another load at the real
10140 // (aligned) offset (the alignment of the other load does not matter in
10141 // this case). If found, then do not use the offset reduction trick, as
10142 // that will prevent the loads from being later combined (as they would
10143 // otherwise be duplicates).
10144 if (!findConsecutiveLoad(LD, DAG))
10147 SDValue Increment = DAG.getConstant(IncValue, dl, getPointerTy());
10148 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10150 MachineMemOperand *ExtraMMO =
10151 MF.getMachineMemOperand(LD->getMemOperand(),
10152 1, 2*MemVT.getStoreSize()-1);
10153 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10154 SDValue ExtraLoad =
10155 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10156 DAG.getVTList(PermTy, MVT::Other),
10157 ExtraLoadOps, LDTy, ExtraMMO);
10159 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10160 BaseLoad.getValue(1), ExtraLoad.getValue(1));
10162 // Because vperm has a big-endian bias, we must reverse the order
10163 // of the input vectors and complement the permute control vector
10164 // when generating little endian code. We have already handled the
10165 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10166 // and ExtraLoad here.
10168 if (isLittleEndian)
10169 Perm = BuildIntrinsicOp(IntrPerm,
10170 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10172 Perm = BuildIntrinsicOp(IntrPerm,
10173 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10176 Perm = Subtarget.hasAltivec() ?
10177 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10178 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10179 DAG.getTargetConstant(1, dl, MVT::i64));
10180 // second argument is 1 because this rounding
10181 // is always exact.
10183 // The output of the permutation is our loaded result, the TokenFactor is
10185 DCI.CombineTo(N, Perm, TF);
10186 return SDValue(N, 0);
10190 case ISD::INTRINSIC_WO_CHAIN: {
10191 bool isLittleEndian = Subtarget.isLittleEndian();
10192 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10193 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10194 : Intrinsic::ppc_altivec_lvsl);
10195 if ((IID == Intr ||
10196 IID == Intrinsic::ppc_qpx_qvlpcld ||
10197 IID == Intrinsic::ppc_qpx_qvlpcls) &&
10198 N->getOperand(1)->getOpcode() == ISD::ADD) {
10199 SDValue Add = N->getOperand(1);
10201 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10202 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10204 if (DAG.MaskedValueIsZero(
10205 Add->getOperand(1),
10206 APInt::getAllOnesValue(Bits /* alignment */)
10208 Add.getValueType().getScalarType().getSizeInBits()))) {
10209 SDNode *BasePtr = Add->getOperand(0).getNode();
10210 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10211 UE = BasePtr->use_end();
10213 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10214 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10215 // We've found another LVSL/LVSR, and this address is an aligned
10216 // multiple of that one. The results will be the same, so use the
10217 // one we've just found instead.
10219 return SDValue(*UI, 0);
10224 if (isa<ConstantSDNode>(Add->getOperand(1))) {
10225 SDNode *BasePtr = Add->getOperand(0).getNode();
10226 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10227 UE = BasePtr->use_end(); UI != UE; ++UI) {
10228 if (UI->getOpcode() == ISD::ADD &&
10229 isa<ConstantSDNode>(UI->getOperand(1)) &&
10230 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10231 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10232 (1ULL << Bits) == 0) {
10233 SDNode *OtherAdd = *UI;
10234 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10235 VE = OtherAdd->use_end(); VI != VE; ++VI) {
10236 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10237 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10238 return SDValue(*VI, 0);
10248 case ISD::INTRINSIC_W_CHAIN: {
10249 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10250 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10251 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10254 case Intrinsic::ppc_vsx_lxvw4x:
10255 case Intrinsic::ppc_vsx_lxvd2x:
10256 return expandVSXLoadForLE(N, DCI);
10261 case ISD::INTRINSIC_VOID: {
10262 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10263 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10264 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10267 case Intrinsic::ppc_vsx_stxvw4x:
10268 case Intrinsic::ppc_vsx_stxvd2x:
10269 return expandVSXStoreForLE(N, DCI);
10275 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10276 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10277 N->getOperand(0).hasOneUse() &&
10278 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10279 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10280 N->getValueType(0) == MVT::i64))) {
10281 SDValue Load = N->getOperand(0);
10282 LoadSDNode *LD = cast<LoadSDNode>(Load);
10283 // Create the byte-swapping load.
10285 LD->getChain(), // Chain
10286 LD->getBasePtr(), // Ptr
10287 DAG.getValueType(N->getValueType(0)) // VT
10290 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10291 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10292 MVT::i64 : MVT::i32, MVT::Other),
10293 Ops, LD->getMemoryVT(), LD->getMemOperand());
10295 // If this is an i16 load, insert the truncate.
10296 SDValue ResVal = BSLoad;
10297 if (N->getValueType(0) == MVT::i16)
10298 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10300 // First, combine the bswap away. This makes the value produced by the
10302 DCI.CombineTo(N, ResVal);
10304 // Next, combine the load away, we give it a bogus result value but a real
10305 // chain result. The result value is dead because the bswap is dead.
10306 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10308 // Return N so it doesn't get rechecked!
10309 return SDValue(N, 0);
10313 case PPCISD::VCMP: {
10314 // If a VCMPo node already exists with exactly the same operands as this
10315 // node, use its result instead of this node (VCMPo computes both a CR6 and
10316 // a normal output).
10318 if (!N->getOperand(0).hasOneUse() &&
10319 !N->getOperand(1).hasOneUse() &&
10320 !N->getOperand(2).hasOneUse()) {
10322 // Scan all of the users of the LHS, looking for VCMPo's that match.
10323 SDNode *VCMPoNode = nullptr;
10325 SDNode *LHSN = N->getOperand(0).getNode();
10326 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10328 if (UI->getOpcode() == PPCISD::VCMPo &&
10329 UI->getOperand(1) == N->getOperand(1) &&
10330 UI->getOperand(2) == N->getOperand(2) &&
10331 UI->getOperand(0) == N->getOperand(0)) {
10336 // If there is no VCMPo node, or if the flag value has a single use, don't
10338 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10341 // Look at the (necessarily single) use of the flag value. If it has a
10342 // chain, this transformation is more complex. Note that multiple things
10343 // could use the value result, which we should ignore.
10344 SDNode *FlagUser = nullptr;
10345 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10346 FlagUser == nullptr; ++UI) {
10347 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10348 SDNode *User = *UI;
10349 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10350 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10357 // If the user is a MFOCRF instruction, we know this is safe.
10358 // Otherwise we give up for right now.
10359 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10360 return SDValue(VCMPoNode, 0);
10364 case ISD::BRCOND: {
10365 SDValue Cond = N->getOperand(1);
10366 SDValue Target = N->getOperand(2);
10368 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10369 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10370 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10372 // We now need to make the intrinsic dead (it cannot be instruction
10374 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10375 assert(Cond.getNode()->hasOneUse() &&
10376 "Counter decrement has more than one use");
10378 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10379 N->getOperand(0), Target);
10384 // If this is a branch on an altivec predicate comparison, lower this so
10385 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10386 // lowering is done pre-legalize, because the legalizer lowers the predicate
10387 // compare down to code that is difficult to reassemble.
10388 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10389 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10391 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10392 // value. If so, pass-through the AND to get to the intrinsic.
10393 if (LHS.getOpcode() == ISD::AND &&
10394 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10395 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10396 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10397 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10398 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10400 LHS = LHS.getOperand(0);
10402 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10403 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10404 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10405 isa<ConstantSDNode>(RHS)) {
10406 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10407 "Counter decrement comparison is not EQ or NE");
10409 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10410 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10411 (CC == ISD::SETNE && !Val);
10413 // We now need to make the intrinsic dead (it cannot be instruction
10415 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10416 assert(LHS.getNode()->hasOneUse() &&
10417 "Counter decrement has more than one use");
10419 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10420 N->getOperand(0), N->getOperand(4));
10426 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10427 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10428 getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10429 assert(isDot && "Can't compare against a vector result!");
10431 // If this is a comparison against something other than 0/1, then we know
10432 // that the condition is never/always true.
10433 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10434 if (Val != 0 && Val != 1) {
10435 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10436 return N->getOperand(0);
10437 // Always !=, turn it into an unconditional branch.
10438 return DAG.getNode(ISD::BR, dl, MVT::Other,
10439 N->getOperand(0), N->getOperand(4));
10442 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10444 // Create the PPCISD altivec 'dot' comparison node.
10446 LHS.getOperand(2), // LHS of compare
10447 LHS.getOperand(3), // RHS of compare
10448 DAG.getConstant(CompareOpc, dl, MVT::i32)
10450 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10451 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10453 // Unpack the result based on how the target uses it.
10454 PPC::Predicate CompOpc;
10455 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10456 default: // Can't happen, don't crash on invalid number though.
10457 case 0: // Branch on the value of the EQ bit of CR6.
10458 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10460 case 1: // Branch on the inverted value of the EQ bit of CR6.
10461 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10463 case 2: // Branch on the value of the LT bit of CR6.
10464 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10466 case 3: // Branch on the inverted value of the LT bit of CR6.
10467 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10471 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10472 DAG.getConstant(CompOpc, dl, MVT::i32),
10473 DAG.getRegister(PPC::CR6, MVT::i32),
10474 N->getOperand(4), CompNode.getValue(1));
10484 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10486 std::vector<SDNode *> *Created) const {
10487 // fold (sdiv X, pow2)
10488 EVT VT = N->getValueType(0);
10489 if (VT == MVT::i64 && !Subtarget.isPPC64())
10491 if ((VT != MVT::i32 && VT != MVT::i64) ||
10492 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10496 SDValue N0 = N->getOperand(0);
10498 bool IsNegPow2 = (-Divisor).isPowerOf2();
10499 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10500 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10502 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10504 Created->push_back(Op.getNode());
10507 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10509 Created->push_back(Op.getNode());
10515 //===----------------------------------------------------------------------===//
10516 // Inline Assembly Support
10517 //===----------------------------------------------------------------------===//
10519 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10522 const SelectionDAG &DAG,
10523 unsigned Depth) const {
10524 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10525 switch (Op.getOpcode()) {
10527 case PPCISD::LBRX: {
10528 // lhbrx is known to have the top bits cleared out.
10529 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10530 KnownZero = 0xFFFF0000;
10533 case ISD::INTRINSIC_WO_CHAIN: {
10534 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10536 case Intrinsic::ppc_altivec_vcmpbfp_p:
10537 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10538 case Intrinsic::ppc_altivec_vcmpequb_p:
10539 case Intrinsic::ppc_altivec_vcmpequh_p:
10540 case Intrinsic::ppc_altivec_vcmpequw_p:
10541 case Intrinsic::ppc_altivec_vcmpequd_p:
10542 case Intrinsic::ppc_altivec_vcmpgefp_p:
10543 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10544 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10545 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10546 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10547 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10548 case Intrinsic::ppc_altivec_vcmpgtub_p:
10549 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10550 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10551 case Intrinsic::ppc_altivec_vcmpgtud_p:
10552 KnownZero = ~1U; // All bits but the low one are known to be zero.
10559 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10560 switch (Subtarget.getDarwinDirective()) {
10563 case PPC::DIR_PWR4:
10564 case PPC::DIR_PWR5:
10565 case PPC::DIR_PWR5X:
10566 case PPC::DIR_PWR6:
10567 case PPC::DIR_PWR6X:
10568 case PPC::DIR_PWR7:
10569 case PPC::DIR_PWR8: {
10573 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10575 // For small loops (between 5 and 8 instructions), align to a 32-byte
10576 // boundary so that the entire loop fits in one instruction-cache line.
10577 uint64_t LoopSize = 0;
10578 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10579 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10580 LoopSize += TII->GetInstSizeInBytes(J);
10582 if (LoopSize > 16 && LoopSize <= 32)
10589 return TargetLowering::getPrefLoopAlignment(ML);
10592 /// getConstraintType - Given a constraint, return the type of
10593 /// constraint it is for this target.
10594 PPCTargetLowering::ConstraintType
10595 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10596 if (Constraint.size() == 1) {
10597 switch (Constraint[0]) {
10604 return C_RegisterClass;
10606 // FIXME: While Z does indicate a memory constraint, it specifically
10607 // indicates an r+r address (used in conjunction with the 'y' modifier
10608 // in the replacement string). Currently, we're forcing the base
10609 // register to be r0 in the asm printer (which is interpreted as zero)
10610 // and forming the complete address in the second register. This is
10614 } else if (Constraint == "wc") { // individual CR bits.
10615 return C_RegisterClass;
10616 } else if (Constraint == "wa" || Constraint == "wd" ||
10617 Constraint == "wf" || Constraint == "ws") {
10618 return C_RegisterClass; // VSX registers.
10620 return TargetLowering::getConstraintType(Constraint);
10623 /// Examine constraint type and operand type and determine a weight value.
10624 /// This object must already have been set up with the operand type
10625 /// and the current alternative constraint selected.
10626 TargetLowering::ConstraintWeight
10627 PPCTargetLowering::getSingleConstraintMatchWeight(
10628 AsmOperandInfo &info, const char *constraint) const {
10629 ConstraintWeight weight = CW_Invalid;
10630 Value *CallOperandVal = info.CallOperandVal;
10631 // If we don't have a value, we can't do a match,
10632 // but allow it at the lowest weight.
10633 if (!CallOperandVal)
10635 Type *type = CallOperandVal->getType();
10637 // Look at the constraint type.
10638 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10639 return CW_Register; // an individual CR bit.
10640 else if ((StringRef(constraint) == "wa" ||
10641 StringRef(constraint) == "wd" ||
10642 StringRef(constraint) == "wf") &&
10643 type->isVectorTy())
10644 return CW_Register;
10645 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10646 return CW_Register;
10648 switch (*constraint) {
10650 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10653 if (type->isIntegerTy())
10654 weight = CW_Register;
10657 if (type->isFloatTy())
10658 weight = CW_Register;
10661 if (type->isDoubleTy())
10662 weight = CW_Register;
10665 if (type->isVectorTy())
10666 weight = CW_Register;
10669 weight = CW_Register;
10672 weight = CW_Memory;
10678 std::pair<unsigned, const TargetRegisterClass *>
10679 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10680 const std::string &Constraint,
10682 if (Constraint.size() == 1) {
10683 // GCC RS6000 Constraint Letters
10684 switch (Constraint[0]) {
10685 case 'b': // R1-R31
10686 if (VT == MVT::i64 && Subtarget.isPPC64())
10687 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10688 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10689 case 'r': // R0-R31
10690 if (VT == MVT::i64 && Subtarget.isPPC64())
10691 return std::make_pair(0U, &PPC::G8RCRegClass);
10692 return std::make_pair(0U, &PPC::GPRCRegClass);
10694 if (VT == MVT::f32 || VT == MVT::i32)
10695 return std::make_pair(0U, &PPC::F4RCRegClass);
10696 if (VT == MVT::f64 || VT == MVT::i64)
10697 return std::make_pair(0U, &PPC::F8RCRegClass);
10698 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10699 return std::make_pair(0U, &PPC::QFRCRegClass);
10700 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10701 return std::make_pair(0U, &PPC::QSRCRegClass);
10704 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10705 return std::make_pair(0U, &PPC::QFRCRegClass);
10706 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10707 return std::make_pair(0U, &PPC::QSRCRegClass);
10708 return std::make_pair(0U, &PPC::VRRCRegClass);
10710 return std::make_pair(0U, &PPC::CRRCRegClass);
10712 } else if (Constraint == "wc") { // an individual CR bit.
10713 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10714 } else if (Constraint == "wa" || Constraint == "wd" ||
10715 Constraint == "wf") {
10716 return std::make_pair(0U, &PPC::VSRCRegClass);
10717 } else if (Constraint == "ws") {
10718 if (VT == MVT::f32)
10719 return std::make_pair(0U, &PPC::VSSRCRegClass);
10721 return std::make_pair(0U, &PPC::VSFRCRegClass);
10724 std::pair<unsigned, const TargetRegisterClass *> R =
10725 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10727 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10728 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10729 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10731 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10732 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10733 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10734 PPC::GPRCRegClass.contains(R.first))
10735 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10736 PPC::sub_32, &PPC::G8RCRegClass),
10737 &PPC::G8RCRegClass);
10739 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10740 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10741 R.first = PPC::CR0;
10742 R.second = &PPC::CRRCRegClass;
10749 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10750 /// vector. If it is invalid, don't add anything to Ops.
10751 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10752 std::string &Constraint,
10753 std::vector<SDValue>&Ops,
10754 SelectionDAG &DAG) const {
10757 // Only support length 1 constraints.
10758 if (Constraint.length() > 1) return;
10760 char Letter = Constraint[0];
10771 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10772 if (!CST) return; // Must be an immediate to match.
10774 int64_t Value = CST->getSExtValue();
10775 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10776 // numbers are printed as such.
10778 default: llvm_unreachable("Unknown constraint letter!");
10779 case 'I': // "I" is a signed 16-bit constant.
10780 if (isInt<16>(Value))
10781 Result = DAG.getTargetConstant(Value, dl, TCVT);
10783 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
10784 if (isShiftedUInt<16, 16>(Value))
10785 Result = DAG.getTargetConstant(Value, dl, TCVT);
10787 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
10788 if (isShiftedInt<16, 16>(Value))
10789 Result = DAG.getTargetConstant(Value, dl, TCVT);
10791 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
10792 if (isUInt<16>(Value))
10793 Result = DAG.getTargetConstant(Value, dl, TCVT);
10795 case 'M': // "M" is a constant that is greater than 31.
10797 Result = DAG.getTargetConstant(Value, dl, TCVT);
10799 case 'N': // "N" is a positive constant that is an exact power of two.
10800 if (Value > 0 && isPowerOf2_64(Value))
10801 Result = DAG.getTargetConstant(Value, dl, TCVT);
10803 case 'O': // "O" is the constant zero.
10805 Result = DAG.getTargetConstant(Value, dl, TCVT);
10807 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
10808 if (isInt<16>(-Value))
10809 Result = DAG.getTargetConstant(Value, dl, TCVT);
10816 if (Result.getNode()) {
10817 Ops.push_back(Result);
10821 // Handle standard constraint letters.
10822 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10825 // isLegalAddressingMode - Return true if the addressing mode represented
10826 // by AM is legal for this target, for a load/store of the specified type.
10827 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10829 unsigned AS) const {
10830 // PPC does not allow r+i addressing modes for vectors!
10831 if (Ty->isVectorTy() && AM.BaseOffs != 0)
10834 // PPC allows a sign-extended 16-bit immediate field.
10835 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10838 // No global is ever allowed as a base.
10842 // PPC only support r+r,
10843 switch (AM.Scale) {
10844 case 0: // "r+i" or just "i", depending on HasBaseReg.
10847 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
10849 // Otherwise we have r+r or r+i.
10852 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
10854 // Allow 2*r as r+r.
10857 // No other scales are supported.
10864 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10865 SelectionDAG &DAG) const {
10866 MachineFunction &MF = DAG.getMachineFunction();
10867 MachineFrameInfo *MFI = MF.getFrameInfo();
10868 MFI->setReturnAddressIsTaken(true);
10870 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10874 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10876 // Make sure the function does not optimize away the store of the RA to
10878 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10879 FuncInfo->setLRStoreRequired();
10880 bool isPPC64 = Subtarget.isPPC64();
10883 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10885 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
10886 isPPC64 ? MVT::i64 : MVT::i32);
10887 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10888 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10889 FrameAddr, Offset),
10890 MachinePointerInfo(), false, false, false, 0);
10893 // Just load the return address off the stack.
10894 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10895 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10896 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10899 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10900 SelectionDAG &DAG) const {
10902 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10904 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10905 bool isPPC64 = PtrVT == MVT::i64;
10907 MachineFunction &MF = DAG.getMachineFunction();
10908 MachineFrameInfo *MFI = MF.getFrameInfo();
10909 MFI->setFrameAddressIsTaken(true);
10911 // Naked functions never have a frame pointer, and so we use r1. For all
10912 // other functions, this decision must be delayed until during PEI.
10914 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10915 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10917 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10919 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10922 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10923 FrameAddr, MachinePointerInfo(), false, false,
10928 // FIXME? Maybe this could be a TableGen attribute on some registers and
10929 // this table could be generated automatically from RegInfo.
10930 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10932 bool isPPC64 = Subtarget.isPPC64();
10933 bool isDarwinABI = Subtarget.isDarwinABI();
10935 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10936 (!isPPC64 && VT != MVT::i32))
10937 report_fatal_error("Invalid register global variable type");
10939 bool is64Bit = isPPC64 && VT == MVT::i64;
10940 unsigned Reg = StringSwitch<unsigned>(RegName)
10941 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10942 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10943 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10944 (is64Bit ? PPC::X13 : PPC::R13))
10949 report_fatal_error("Invalid register name global variable");
10953 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10954 // The PowerPC target isn't yet aware of offsets.
10958 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10960 unsigned Intrinsic) const {
10962 switch (Intrinsic) {
10963 case Intrinsic::ppc_qpx_qvlfd:
10964 case Intrinsic::ppc_qpx_qvlfs:
10965 case Intrinsic::ppc_qpx_qvlfcd:
10966 case Intrinsic::ppc_qpx_qvlfcs:
10967 case Intrinsic::ppc_qpx_qvlfiwa:
10968 case Intrinsic::ppc_qpx_qvlfiwz:
10969 case Intrinsic::ppc_altivec_lvx:
10970 case Intrinsic::ppc_altivec_lvxl:
10971 case Intrinsic::ppc_altivec_lvebx:
10972 case Intrinsic::ppc_altivec_lvehx:
10973 case Intrinsic::ppc_altivec_lvewx:
10974 case Intrinsic::ppc_vsx_lxvd2x:
10975 case Intrinsic::ppc_vsx_lxvw4x: {
10977 switch (Intrinsic) {
10978 case Intrinsic::ppc_altivec_lvebx:
10981 case Intrinsic::ppc_altivec_lvehx:
10984 case Intrinsic::ppc_altivec_lvewx:
10987 case Intrinsic::ppc_vsx_lxvd2x:
10990 case Intrinsic::ppc_qpx_qvlfd:
10993 case Intrinsic::ppc_qpx_qvlfs:
10996 case Intrinsic::ppc_qpx_qvlfcd:
10999 case Intrinsic::ppc_qpx_qvlfcs:
11007 Info.opc = ISD::INTRINSIC_W_CHAIN;
11009 Info.ptrVal = I.getArgOperand(0);
11010 Info.offset = -VT.getStoreSize()+1;
11011 Info.size = 2*VT.getStoreSize()-1;
11014 Info.readMem = true;
11015 Info.writeMem = false;
11018 case Intrinsic::ppc_qpx_qvlfda:
11019 case Intrinsic::ppc_qpx_qvlfsa:
11020 case Intrinsic::ppc_qpx_qvlfcda:
11021 case Intrinsic::ppc_qpx_qvlfcsa:
11022 case Intrinsic::ppc_qpx_qvlfiwaa:
11023 case Intrinsic::ppc_qpx_qvlfiwza: {
11025 switch (Intrinsic) {
11026 case Intrinsic::ppc_qpx_qvlfda:
11029 case Intrinsic::ppc_qpx_qvlfsa:
11032 case Intrinsic::ppc_qpx_qvlfcda:
11035 case Intrinsic::ppc_qpx_qvlfcsa:
11043 Info.opc = ISD::INTRINSIC_W_CHAIN;
11045 Info.ptrVal = I.getArgOperand(0);
11047 Info.size = VT.getStoreSize();
11050 Info.readMem = true;
11051 Info.writeMem = false;
11054 case Intrinsic::ppc_qpx_qvstfd:
11055 case Intrinsic::ppc_qpx_qvstfs:
11056 case Intrinsic::ppc_qpx_qvstfcd:
11057 case Intrinsic::ppc_qpx_qvstfcs:
11058 case Intrinsic::ppc_qpx_qvstfiw:
11059 case Intrinsic::ppc_altivec_stvx:
11060 case Intrinsic::ppc_altivec_stvxl:
11061 case Intrinsic::ppc_altivec_stvebx:
11062 case Intrinsic::ppc_altivec_stvehx:
11063 case Intrinsic::ppc_altivec_stvewx:
11064 case Intrinsic::ppc_vsx_stxvd2x:
11065 case Intrinsic::ppc_vsx_stxvw4x: {
11067 switch (Intrinsic) {
11068 case Intrinsic::ppc_altivec_stvebx:
11071 case Intrinsic::ppc_altivec_stvehx:
11074 case Intrinsic::ppc_altivec_stvewx:
11077 case Intrinsic::ppc_vsx_stxvd2x:
11080 case Intrinsic::ppc_qpx_qvstfd:
11083 case Intrinsic::ppc_qpx_qvstfs:
11086 case Intrinsic::ppc_qpx_qvstfcd:
11089 case Intrinsic::ppc_qpx_qvstfcs:
11097 Info.opc = ISD::INTRINSIC_VOID;
11099 Info.ptrVal = I.getArgOperand(1);
11100 Info.offset = -VT.getStoreSize()+1;
11101 Info.size = 2*VT.getStoreSize()-1;
11104 Info.readMem = false;
11105 Info.writeMem = true;
11108 case Intrinsic::ppc_qpx_qvstfda:
11109 case Intrinsic::ppc_qpx_qvstfsa:
11110 case Intrinsic::ppc_qpx_qvstfcda:
11111 case Intrinsic::ppc_qpx_qvstfcsa:
11112 case Intrinsic::ppc_qpx_qvstfiwa: {
11114 switch (Intrinsic) {
11115 case Intrinsic::ppc_qpx_qvstfda:
11118 case Intrinsic::ppc_qpx_qvstfsa:
11121 case Intrinsic::ppc_qpx_qvstfcda:
11124 case Intrinsic::ppc_qpx_qvstfcsa:
11132 Info.opc = ISD::INTRINSIC_VOID;
11134 Info.ptrVal = I.getArgOperand(1);
11136 Info.size = VT.getStoreSize();
11139 Info.readMem = false;
11140 Info.writeMem = true;
11150 /// getOptimalMemOpType - Returns the target specific optimal type for load
11151 /// and store operations as a result of memset, memcpy, and memmove
11152 /// lowering. If DstAlign is zero that means it's safe to destination
11153 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11154 /// means there isn't a need to check it against alignment requirement,
11155 /// probably because the source does not need to be loaded. If 'IsMemset' is
11156 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11157 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11158 /// source is constant so it does not need to be loaded.
11159 /// It returns EVT::Other if the type should be determined using generic
11160 /// target-independent logic.
11161 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11162 unsigned DstAlign, unsigned SrcAlign,
11163 bool IsMemset, bool ZeroMemset,
11165 MachineFunction &MF) const {
11166 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11167 const Function *F = MF.getFunction();
11168 // When expanding a memset, require at least two QPX instructions to cover
11169 // the cost of loading the value to be stored from the constant pool.
11170 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11171 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11172 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11176 // We should use Altivec/VSX loads and stores when available. For unaligned
11177 // addresses, unaligned VSX loads are only fast starting with the P8.
11178 if (Subtarget.hasAltivec() && Size >= 16 &&
11179 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11180 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11184 if (Subtarget.isPPC64()) {
11191 /// \brief Returns true if it is beneficial to convert a load of a constant
11192 /// to just the constant itself.
11193 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11195 assert(Ty->isIntegerTy());
11197 unsigned BitSize = Ty->getPrimitiveSizeInBits();
11198 if (BitSize == 0 || BitSize > 64)
11203 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11204 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11206 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11207 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11208 return NumBits1 == 64 && NumBits2 == 32;
11211 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11212 if (!VT1.isInteger() || !VT2.isInteger())
11214 unsigned NumBits1 = VT1.getSizeInBits();
11215 unsigned NumBits2 = VT2.getSizeInBits();
11216 return NumBits1 == 64 && NumBits2 == 32;
11219 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11220 // Generally speaking, zexts are not free, but they are free when they can be
11221 // folded with other operations.
11222 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11223 EVT MemVT = LD->getMemoryVT();
11224 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11225 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11226 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11227 LD->getExtensionType() == ISD::ZEXTLOAD))
11231 // FIXME: Add other cases...
11232 // - 32-bit shifts with a zext to i64
11233 // - zext after ctlz, bswap, etc.
11234 // - zext after and by a constant mask
11236 return TargetLowering::isZExtFree(Val, VT2);
11239 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11240 assert(VT.isFloatingPoint());
11244 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11245 return isInt<16>(Imm) || isUInt<16>(Imm);
11248 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11249 return isInt<16>(Imm) || isUInt<16>(Imm);
11252 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11255 bool *Fast) const {
11256 if (DisablePPCUnaligned)
11259 // PowerPC supports unaligned memory access for simple non-vector types.
11260 // Although accessing unaligned addresses is not as efficient as accessing
11261 // aligned addresses, it is generally more efficient than manual expansion,
11262 // and generally only traps for software emulation when crossing page
11265 if (!VT.isSimple())
11268 if (VT.getSimpleVT().isVector()) {
11269 if (Subtarget.hasVSX()) {
11270 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11271 VT != MVT::v4f32 && VT != MVT::v4i32)
11278 if (VT == MVT::ppcf128)
11287 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11288 VT = VT.getScalarType();
11290 if (!VT.isSimple())
11293 switch (VT.getSimpleVT().SimpleTy) {
11305 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11306 // LR is a callee-save register, but we must treat it as clobbered by any call
11307 // site. Hence we include LR in the scratch registers, which are in turn added
11308 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11309 // to CTR, which is used by any indirect call.
11310 static const MCPhysReg ScratchRegs[] = {
11311 PPC::X12, PPC::LR8, PPC::CTR8, 0
11314 return ScratchRegs;
11318 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11319 EVT VT , unsigned DefinedValues) const {
11320 if (VT == MVT::v2i64)
11323 if (Subtarget.hasQPX()) {
11324 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11328 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11331 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11332 if (DisableILPPref || Subtarget.enableMachineScheduler())
11333 return TargetLowering::getSchedulingPreference(N);
11338 // Create a fast isel object.
11340 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11341 const TargetLibraryInfo *LibInfo) const {
11342 return PPC::createFastISel(FuncInfo, LibInfo);