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 "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
40 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
41 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
43 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
44 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
46 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
47 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
49 // FIXME: Remove this once the bug has been fixed!
50 extern cl::opt<bool> ANDIGlueBug;
52 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
53 if (TM.getSubtargetImpl()->isDarwin())
54 return new TargetLoweringObjectFileMachO();
56 if (TM.getSubtargetImpl()->isSVR4ABI())
57 return new PPC64LinuxTargetObjectFile();
59 return new TargetLoweringObjectFileELF();
62 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
63 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
64 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
68 // Use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(true);
72 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73 // arguments are at least 4/8 bytes aligned.
74 bool isPPC64 = Subtarget->isPPC64();
75 setMinStackArgumentAlignment(isPPC64 ? 8:4);
77 // Set up the register classes.
78 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
82 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
86 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88 // PowerPC has pre-inc load and store's.
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, 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);
100 if (Subtarget->useCRBits()) {
101 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
104 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
105 isPPC64 ? MVT::i64 : MVT::i32);
106 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
107 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
108 isPPC64 ? MVT::i64 : MVT::i32);
110 // PowerPC does not support direct load / store of condition registers
111 setOperationAction(ISD::LOAD, MVT::i1, Custom);
112 setOperationAction(ISD::STORE, MVT::i1, Custom);
114 // FIXME: Remove this once the ANDI glue bug is fixed:
116 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
118 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
120 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
121 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
122 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
123 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
125 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
128 // This is used in the ppcf128->int sequence. Note it has different semantics
129 // from FP_ROUND: that rounds to nearest, this rounds to zero.
130 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
132 // We do not currently implement these libm ops for PowerPC.
133 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
134 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
140 // PowerPC has no SREM/UREM instructions
141 setOperationAction(ISD::SREM, MVT::i32, Expand);
142 setOperationAction(ISD::UREM, MVT::i32, Expand);
143 setOperationAction(ISD::SREM, MVT::i64, Expand);
144 setOperationAction(ISD::UREM, MVT::i64, Expand);
146 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
147 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
148 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
149 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
150 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
151 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
152 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
153 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
154 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
156 // We don't support sin/cos/sqrt/fmod/pow
157 setOperationAction(ISD::FSIN , MVT::f64, Expand);
158 setOperationAction(ISD::FCOS , MVT::f64, Expand);
159 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
160 setOperationAction(ISD::FREM , MVT::f64, Expand);
161 setOperationAction(ISD::FPOW , MVT::f64, Expand);
162 setOperationAction(ISD::FMA , MVT::f64, Legal);
163 setOperationAction(ISD::FSIN , MVT::f32, Expand);
164 setOperationAction(ISD::FCOS , MVT::f32, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
166 setOperationAction(ISD::FREM , MVT::f32, Expand);
167 setOperationAction(ISD::FPOW , MVT::f32, Expand);
168 setOperationAction(ISD::FMA , MVT::f32, Legal);
170 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
172 // If we're enabling GP optimizations, use hardware square root
173 if (!Subtarget->hasFSQRT() &&
174 !(TM.Options.UnsafeFPMath &&
175 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
176 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
178 if (!Subtarget->hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
181 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
183 if (Subtarget->hasFCPSGN()) {
184 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
185 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
191 if (Subtarget->hasFPRND()) {
192 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
193 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
194 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
195 setOperationAction(ISD::FROUND, MVT::f64, Legal);
197 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
200 setOperationAction(ISD::FROUND, MVT::f32, Legal);
203 // PowerPC does not have BSWAP, CTPOP or CTTZ
204 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
205 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
206 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
207 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
208 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
209 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
210 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
211 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
213 if (Subtarget->hasPOPCNTD()) {
214 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
215 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
217 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
218 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
221 // PowerPC does not have ROTR
222 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
223 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
225 if (!Subtarget->useCRBits()) {
226 // PowerPC does not have Select
227 setOperationAction(ISD::SELECT, MVT::i32, Expand);
228 setOperationAction(ISD::SELECT, MVT::i64, Expand);
229 setOperationAction(ISD::SELECT, MVT::f32, Expand);
230 setOperationAction(ISD::SELECT, MVT::f64, Expand);
233 // PowerPC wants to turn select_cc of FP into fsel when possible.
234 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
235 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
237 // PowerPC wants to optimize integer setcc a bit
238 if (!Subtarget->useCRBits())
239 setOperationAction(ISD::SETCC, MVT::i32, Custom);
241 // PowerPC does not have BRCOND which requires SetCC
242 if (!Subtarget->useCRBits())
243 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
245 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
247 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 // PowerPC does not have [U|S]INT_TO_FP
251 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
252 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
254 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
256 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
257 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
259 // We cannot sextinreg(i1). Expand to shifts.
260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
262 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
263 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
264 // support continuation, user-level threading, and etc.. As a result, no
265 // other SjLj exception interfaces are implemented and please don't build
266 // your own exception handling based on them.
267 // LLVM/Clang supports zero-cost DWARF exception handling.
268 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
269 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
271 // We want to legalize GlobalAddress and ConstantPool nodes into the
272 // appropriate instructions to materialize the address.
273 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
274 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
275 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
276 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
277 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
278 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
285 setOperationAction(ISD::TRAP, MVT::Other, Legal);
287 // TRAMPOLINE is custom lowered.
288 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
289 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
291 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
292 setOperationAction(ISD::VASTART , MVT::Other, Custom);
294 if (Subtarget->isSVR4ABI()) {
296 // VAARG always uses double-word chunks, so promote anything smaller.
297 setOperationAction(ISD::VAARG, MVT::i1, Promote);
298 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
299 setOperationAction(ISD::VAARG, MVT::i8, Promote);
300 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
301 setOperationAction(ISD::VAARG, MVT::i16, Promote);
302 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
303 setOperationAction(ISD::VAARG, MVT::i32, Promote);
304 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
305 setOperationAction(ISD::VAARG, MVT::Other, Expand);
307 // VAARG is custom lowered with the 32-bit SVR4 ABI.
308 setOperationAction(ISD::VAARG, MVT::Other, Custom);
309 setOperationAction(ISD::VAARG, MVT::i64, Custom);
312 setOperationAction(ISD::VAARG, MVT::Other, Expand);
314 if (Subtarget->isSVR4ABI() && !isPPC64)
315 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
316 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
318 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
320 // Use the default implementation.
321 setOperationAction(ISD::VAEND , MVT::Other, Expand);
322 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
323 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
327 // We want to custom lower some of our intrinsics.
328 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
330 // To handle counter-based loop conditions.
331 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
333 // Comparisons that require checking two conditions.
334 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
335 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
336 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
337 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
338 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
339 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
340 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
341 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
342 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
347 if (Subtarget->has64BitSupport()) {
348 // They also have instructions for converting between i64 and fp.
349 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
351 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
352 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
353 // This is just the low 32 bits of a (signed) fp->i64 conversion.
354 // We cannot do this with Promote because i64 is not a legal type.
355 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
357 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
358 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
360 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
364 // With the instructions enabled under FPCVT, we can do everything.
365 if (PPCSubTarget.hasFPCVT()) {
366 if (Subtarget->has64BitSupport()) {
367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
368 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
369 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
370 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
374 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
375 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
376 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
379 if (Subtarget->use64BitRegs()) {
380 // 64-bit PowerPC implementations can support i64 types directly
381 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
382 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
383 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
384 // 64-bit PowerPC wants to expand i128 shifts itself.
385 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
386 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
387 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
389 // 32-bit PowerPC wants to expand i64 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
395 if (Subtarget->hasAltivec()) {
396 // First set operation action for all vector types to expand. Then we
397 // will selectively turn on ones that can be effectively codegen'd.
398 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
399 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
400 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
402 // add/sub are legal for all supported vector VT's.
403 setOperationAction(ISD::ADD , VT, Legal);
404 setOperationAction(ISD::SUB , VT, Legal);
406 // We promote all shuffles to v16i8.
407 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
408 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
410 // We promote all non-typed operations to v4i32.
411 setOperationAction(ISD::AND , VT, Promote);
412 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
413 setOperationAction(ISD::OR , VT, Promote);
414 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
415 setOperationAction(ISD::XOR , VT, Promote);
416 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
417 setOperationAction(ISD::LOAD , VT, Promote);
418 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
419 setOperationAction(ISD::SELECT, VT, Promote);
420 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
421 setOperationAction(ISD::STORE, VT, Promote);
422 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
424 // No other operations are legal.
425 setOperationAction(ISD::MUL , VT, Expand);
426 setOperationAction(ISD::SDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UDIV, VT, Expand);
429 setOperationAction(ISD::UREM, VT, Expand);
430 setOperationAction(ISD::FDIV, VT, Expand);
431 setOperationAction(ISD::FREM, VT, Expand);
432 setOperationAction(ISD::FNEG, VT, Expand);
433 setOperationAction(ISD::FSQRT, VT, Expand);
434 setOperationAction(ISD::FLOG, VT, Expand);
435 setOperationAction(ISD::FLOG10, VT, Expand);
436 setOperationAction(ISD::FLOG2, VT, Expand);
437 setOperationAction(ISD::FEXP, VT, Expand);
438 setOperationAction(ISD::FEXP2, VT, Expand);
439 setOperationAction(ISD::FSIN, VT, Expand);
440 setOperationAction(ISD::FCOS, VT, Expand);
441 setOperationAction(ISD::FABS, VT, Expand);
442 setOperationAction(ISD::FPOWI, VT, Expand);
443 setOperationAction(ISD::FFLOOR, VT, Expand);
444 setOperationAction(ISD::FCEIL, VT, Expand);
445 setOperationAction(ISD::FTRUNC, VT, Expand);
446 setOperationAction(ISD::FRINT, VT, Expand);
447 setOperationAction(ISD::FNEARBYINT, VT, Expand);
448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
449 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
450 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
451 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
452 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
453 setOperationAction(ISD::UDIVREM, VT, Expand);
454 setOperationAction(ISD::SDIVREM, VT, Expand);
455 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
456 setOperationAction(ISD::FPOW, VT, Expand);
457 setOperationAction(ISD::CTPOP, VT, Expand);
458 setOperationAction(ISD::CTLZ, VT, Expand);
459 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
460 setOperationAction(ISD::CTTZ, VT, Expand);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
462 setOperationAction(ISD::VSELECT, VT, Expand);
463 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
465 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
466 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
467 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
468 setTruncStoreAction(VT, InnerVT, Expand);
470 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
471 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
472 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
475 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
476 // with merges, splats, etc.
477 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
479 setOperationAction(ISD::AND , MVT::v4i32, Legal);
480 setOperationAction(ISD::OR , MVT::v4i32, Legal);
481 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
482 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
483 setOperationAction(ISD::SELECT, MVT::v4i32,
484 Subtarget->useCRBits() ? Legal : Expand);
485 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
486 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
487 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
488 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
489 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
490 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
491 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
492 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
493 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
495 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
496 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
497 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
498 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
500 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
501 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
503 if (TM.Options.UnsafeFPMath) {
504 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
505 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
508 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
509 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
510 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
512 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
513 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
515 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
516 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
517 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
518 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
520 // Altivec does not contain unordered floating-point compare instructions
521 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
522 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
523 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
524 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
525 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
526 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
532 if (Subtarget->has64BitSupport()) {
533 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
534 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
537 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
538 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
539 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
540 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
542 setBooleanContents(ZeroOrOneBooleanContent);
543 // Altivec instructions set fields to all zeros or all ones.
544 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
547 setStackPointerRegisterToSaveRestore(PPC::X1);
548 setExceptionPointerRegister(PPC::X3);
549 setExceptionSelectorRegister(PPC::X4);
551 setStackPointerRegisterToSaveRestore(PPC::R1);
552 setExceptionPointerRegister(PPC::R3);
553 setExceptionSelectorRegister(PPC::R4);
556 // We have target-specific dag combine patterns for the following nodes:
557 setTargetDAGCombine(ISD::SINT_TO_FP);
558 setTargetDAGCombine(ISD::LOAD);
559 setTargetDAGCombine(ISD::STORE);
560 setTargetDAGCombine(ISD::BR_CC);
561 if (Subtarget->useCRBits())
562 setTargetDAGCombine(ISD::BRCOND);
563 setTargetDAGCombine(ISD::BSWAP);
564 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
566 setTargetDAGCombine(ISD::SIGN_EXTEND);
567 setTargetDAGCombine(ISD::ZERO_EXTEND);
568 setTargetDAGCombine(ISD::ANY_EXTEND);
570 if (Subtarget->useCRBits()) {
571 setTargetDAGCombine(ISD::TRUNCATE);
572 setTargetDAGCombine(ISD::SETCC);
573 setTargetDAGCombine(ISD::SELECT_CC);
576 // Use reciprocal estimates.
577 if (TM.Options.UnsafeFPMath) {
578 setTargetDAGCombine(ISD::FDIV);
579 setTargetDAGCombine(ISD::FSQRT);
582 // Darwin long double math library functions have $LDBL128 appended.
583 if (Subtarget->isDarwin()) {
584 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
585 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
586 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
587 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
588 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
589 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
590 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
591 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
592 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
593 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
596 // With 32 condition bits, we don't need to sink (and duplicate) compares
597 // aggressively in CodeGenPrep.
598 if (Subtarget->useCRBits())
599 setHasMultipleConditionRegisters();
601 setMinFunctionAlignment(2);
602 if (PPCSubTarget.isDarwin())
603 setPrefFunctionAlignment(4);
605 if (isPPC64 && Subtarget->isJITCodeModel())
606 // Temporary workaround for the inability of PPC64 JIT to handle jump
608 setSupportJumpTables(false);
610 setInsertFencesForAtomic(true);
612 if (Subtarget->enableMachineScheduler())
613 setSchedulingPreference(Sched::Source);
615 setSchedulingPreference(Sched::Hybrid);
617 computeRegisterProperties();
619 // The Freescale cores does better with aggressive inlining of memcpy and
620 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
621 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
622 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
623 MaxStoresPerMemset = 32;
624 MaxStoresPerMemsetOptSize = 16;
625 MaxStoresPerMemcpy = 32;
626 MaxStoresPerMemcpyOptSize = 8;
627 MaxStoresPerMemmove = 32;
628 MaxStoresPerMemmoveOptSize = 8;
630 setPrefFunctionAlignment(4);
634 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
635 /// the desired ByVal argument alignment.
636 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
637 unsigned MaxMaxAlign) {
638 if (MaxAlign == MaxMaxAlign)
640 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
641 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
643 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
645 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
646 unsigned EltAlign = 0;
647 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
648 if (EltAlign > MaxAlign)
650 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
651 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
652 unsigned EltAlign = 0;
653 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
654 if (EltAlign > MaxAlign)
656 if (MaxAlign == MaxMaxAlign)
662 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
663 /// function arguments in the caller parameter area.
664 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
665 // Darwin passes everything on 4 byte boundary.
666 if (PPCSubTarget.isDarwin())
669 // 16byte and wider vectors are passed on 16byte boundary.
670 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
671 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
672 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
673 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
677 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
680 case PPCISD::FSEL: return "PPCISD::FSEL";
681 case PPCISD::FCFID: return "PPCISD::FCFID";
682 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
683 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
684 case PPCISD::FRE: return "PPCISD::FRE";
685 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
686 case PPCISD::STFIWX: return "PPCISD::STFIWX";
687 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
688 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
689 case PPCISD::VPERM: return "PPCISD::VPERM";
690 case PPCISD::Hi: return "PPCISD::Hi";
691 case PPCISD::Lo: return "PPCISD::Lo";
692 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
693 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
694 case PPCISD::LOAD: return "PPCISD::LOAD";
695 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
696 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
697 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
698 case PPCISD::SRL: return "PPCISD::SRL";
699 case PPCISD::SRA: return "PPCISD::SRA";
700 case PPCISD::SHL: return "PPCISD::SHL";
701 case PPCISD::CALL: return "PPCISD::CALL";
702 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
703 case PPCISD::MTCTR: return "PPCISD::MTCTR";
704 case PPCISD::BCTRL: return "PPCISD::BCTRL";
705 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
706 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
707 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
708 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
709 case PPCISD::VCMP: return "PPCISD::VCMP";
710 case PPCISD::VCMPo: return "PPCISD::VCMPo";
711 case PPCISD::LBRX: return "PPCISD::LBRX";
712 case PPCISD::STBRX: return "PPCISD::STBRX";
713 case PPCISD::LARX: return "PPCISD::LARX";
714 case PPCISD::STCX: return "PPCISD::STCX";
715 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
716 case PPCISD::BDNZ: return "PPCISD::BDNZ";
717 case PPCISD::BDZ: return "PPCISD::BDZ";
718 case PPCISD::MFFS: return "PPCISD::MFFS";
719 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
720 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
721 case PPCISD::CR6SET: return "PPCISD::CR6SET";
722 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
723 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
724 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
725 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
726 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
727 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
728 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
729 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
730 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
731 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
732 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
733 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
734 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
735 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
736 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
737 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
738 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
739 case PPCISD::SC: return "PPCISD::SC";
743 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
745 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
746 return VT.changeVectorElementTypeToInteger();
749 //===----------------------------------------------------------------------===//
750 // Node matching predicates, for use by the tblgen matching code.
751 //===----------------------------------------------------------------------===//
753 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
754 static bool isFloatingPointZero(SDValue Op) {
755 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
756 return CFP->getValueAPF().isZero();
757 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
758 // Maybe this has already been legalized into the constant pool?
759 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
760 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
761 return CFP->getValueAPF().isZero();
766 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
767 /// true if Op is undef or if it matches the specified value.
768 static bool isConstantOrUndef(int Op, int Val) {
769 return Op < 0 || Op == Val;
772 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
773 /// VPKUHUM instruction.
774 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
776 for (unsigned i = 0; i != 16; ++i)
777 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
780 for (unsigned i = 0; i != 8; ++i)
781 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
782 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
788 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
789 /// VPKUWUM instruction.
790 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
792 for (unsigned i = 0; i != 16; i += 2)
793 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
794 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
797 for (unsigned i = 0; i != 8; i += 2)
798 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
799 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
800 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
801 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
807 /// isVMerge - Common function, used to match vmrg* shuffles.
809 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
810 unsigned LHSStart, unsigned RHSStart) {
811 assert(N->getValueType(0) == MVT::v16i8 &&
812 "PPC only supports shuffles by bytes!");
813 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
814 "Unsupported merge size!");
816 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
817 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
818 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
819 LHSStart+j+i*UnitSize) ||
820 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
821 RHSStart+j+i*UnitSize))
827 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
828 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
829 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
832 return isVMerge(N, UnitSize, 8, 24);
833 return isVMerge(N, UnitSize, 8, 8);
836 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
837 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
838 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
841 return isVMerge(N, UnitSize, 0, 16);
842 return isVMerge(N, UnitSize, 0, 0);
846 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
847 /// amount, otherwise return -1.
848 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
849 assert(N->getValueType(0) == MVT::v16i8 &&
850 "PPC only supports shuffles by bytes!");
852 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
854 // Find the first non-undef value in the shuffle mask.
856 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
859 if (i == 16) return -1; // all undef.
861 // Otherwise, check to see if the rest of the elements are consecutively
862 // numbered from this value.
863 unsigned ShiftAmt = SVOp->getMaskElt(i);
864 if (ShiftAmt < i) return -1;
868 // Check the rest of the elements to see if they are consecutive.
869 for (++i; i != 16; ++i)
870 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
873 // Check the rest of the elements to see if they are consecutive.
874 for (++i; i != 16; ++i)
875 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
881 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
882 /// specifies a splat of a single element that is suitable for input to
883 /// VSPLTB/VSPLTH/VSPLTW.
884 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
885 assert(N->getValueType(0) == MVT::v16i8 &&
886 (EltSize == 1 || EltSize == 2 || EltSize == 4));
888 // This is a splat operation if each element of the permute is the same, and
889 // if the value doesn't reference the second vector.
890 unsigned ElementBase = N->getMaskElt(0);
892 // FIXME: Handle UNDEF elements too!
893 if (ElementBase >= 16)
896 // Check that the indices are consecutive, in the case of a multi-byte element
897 // splatted with a v16i8 mask.
898 for (unsigned i = 1; i != EltSize; ++i)
899 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
902 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
903 if (N->getMaskElt(i) < 0) continue;
904 for (unsigned j = 0; j != EltSize; ++j)
905 if (N->getMaskElt(i+j) != N->getMaskElt(j))
911 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
913 bool PPC::isAllNegativeZeroVector(SDNode *N) {
914 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
916 APInt APVal, APUndef;
920 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
921 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
922 return CFP->getValueAPF().isNegZero();
927 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
928 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
929 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
930 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
931 assert(isSplatShuffleMask(SVOp, EltSize));
932 return SVOp->getMaskElt(0) / EltSize;
935 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
936 /// by using a vspltis[bhw] instruction of the specified element size, return
937 /// the constant being splatted. The ByteSize field indicates the number of
938 /// bytes of each element [124] -> [bhw].
939 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
942 // If ByteSize of the splat is bigger than the element size of the
943 // build_vector, then we have a case where we are checking for a splat where
944 // multiple elements of the buildvector are folded together into a single
945 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
946 unsigned EltSize = 16/N->getNumOperands();
947 if (EltSize < ByteSize) {
948 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
949 SDValue UniquedVals[4];
950 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
952 // See if all of the elements in the buildvector agree across.
953 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
954 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
955 // If the element isn't a constant, bail fully out.
956 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
959 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
960 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
961 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
962 return SDValue(); // no match.
965 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
966 // either constant or undef values that are identical for each chunk. See
967 // if these chunks can form into a larger vspltis*.
969 // Check to see if all of the leading entries are either 0 or -1. If
970 // neither, then this won't fit into the immediate field.
971 bool LeadingZero = true;
972 bool LeadingOnes = true;
973 for (unsigned i = 0; i != Multiple-1; ++i) {
974 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
976 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
977 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
979 // Finally, check the least significant entry.
981 if (UniquedVals[Multiple-1].getNode() == 0)
982 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
983 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
985 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
988 if (UniquedVals[Multiple-1].getNode() == 0)
989 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
990 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
991 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
992 return DAG.getTargetConstant(Val, MVT::i32);
998 // Check to see if this buildvec has a single non-undef value in its elements.
999 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1000 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1001 if (OpVal.getNode() == 0)
1002 OpVal = N->getOperand(i);
1003 else if (OpVal != N->getOperand(i))
1007 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
1009 unsigned ValSizeInBytes = EltSize;
1011 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1012 Value = CN->getZExtValue();
1013 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1014 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1015 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1018 // If the splat value is larger than the element value, then we can never do
1019 // this splat. The only case that we could fit the replicated bits into our
1020 // immediate field for would be zero, and we prefer to use vxor for it.
1021 if (ValSizeInBytes < ByteSize) return SDValue();
1023 // If the element value is larger than the splat value, cut it in half and
1024 // check to see if the two halves are equal. Continue doing this until we
1025 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1026 while (ValSizeInBytes > ByteSize) {
1027 ValSizeInBytes >>= 1;
1029 // If the top half equals the bottom half, we're still ok.
1030 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1031 (Value & ((1 << (8*ValSizeInBytes))-1)))
1035 // Properly sign extend the value.
1036 int MaskVal = SignExtend32(Value, ByteSize * 8);
1038 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1039 if (MaskVal == 0) return SDValue();
1041 // Finally, if this value fits in a 5 bit sext field, return it
1042 if (SignExtend32<5>(MaskVal) == MaskVal)
1043 return DAG.getTargetConstant(MaskVal, MVT::i32);
1047 //===----------------------------------------------------------------------===//
1048 // Addressing Mode Selection
1049 //===----------------------------------------------------------------------===//
1051 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1052 /// or 64-bit immediate, and if the value can be accurately represented as a
1053 /// sign extension from a 16-bit value. If so, this returns true and the
1055 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1056 if (N->getOpcode() != ISD::Constant)
1059 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1060 if (N->getValueType(0) == MVT::i32)
1061 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1063 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1065 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1066 return isIntS16Immediate(Op.getNode(), Imm);
1070 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1071 /// can be represented as an indexed [r+r] operation. Returns false if it
1072 /// can be more efficiently represented with [r+imm].
1073 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1075 SelectionDAG &DAG) const {
1077 if (N.getOpcode() == ISD::ADD) {
1078 if (isIntS16Immediate(N.getOperand(1), imm))
1079 return false; // r+i
1080 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1081 return false; // r+i
1083 Base = N.getOperand(0);
1084 Index = N.getOperand(1);
1086 } else if (N.getOpcode() == ISD::OR) {
1087 if (isIntS16Immediate(N.getOperand(1), imm))
1088 return false; // r+i can fold it if we can.
1090 // If this is an or of disjoint bitfields, we can codegen this as an add
1091 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1093 APInt LHSKnownZero, LHSKnownOne;
1094 APInt RHSKnownZero, RHSKnownOne;
1095 DAG.ComputeMaskedBits(N.getOperand(0),
1096 LHSKnownZero, LHSKnownOne);
1098 if (LHSKnownZero.getBoolValue()) {
1099 DAG.ComputeMaskedBits(N.getOperand(1),
1100 RHSKnownZero, RHSKnownOne);
1101 // If all of the bits are known zero on the LHS or RHS, the add won't
1103 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1104 Base = N.getOperand(0);
1105 Index = N.getOperand(1);
1114 // If we happen to be doing an i64 load or store into a stack slot that has
1115 // less than a 4-byte alignment, then the frame-index elimination may need to
1116 // use an indexed load or store instruction (because the offset may not be a
1117 // multiple of 4). The extra register needed to hold the offset comes from the
1118 // register scavenger, and it is possible that the scavenger will need to use
1119 // an emergency spill slot. As a result, we need to make sure that a spill slot
1120 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1122 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1123 // FIXME: This does not handle the LWA case.
1127 // NOTE: We'll exclude negative FIs here, which come from argument
1128 // lowering, because there are no known test cases triggering this problem
1129 // using packed structures (or similar). We can remove this exclusion if
1130 // we find such a test case. The reason why this is so test-case driven is
1131 // because this entire 'fixup' is only to prevent crashes (from the
1132 // register scavenger) on not-really-valid inputs. For example, if we have:
1134 // %b = bitcast i1* %a to i64*
1135 // store i64* a, i64 b
1136 // then the store should really be marked as 'align 1', but is not. If it
1137 // were marked as 'align 1' then the indexed form would have been
1138 // instruction-selected initially, and the problem this 'fixup' is preventing
1139 // won't happen regardless.
1143 MachineFunction &MF = DAG.getMachineFunction();
1144 MachineFrameInfo *MFI = MF.getFrameInfo();
1146 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1150 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1151 FuncInfo->setHasNonRISpills();
1154 /// Returns true if the address N can be represented by a base register plus
1155 /// a signed 16-bit displacement [r+imm], and if it is not better
1156 /// represented as reg+reg. If Aligned is true, only accept displacements
1157 /// suitable for STD and friends, i.e. multiples of 4.
1158 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1161 bool Aligned) const {
1162 // FIXME dl should come from parent load or store, not from address
1164 // If this can be more profitably realized as r+r, fail.
1165 if (SelectAddressRegReg(N, Disp, Base, DAG))
1168 if (N.getOpcode() == ISD::ADD) {
1170 if (isIntS16Immediate(N.getOperand(1), imm) &&
1171 (!Aligned || (imm & 3) == 0)) {
1172 Disp = DAG.getTargetConstant(imm, N.getValueType());
1173 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1174 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1175 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1177 Base = N.getOperand(0);
1179 return true; // [r+i]
1180 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1181 // Match LOAD (ADD (X, Lo(G))).
1182 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1183 && "Cannot handle constant offsets yet!");
1184 Disp = N.getOperand(1).getOperand(0); // The global address.
1185 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1186 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1187 Disp.getOpcode() == ISD::TargetConstantPool ||
1188 Disp.getOpcode() == ISD::TargetJumpTable);
1189 Base = N.getOperand(0);
1190 return true; // [&g+r]
1192 } else if (N.getOpcode() == ISD::OR) {
1194 if (isIntS16Immediate(N.getOperand(1), imm) &&
1195 (!Aligned || (imm & 3) == 0)) {
1196 // If this is an or of disjoint bitfields, we can codegen this as an add
1197 // (for better address arithmetic) if the LHS and RHS of the OR are
1198 // provably disjoint.
1199 APInt LHSKnownZero, LHSKnownOne;
1200 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1202 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1203 // If all of the bits are known zero on the LHS or RHS, the add won't
1205 Base = N.getOperand(0);
1206 Disp = DAG.getTargetConstant(imm, N.getValueType());
1210 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1211 // Loading from a constant address.
1213 // If this address fits entirely in a 16-bit sext immediate field, codegen
1216 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1217 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1218 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1219 CN->getValueType(0));
1223 // Handle 32-bit sext immediates with LIS + addr mode.
1224 if ((CN->getValueType(0) == MVT::i32 ||
1225 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1226 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1227 int Addr = (int)CN->getZExtValue();
1229 // Otherwise, break this down into an LIS + disp.
1230 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1232 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1233 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1234 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1239 Disp = DAG.getTargetConstant(0, getPointerTy());
1240 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1241 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1242 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1245 return true; // [r+0]
1248 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1249 /// represented as an indexed [r+r] operation.
1250 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1252 SelectionDAG &DAG) const {
1253 // Check to see if we can easily represent this as an [r+r] address. This
1254 // will fail if it thinks that the address is more profitably represented as
1255 // reg+imm, e.g. where imm = 0.
1256 if (SelectAddressRegReg(N, Base, Index, DAG))
1259 // If the operand is an addition, always emit this as [r+r], since this is
1260 // better (for code size, and execution, as the memop does the add for free)
1261 // than emitting an explicit add.
1262 if (N.getOpcode() == ISD::ADD) {
1263 Base = N.getOperand(0);
1264 Index = N.getOperand(1);
1268 // Otherwise, do it the hard way, using R0 as the base register.
1269 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1275 /// getPreIndexedAddressParts - returns true by value, base pointer and
1276 /// offset pointer and addressing mode by reference if the node's address
1277 /// can be legally represented as pre-indexed load / store address.
1278 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1280 ISD::MemIndexedMode &AM,
1281 SelectionDAG &DAG) const {
1282 if (DisablePPCPreinc) return false;
1288 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1289 Ptr = LD->getBasePtr();
1290 VT = LD->getMemoryVT();
1291 Alignment = LD->getAlignment();
1292 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1293 Ptr = ST->getBasePtr();
1294 VT = ST->getMemoryVT();
1295 Alignment = ST->getAlignment();
1300 // PowerPC doesn't have preinc load/store instructions for vectors.
1304 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1306 // Common code will reject creating a pre-inc form if the base pointer
1307 // is a frame index, or if N is a store and the base pointer is either
1308 // the same as or a predecessor of the value being stored. Check for
1309 // those situations here, and try with swapped Base/Offset instead.
1312 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1315 SDValue Val = cast<StoreSDNode>(N)->getValue();
1316 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1321 std::swap(Base, Offset);
1327 // LDU/STU can only handle immediates that are a multiple of 4.
1328 if (VT != MVT::i64) {
1329 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1332 // LDU/STU need an address with at least 4-byte alignment.
1336 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1340 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1341 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1342 // sext i32 to i64 when addr mode is r+i.
1343 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1344 LD->getExtensionType() == ISD::SEXTLOAD &&
1345 isa<ConstantSDNode>(Offset))
1353 //===----------------------------------------------------------------------===//
1354 // LowerOperation implementation
1355 //===----------------------------------------------------------------------===//
1357 /// GetLabelAccessInfo - Return true if we should reference labels using a
1358 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1359 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1360 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1361 HiOpFlags = PPCII::MO_HA;
1362 LoOpFlags = PPCII::MO_LO;
1364 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1365 // non-darwin platform. We don't support PIC on other platforms yet.
1366 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1367 TM.getSubtarget<PPCSubtarget>().isDarwin();
1369 HiOpFlags |= PPCII::MO_PIC_FLAG;
1370 LoOpFlags |= PPCII::MO_PIC_FLAG;
1373 // If this is a reference to a global value that requires a non-lazy-ptr, make
1374 // sure that instruction lowering adds it.
1375 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1376 HiOpFlags |= PPCII::MO_NLP_FLAG;
1377 LoOpFlags |= PPCII::MO_NLP_FLAG;
1379 if (GV->hasHiddenVisibility()) {
1380 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1381 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1388 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1389 SelectionDAG &DAG) {
1390 EVT PtrVT = HiPart.getValueType();
1391 SDValue Zero = DAG.getConstant(0, PtrVT);
1394 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1395 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1397 // With PIC, the first instruction is actually "GR+hi(&G)".
1399 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1400 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1402 // Generate non-pic code that has direct accesses to the constant pool.
1403 // The address of the global is just (hi(&g)+lo(&g)).
1404 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1407 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1408 SelectionDAG &DAG) const {
1409 EVT PtrVT = Op.getValueType();
1410 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1411 const Constant *C = CP->getConstVal();
1413 // 64-bit SVR4 ABI code is always position-independent.
1414 // The actual address of the GlobalValue is stored in the TOC.
1415 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1416 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1417 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1418 DAG.getRegister(PPC::X2, MVT::i64));
1421 unsigned MOHiFlag, MOLoFlag;
1422 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1424 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1426 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1427 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1430 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1431 EVT PtrVT = Op.getValueType();
1432 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1434 // 64-bit SVR4 ABI code is always position-independent.
1435 // The actual address of the GlobalValue is stored in the TOC.
1436 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1437 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1438 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1439 DAG.getRegister(PPC::X2, MVT::i64));
1442 unsigned MOHiFlag, MOLoFlag;
1443 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1444 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1445 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1446 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1449 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1450 SelectionDAG &DAG) const {
1451 EVT PtrVT = Op.getValueType();
1453 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1455 unsigned MOHiFlag, MOLoFlag;
1456 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1457 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1458 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1459 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1462 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1463 SelectionDAG &DAG) const {
1465 // FIXME: TLS addresses currently use medium model code sequences,
1466 // which is the most useful form. Eventually support for small and
1467 // large models could be added if users need it, at the cost of
1468 // additional complexity.
1469 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1471 const GlobalValue *GV = GA->getGlobal();
1472 EVT PtrVT = getPointerTy();
1473 bool is64bit = PPCSubTarget.isPPC64();
1475 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1477 if (Model == TLSModel::LocalExec) {
1478 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1479 PPCII::MO_TPREL_HA);
1480 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1481 PPCII::MO_TPREL_LO);
1482 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1483 is64bit ? MVT::i64 : MVT::i32);
1484 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1485 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1488 if (Model == TLSModel::InitialExec) {
1489 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1490 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1494 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1495 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1496 PtrVT, GOTReg, TGA);
1498 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1499 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1500 PtrVT, TGA, GOTPtr);
1501 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1504 if (Model == TLSModel::GeneralDynamic) {
1505 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1506 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1507 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1509 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1512 // We need a chain node, and don't have one handy. The underlying
1513 // call has no side effects, so using the function entry node
1515 SDValue Chain = DAG.getEntryNode();
1516 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1517 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1518 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1519 PtrVT, ParmReg, TGA);
1520 // The return value from GET_TLS_ADDR really is in X3 already, but
1521 // some hacks are needed here to tie everything together. The extra
1522 // copies dissolve during subsequent transforms.
1523 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1524 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1527 if (Model == TLSModel::LocalDynamic) {
1528 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1529 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1530 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1532 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1535 // We need a chain node, and don't have one handy. The underlying
1536 // call has no side effects, so using the function entry node
1538 SDValue Chain = DAG.getEntryNode();
1539 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1540 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1541 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1542 PtrVT, ParmReg, TGA);
1543 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1544 // some hacks are needed here to tie everything together. The extra
1545 // copies dissolve during subsequent transforms.
1546 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1547 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1548 Chain, ParmReg, TGA);
1549 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1552 llvm_unreachable("Unknown TLS model!");
1555 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1556 SelectionDAG &DAG) const {
1557 EVT PtrVT = Op.getValueType();
1558 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1560 const GlobalValue *GV = GSDN->getGlobal();
1562 // 64-bit SVR4 ABI code is always position-independent.
1563 // The actual address of the GlobalValue is stored in the TOC.
1564 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1565 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1566 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1567 DAG.getRegister(PPC::X2, MVT::i64));
1570 unsigned MOHiFlag, MOLoFlag;
1571 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1574 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1576 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1578 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1580 // If the global reference is actually to a non-lazy-pointer, we have to do an
1581 // extra load to get the address of the global.
1582 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1583 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1584 false, false, false, 0);
1588 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1589 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1592 // If we're comparing for equality to zero, expose the fact that this is
1593 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1594 // fold the new nodes.
1595 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1596 if (C->isNullValue() && CC == ISD::SETEQ) {
1597 EVT VT = Op.getOperand(0).getValueType();
1598 SDValue Zext = Op.getOperand(0);
1599 if (VT.bitsLT(MVT::i32)) {
1601 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1603 unsigned Log2b = Log2_32(VT.getSizeInBits());
1604 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1605 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1606 DAG.getConstant(Log2b, MVT::i32));
1607 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1609 // Leave comparisons against 0 and -1 alone for now, since they're usually
1610 // optimized. FIXME: revisit this when we can custom lower all setcc
1612 if (C->isAllOnesValue() || C->isNullValue())
1616 // If we have an integer seteq/setne, turn it into a compare against zero
1617 // by xor'ing the rhs with the lhs, which is faster than setting a
1618 // condition register, reading it back out, and masking the correct bit. The
1619 // normal approach here uses sub to do this instead of xor. Using xor exposes
1620 // the result to other bit-twiddling opportunities.
1621 EVT LHSVT = Op.getOperand(0).getValueType();
1622 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1623 EVT VT = Op.getValueType();
1624 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1626 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1631 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1632 const PPCSubtarget &Subtarget) const {
1633 SDNode *Node = Op.getNode();
1634 EVT VT = Node->getValueType(0);
1635 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1636 SDValue InChain = Node->getOperand(0);
1637 SDValue VAListPtr = Node->getOperand(1);
1638 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1641 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1644 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1645 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1647 InChain = GprIndex.getValue(1);
1649 if (VT == MVT::i64) {
1650 // Check if GprIndex is even
1651 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1652 DAG.getConstant(1, MVT::i32));
1653 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1654 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1655 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1656 DAG.getConstant(1, MVT::i32));
1657 // Align GprIndex to be even if it isn't
1658 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1662 // fpr index is 1 byte after gpr
1663 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1664 DAG.getConstant(1, MVT::i32));
1667 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1668 FprPtr, MachinePointerInfo(SV), MVT::i8,
1670 InChain = FprIndex.getValue(1);
1672 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1673 DAG.getConstant(8, MVT::i32));
1675 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1676 DAG.getConstant(4, MVT::i32));
1679 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1680 MachinePointerInfo(), false, false,
1682 InChain = OverflowArea.getValue(1);
1684 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1685 MachinePointerInfo(), false, false,
1687 InChain = RegSaveArea.getValue(1);
1689 // select overflow_area if index > 8
1690 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1691 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1693 // adjustment constant gpr_index * 4/8
1694 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1695 VT.isInteger() ? GprIndex : FprIndex,
1696 DAG.getConstant(VT.isInteger() ? 4 : 8,
1699 // OurReg = RegSaveArea + RegConstant
1700 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1703 // Floating types are 32 bytes into RegSaveArea
1704 if (VT.isFloatingPoint())
1705 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1706 DAG.getConstant(32, MVT::i32));
1708 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1709 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1710 VT.isInteger() ? GprIndex : FprIndex,
1711 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1714 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1715 VT.isInteger() ? VAListPtr : FprPtr,
1716 MachinePointerInfo(SV),
1717 MVT::i8, false, false, 0);
1719 // determine if we should load from reg_save_area or overflow_area
1720 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1722 // increase overflow_area by 4/8 if gpr/fpr > 8
1723 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1724 DAG.getConstant(VT.isInteger() ? 4 : 8,
1727 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1730 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1732 MachinePointerInfo(),
1733 MVT::i32, false, false, 0);
1735 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1736 false, false, false, 0);
1739 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1740 const PPCSubtarget &Subtarget) const {
1741 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1743 // We have to copy the entire va_list struct:
1744 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1745 return DAG.getMemcpy(Op.getOperand(0), Op,
1746 Op.getOperand(1), Op.getOperand(2),
1747 DAG.getConstant(12, MVT::i32), 8, false, true,
1748 MachinePointerInfo(), MachinePointerInfo());
1751 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1752 SelectionDAG &DAG) const {
1753 return Op.getOperand(0);
1756 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1757 SelectionDAG &DAG) const {
1758 SDValue Chain = Op.getOperand(0);
1759 SDValue Trmp = Op.getOperand(1); // trampoline
1760 SDValue FPtr = Op.getOperand(2); // nested function
1761 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1764 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1765 bool isPPC64 = (PtrVT == MVT::i64);
1767 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1770 TargetLowering::ArgListTy Args;
1771 TargetLowering::ArgListEntry Entry;
1773 Entry.Ty = IntPtrTy;
1774 Entry.Node = Trmp; Args.push_back(Entry);
1776 // TrampSize == (isPPC64 ? 48 : 40);
1777 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1778 isPPC64 ? MVT::i64 : MVT::i32);
1779 Args.push_back(Entry);
1781 Entry.Node = FPtr; Args.push_back(Entry);
1782 Entry.Node = Nest; Args.push_back(Entry);
1784 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1785 TargetLowering::CallLoweringInfo CLI(Chain,
1786 Type::getVoidTy(*DAG.getContext()),
1787 false, false, false, false, 0,
1789 /*isTailCall=*/false,
1790 /*doesNotRet=*/false,
1791 /*isReturnValueUsed=*/true,
1792 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1794 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1796 return CallResult.second;
1799 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1800 const PPCSubtarget &Subtarget) const {
1801 MachineFunction &MF = DAG.getMachineFunction();
1802 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1806 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1807 // vastart just stores the address of the VarArgsFrameIndex slot into the
1808 // memory location argument.
1809 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1810 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1811 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1812 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1813 MachinePointerInfo(SV),
1817 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1818 // We suppose the given va_list is already allocated.
1821 // char gpr; /* index into the array of 8 GPRs
1822 // * stored in the register save area
1823 // * gpr=0 corresponds to r3,
1824 // * gpr=1 to r4, etc.
1826 // char fpr; /* index into the array of 8 FPRs
1827 // * stored in the register save area
1828 // * fpr=0 corresponds to f1,
1829 // * fpr=1 to f2, etc.
1831 // char *overflow_arg_area;
1832 // /* location on stack that holds
1833 // * the next overflow argument
1835 // char *reg_save_area;
1836 // /* where r3:r10 and f1:f8 (if saved)
1842 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1843 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1846 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1848 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1850 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1853 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1854 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1856 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1857 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1859 uint64_t FPROffset = 1;
1860 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1862 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1864 // Store first byte : number of int regs
1865 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1867 MachinePointerInfo(SV),
1868 MVT::i8, false, false, 0);
1869 uint64_t nextOffset = FPROffset;
1870 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1873 // Store second byte : number of float regs
1874 SDValue secondStore =
1875 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1876 MachinePointerInfo(SV, nextOffset), MVT::i8,
1878 nextOffset += StackOffset;
1879 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1881 // Store second word : arguments given on stack
1882 SDValue thirdStore =
1883 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1884 MachinePointerInfo(SV, nextOffset),
1886 nextOffset += FrameOffset;
1887 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1889 // Store third word : arguments given in registers
1890 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1891 MachinePointerInfo(SV, nextOffset),
1896 #include "PPCGenCallingConv.inc"
1898 // Function whose sole purpose is to kill compiler warnings
1899 // stemming from unused functions included from PPCGenCallingConv.inc.
1900 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1901 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1904 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1905 CCValAssign::LocInfo &LocInfo,
1906 ISD::ArgFlagsTy &ArgFlags,
1911 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1913 CCValAssign::LocInfo &LocInfo,
1914 ISD::ArgFlagsTy &ArgFlags,
1916 static const uint16_t ArgRegs[] = {
1917 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1918 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1920 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1922 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1924 // Skip one register if the first unallocated register has an even register
1925 // number and there are still argument registers available which have not been
1926 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1927 // need to skip a register if RegNum is odd.
1928 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1929 State.AllocateReg(ArgRegs[RegNum]);
1932 // Always return false here, as this function only makes sure that the first
1933 // unallocated register has an odd register number and does not actually
1934 // allocate a register for the current argument.
1938 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1940 CCValAssign::LocInfo &LocInfo,
1941 ISD::ArgFlagsTy &ArgFlags,
1943 static const uint16_t ArgRegs[] = {
1944 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1948 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1950 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1952 // If there is only one Floating-point register left we need to put both f64
1953 // values of a split ppc_fp128 value on the stack.
1954 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1955 State.AllocateReg(ArgRegs[RegNum]);
1958 // Always return false here, as this function only makes sure that the two f64
1959 // values a ppc_fp128 value is split into are both passed in registers or both
1960 // passed on the stack and does not actually allocate a register for the
1961 // current argument.
1965 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1967 static const uint16_t *GetFPR() {
1968 static const uint16_t FPR[] = {
1969 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1970 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1976 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1978 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1979 unsigned PtrByteSize) {
1980 unsigned ArgSize = ArgVT.getStoreSize();
1981 if (Flags.isByVal())
1982 ArgSize = Flags.getByValSize();
1983 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1989 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1990 CallingConv::ID CallConv, bool isVarArg,
1991 const SmallVectorImpl<ISD::InputArg>
1993 SDLoc dl, SelectionDAG &DAG,
1994 SmallVectorImpl<SDValue> &InVals)
1996 if (PPCSubTarget.isSVR4ABI()) {
1997 if (PPCSubTarget.isPPC64())
1998 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2001 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2004 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2010 PPCTargetLowering::LowerFormalArguments_32SVR4(
2012 CallingConv::ID CallConv, bool isVarArg,
2013 const SmallVectorImpl<ISD::InputArg>
2015 SDLoc dl, SelectionDAG &DAG,
2016 SmallVectorImpl<SDValue> &InVals) const {
2018 // 32-bit SVR4 ABI Stack Frame Layout:
2019 // +-----------------------------------+
2020 // +--> | Back chain |
2021 // | +-----------------------------------+
2022 // | | Floating-point register save area |
2023 // | +-----------------------------------+
2024 // | | General register save area |
2025 // | +-----------------------------------+
2026 // | | CR save word |
2027 // | +-----------------------------------+
2028 // | | VRSAVE save word |
2029 // | +-----------------------------------+
2030 // | | Alignment padding |
2031 // | +-----------------------------------+
2032 // | | Vector register save area |
2033 // | +-----------------------------------+
2034 // | | Local variable space |
2035 // | +-----------------------------------+
2036 // | | Parameter list area |
2037 // | +-----------------------------------+
2038 // | | LR save word |
2039 // | +-----------------------------------+
2040 // SP--> +--- | Back chain |
2041 // +-----------------------------------+
2044 // System V Application Binary Interface PowerPC Processor Supplement
2045 // AltiVec Technology Programming Interface Manual
2047 MachineFunction &MF = DAG.getMachineFunction();
2048 MachineFrameInfo *MFI = MF.getFrameInfo();
2049 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2051 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2052 // Potential tail calls could cause overwriting of argument stack slots.
2053 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2054 (CallConv == CallingConv::Fast));
2055 unsigned PtrByteSize = 4;
2057 // Assign locations to all of the incoming arguments.
2058 SmallVector<CCValAssign, 16> ArgLocs;
2059 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2060 getTargetMachine(), ArgLocs, *DAG.getContext());
2062 // Reserve space for the linkage area on the stack.
2063 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2065 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2067 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2068 CCValAssign &VA = ArgLocs[i];
2070 // Arguments stored in registers.
2071 if (VA.isRegLoc()) {
2072 const TargetRegisterClass *RC;
2073 EVT ValVT = VA.getValVT();
2075 switch (ValVT.getSimpleVT().SimpleTy) {
2077 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2080 RC = &PPC::GPRCRegClass;
2083 RC = &PPC::F4RCRegClass;
2086 RC = &PPC::F8RCRegClass;
2092 RC = &PPC::VRRCRegClass;
2096 // Transform the arguments stored in physical registers into virtual ones.
2097 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2098 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2099 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2101 if (ValVT == MVT::i1)
2102 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2104 InVals.push_back(ArgValue);
2106 // Argument stored in memory.
2107 assert(VA.isMemLoc());
2109 unsigned ArgSize = VA.getLocVT().getStoreSize();
2110 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2113 // Create load nodes to retrieve arguments from the stack.
2114 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2115 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2116 MachinePointerInfo(),
2117 false, false, false, 0));
2121 // Assign locations to all of the incoming aggregate by value arguments.
2122 // Aggregates passed by value are stored in the local variable space of the
2123 // caller's stack frame, right above the parameter list area.
2124 SmallVector<CCValAssign, 16> ByValArgLocs;
2125 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2126 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2128 // Reserve stack space for the allocations in CCInfo.
2129 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2131 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2133 // Area that is at least reserved in the caller of this function.
2134 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2136 // Set the size that is at least reserved in caller of this function. Tail
2137 // call optimized function's reserved stack space needs to be aligned so that
2138 // taking the difference between two stack areas will result in an aligned
2140 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2143 std::max(MinReservedArea,
2144 PPCFrameLowering::getMinCallFrameSize(false, false));
2146 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2147 getStackAlignment();
2148 unsigned AlignMask = TargetAlign-1;
2149 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2151 FI->setMinReservedArea(MinReservedArea);
2153 SmallVector<SDValue, 8> MemOps;
2155 // If the function takes variable number of arguments, make a frame index for
2156 // the start of the first vararg value... for expansion of llvm.va_start.
2158 static const uint16_t GPArgRegs[] = {
2159 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2160 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2162 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2164 static const uint16_t FPArgRegs[] = {
2165 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2168 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2170 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2172 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2175 // Make room for NumGPArgRegs and NumFPArgRegs.
2176 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2177 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2179 FuncInfo->setVarArgsStackOffset(
2180 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2181 CCInfo.getNextStackOffset(), true));
2183 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2184 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2186 // The fixed integer arguments of a variadic function are stored to the
2187 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2188 // the result of va_next.
2189 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2190 // Get an existing live-in vreg, or add a new one.
2191 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2193 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2195 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2196 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2197 MachinePointerInfo(), false, false, 0);
2198 MemOps.push_back(Store);
2199 // Increment the address by four for the next argument to store
2200 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2201 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2204 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2206 // The double arguments are stored to the VarArgsFrameIndex
2208 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2209 // Get an existing live-in vreg, or add a new one.
2210 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2212 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2214 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2215 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2216 MachinePointerInfo(), false, false, 0);
2217 MemOps.push_back(Store);
2218 // Increment the address by eight for the next argument to store
2219 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2221 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2225 if (!MemOps.empty())
2226 Chain = DAG.getNode(ISD::TokenFactor, dl,
2227 MVT::Other, &MemOps[0], MemOps.size());
2232 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2233 // value to MVT::i64 and then truncate to the correct register size.
2235 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2236 SelectionDAG &DAG, SDValue ArgVal,
2239 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2240 DAG.getValueType(ObjectVT));
2241 else if (Flags.isZExt())
2242 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2243 DAG.getValueType(ObjectVT));
2245 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2248 // Set the size that is at least reserved in caller of this function. Tail
2249 // call optimized functions' reserved stack space needs to be aligned so that
2250 // taking the difference between two stack areas will result in an aligned
2253 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2254 unsigned nAltivecParamsAtEnd,
2255 unsigned MinReservedArea,
2256 bool isPPC64) const {
2257 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2258 // Add the Altivec parameters at the end, if needed.
2259 if (nAltivecParamsAtEnd) {
2260 MinReservedArea = ((MinReservedArea+15)/16)*16;
2261 MinReservedArea += 16*nAltivecParamsAtEnd;
2264 std::max(MinReservedArea,
2265 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2266 unsigned TargetAlign
2267 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2268 getStackAlignment();
2269 unsigned AlignMask = TargetAlign-1;
2270 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2271 FI->setMinReservedArea(MinReservedArea);
2275 PPCTargetLowering::LowerFormalArguments_64SVR4(
2277 CallingConv::ID CallConv, bool isVarArg,
2278 const SmallVectorImpl<ISD::InputArg>
2280 SDLoc dl, SelectionDAG &DAG,
2281 SmallVectorImpl<SDValue> &InVals) const {
2282 // TODO: add description of PPC stack frame format, or at least some docs.
2284 MachineFunction &MF = DAG.getMachineFunction();
2285 MachineFrameInfo *MFI = MF.getFrameInfo();
2286 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2288 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2289 // Potential tail calls could cause overwriting of argument stack slots.
2290 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2291 (CallConv == CallingConv::Fast));
2292 unsigned PtrByteSize = 8;
2294 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2295 // Area that is at least reserved in caller of this function.
2296 unsigned MinReservedArea = ArgOffset;
2298 static const uint16_t GPR[] = {
2299 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2300 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2303 static const uint16_t *FPR = GetFPR();
2305 static const uint16_t VR[] = {
2306 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2307 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2310 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2311 const unsigned Num_FPR_Regs = 13;
2312 const unsigned Num_VR_Regs = array_lengthof(VR);
2314 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2316 // Add DAG nodes to load the arguments or copy them out of registers. On
2317 // entry to a function on PPC, the arguments start after the linkage area,
2318 // although the first ones are often in registers.
2320 SmallVector<SDValue, 8> MemOps;
2321 unsigned nAltivecParamsAtEnd = 0;
2322 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2323 unsigned CurArgIdx = 0;
2324 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2326 bool needsLoad = false;
2327 EVT ObjectVT = Ins[ArgNo].VT;
2328 unsigned ObjSize = ObjectVT.getStoreSize();
2329 unsigned ArgSize = ObjSize;
2330 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2331 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2332 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2334 unsigned CurArgOffset = ArgOffset;
2336 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2337 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2338 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2340 MinReservedArea = ((MinReservedArea+15)/16)*16;
2341 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2345 nAltivecParamsAtEnd++;
2347 // Calculate min reserved area.
2348 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2352 // FIXME the codegen can be much improved in some cases.
2353 // We do not have to keep everything in memory.
2354 if (Flags.isByVal()) {
2355 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2356 ObjSize = Flags.getByValSize();
2357 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2358 // Empty aggregate parameters do not take up registers. Examples:
2362 // etc. However, we have to provide a place-holder in InVals, so
2363 // pretend we have an 8-byte item at the current address for that
2366 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2367 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2368 InVals.push_back(FIN);
2372 unsigned BVAlign = Flags.getByValAlign();
2374 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2375 CurArgOffset = ArgOffset;
2378 // All aggregates smaller than 8 bytes must be passed right-justified.
2379 if (ObjSize < PtrByteSize)
2380 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2381 // The value of the object is its address.
2382 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2383 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2384 InVals.push_back(FIN);
2387 if (GPR_idx != Num_GPR_Regs) {
2388 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2389 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2392 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2393 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2394 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2395 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2396 MachinePointerInfo(FuncArg),
2397 ObjType, false, false, 0);
2399 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2400 // store the whole register as-is to the parameter save area
2401 // slot. The address of the parameter was already calculated
2402 // above (InVals.push_back(FIN)) to be the right-justified
2403 // offset within the slot. For this store, we need a new
2404 // frame index that points at the beginning of the slot.
2405 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2406 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2407 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2408 MachinePointerInfo(FuncArg),
2412 MemOps.push_back(Store);
2415 // Whether we copied from a register or not, advance the offset
2416 // into the parameter save area by a full doubleword.
2417 ArgOffset += PtrByteSize;
2421 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2422 // Store whatever pieces of the object are in registers
2423 // to memory. ArgOffset will be the address of the beginning
2425 if (GPR_idx != Num_GPR_Regs) {
2427 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2428 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2429 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2430 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2431 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2432 MachinePointerInfo(FuncArg, j),
2434 MemOps.push_back(Store);
2436 ArgOffset += PtrByteSize;
2438 ArgOffset += ArgSize - j;
2445 switch (ObjectVT.getSimpleVT().SimpleTy) {
2446 default: llvm_unreachable("Unhandled argument type!");
2450 if (GPR_idx != Num_GPR_Regs) {
2451 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2452 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2454 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2455 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2456 // value to MVT::i64 and then truncate to the correct register size.
2457 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2462 ArgSize = PtrByteSize;
2469 // Every 8 bytes of argument space consumes one of the GPRs available for
2470 // argument passing.
2471 if (GPR_idx != Num_GPR_Regs) {
2474 if (FPR_idx != Num_FPR_Regs) {
2477 if (ObjectVT == MVT::f32)
2478 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2480 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2482 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2486 ArgSize = PtrByteSize;
2495 // Note that vector arguments in registers don't reserve stack space,
2496 // except in varargs functions.
2497 if (VR_idx != Num_VR_Regs) {
2498 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2499 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2501 while ((ArgOffset % 16) != 0) {
2502 ArgOffset += PtrByteSize;
2503 if (GPR_idx != Num_GPR_Regs)
2507 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2511 // Vectors are aligned.
2512 ArgOffset = ((ArgOffset+15)/16)*16;
2513 CurArgOffset = ArgOffset;
2520 // We need to load the argument to a virtual register if we determined
2521 // above that we ran out of physical registers of the appropriate type.
2523 int FI = MFI->CreateFixedObject(ObjSize,
2524 CurArgOffset + (ArgSize - ObjSize),
2526 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2527 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2528 false, false, false, 0);
2531 InVals.push_back(ArgVal);
2534 // Set the size that is at least reserved in caller of this function. Tail
2535 // call optimized functions' reserved stack space needs to be aligned so that
2536 // taking the difference between two stack areas will result in an aligned
2538 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2540 // If the function takes variable number of arguments, make a frame index for
2541 // the start of the first vararg value... for expansion of llvm.va_start.
2543 int Depth = ArgOffset;
2545 FuncInfo->setVarArgsFrameIndex(
2546 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2547 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2549 // If this function is vararg, store any remaining integer argument regs
2550 // to their spots on the stack so that they may be loaded by deferencing the
2551 // result of va_next.
2552 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2553 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2554 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2555 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2556 MachinePointerInfo(), false, false, 0);
2557 MemOps.push_back(Store);
2558 // Increment the address by four for the next argument to store
2559 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2560 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2564 if (!MemOps.empty())
2565 Chain = DAG.getNode(ISD::TokenFactor, dl,
2566 MVT::Other, &MemOps[0], MemOps.size());
2572 PPCTargetLowering::LowerFormalArguments_Darwin(
2574 CallingConv::ID CallConv, bool isVarArg,
2575 const SmallVectorImpl<ISD::InputArg>
2577 SDLoc dl, SelectionDAG &DAG,
2578 SmallVectorImpl<SDValue> &InVals) const {
2579 // TODO: add description of PPC stack frame format, or at least some docs.
2581 MachineFunction &MF = DAG.getMachineFunction();
2582 MachineFrameInfo *MFI = MF.getFrameInfo();
2583 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2585 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2586 bool isPPC64 = PtrVT == MVT::i64;
2587 // Potential tail calls could cause overwriting of argument stack slots.
2588 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2589 (CallConv == CallingConv::Fast));
2590 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2592 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2593 // Area that is at least reserved in caller of this function.
2594 unsigned MinReservedArea = ArgOffset;
2596 static const uint16_t GPR_32[] = { // 32-bit registers.
2597 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2598 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2600 static const uint16_t GPR_64[] = { // 64-bit registers.
2601 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2602 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2605 static const uint16_t *FPR = GetFPR();
2607 static const uint16_t VR[] = {
2608 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2609 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2612 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2613 const unsigned Num_FPR_Regs = 13;
2614 const unsigned Num_VR_Regs = array_lengthof( VR);
2616 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2618 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2620 // In 32-bit non-varargs functions, the stack space for vectors is after the
2621 // stack space for non-vectors. We do not use this space unless we have
2622 // too many vectors to fit in registers, something that only occurs in
2623 // constructed examples:), but we have to walk the arglist to figure
2624 // that out...for the pathological case, compute VecArgOffset as the
2625 // start of the vector parameter area. Computing VecArgOffset is the
2626 // entire point of the following loop.
2627 unsigned VecArgOffset = ArgOffset;
2628 if (!isVarArg && !isPPC64) {
2629 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2631 EVT ObjectVT = Ins[ArgNo].VT;
2632 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2634 if (Flags.isByVal()) {
2635 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2636 unsigned ObjSize = Flags.getByValSize();
2638 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2639 VecArgOffset += ArgSize;
2643 switch(ObjectVT.getSimpleVT().SimpleTy) {
2644 default: llvm_unreachable("Unhandled argument type!");
2650 case MVT::i64: // PPC64
2652 // FIXME: We are guaranteed to be !isPPC64 at this point.
2653 // Does MVT::i64 apply?
2660 // Nothing to do, we're only looking at Nonvector args here.
2665 // We've found where the vector parameter area in memory is. Skip the
2666 // first 12 parameters; these don't use that memory.
2667 VecArgOffset = ((VecArgOffset+15)/16)*16;
2668 VecArgOffset += 12*16;
2670 // Add DAG nodes to load the arguments or copy them out of registers. On
2671 // entry to a function on PPC, the arguments start after the linkage area,
2672 // although the first ones are often in registers.
2674 SmallVector<SDValue, 8> MemOps;
2675 unsigned nAltivecParamsAtEnd = 0;
2676 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2677 unsigned CurArgIdx = 0;
2678 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2680 bool needsLoad = false;
2681 EVT ObjectVT = Ins[ArgNo].VT;
2682 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2683 unsigned ArgSize = ObjSize;
2684 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2685 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2686 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2688 unsigned CurArgOffset = ArgOffset;
2690 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2691 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2692 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2693 if (isVarArg || isPPC64) {
2694 MinReservedArea = ((MinReservedArea+15)/16)*16;
2695 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2698 } else nAltivecParamsAtEnd++;
2700 // Calculate min reserved area.
2701 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2705 // FIXME the codegen can be much improved in some cases.
2706 // We do not have to keep everything in memory.
2707 if (Flags.isByVal()) {
2708 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2709 ObjSize = Flags.getByValSize();
2710 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2711 // Objects of size 1 and 2 are right justified, everything else is
2712 // left justified. This means the memory address is adjusted forwards.
2713 if (ObjSize==1 || ObjSize==2) {
2714 CurArgOffset = CurArgOffset + (4 - ObjSize);
2716 // The value of the object is its address.
2717 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2718 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2719 InVals.push_back(FIN);
2720 if (ObjSize==1 || ObjSize==2) {
2721 if (GPR_idx != Num_GPR_Regs) {
2724 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2726 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2727 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2728 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2729 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2730 MachinePointerInfo(FuncArg),
2731 ObjType, false, false, 0);
2732 MemOps.push_back(Store);
2736 ArgOffset += PtrByteSize;
2740 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2741 // Store whatever pieces of the object are in registers
2742 // to memory. ArgOffset will be the address of the beginning
2744 if (GPR_idx != Num_GPR_Regs) {
2747 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2749 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2750 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2751 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2752 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2753 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2754 MachinePointerInfo(FuncArg, j),
2756 MemOps.push_back(Store);
2758 ArgOffset += PtrByteSize;
2760 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2767 switch (ObjectVT.getSimpleVT().SimpleTy) {
2768 default: llvm_unreachable("Unhandled argument type!");
2772 if (GPR_idx != Num_GPR_Regs) {
2773 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2774 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2778 ArgSize = PtrByteSize;
2780 // All int arguments reserve stack space in the Darwin ABI.
2781 ArgOffset += PtrByteSize;
2785 case MVT::i64: // PPC64
2786 if (GPR_idx != Num_GPR_Regs) {
2787 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2788 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2790 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2791 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2792 // value to MVT::i64 and then truncate to the correct register size.
2793 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2798 ArgSize = PtrByteSize;
2800 // All int arguments reserve stack space in the Darwin ABI.
2806 // Every 4 bytes of argument space consumes one of the GPRs available for
2807 // argument passing.
2808 if (GPR_idx != Num_GPR_Regs) {
2810 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2813 if (FPR_idx != Num_FPR_Regs) {
2816 if (ObjectVT == MVT::f32)
2817 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2819 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2821 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2827 // All FP arguments reserve stack space in the Darwin ABI.
2828 ArgOffset += isPPC64 ? 8 : ObjSize;
2834 // Note that vector arguments in registers don't reserve stack space,
2835 // except in varargs functions.
2836 if (VR_idx != Num_VR_Regs) {
2837 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2838 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2840 while ((ArgOffset % 16) != 0) {
2841 ArgOffset += PtrByteSize;
2842 if (GPR_idx != Num_GPR_Regs)
2846 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2850 if (!isVarArg && !isPPC64) {
2851 // Vectors go after all the nonvectors.
2852 CurArgOffset = VecArgOffset;
2855 // Vectors are aligned.
2856 ArgOffset = ((ArgOffset+15)/16)*16;
2857 CurArgOffset = ArgOffset;
2865 // We need to load the argument to a virtual register if we determined above
2866 // that we ran out of physical registers of the appropriate type.
2868 int FI = MFI->CreateFixedObject(ObjSize,
2869 CurArgOffset + (ArgSize - ObjSize),
2871 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2872 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2873 false, false, false, 0);
2876 InVals.push_back(ArgVal);
2879 // Set the size that is at least reserved in caller of this function. Tail
2880 // call optimized functions' reserved stack space needs to be aligned so that
2881 // taking the difference between two stack areas will result in an aligned
2883 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2885 // If the function takes variable number of arguments, make a frame index for
2886 // the start of the first vararg value... for expansion of llvm.va_start.
2888 int Depth = ArgOffset;
2890 FuncInfo->setVarArgsFrameIndex(
2891 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2893 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2895 // If this function is vararg, store any remaining integer argument regs
2896 // to their spots on the stack so that they may be loaded by deferencing the
2897 // result of va_next.
2898 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2902 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2904 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2906 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2907 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2908 MachinePointerInfo(), false, false, 0);
2909 MemOps.push_back(Store);
2910 // Increment the address by four for the next argument to store
2911 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2912 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2916 if (!MemOps.empty())
2917 Chain = DAG.getNode(ISD::TokenFactor, dl,
2918 MVT::Other, &MemOps[0], MemOps.size());
2923 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2924 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2926 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2930 const SmallVectorImpl<ISD::OutputArg>
2932 const SmallVectorImpl<SDValue> &OutVals,
2933 unsigned &nAltivecParamsAtEnd) {
2934 // Count how many bytes are to be pushed on the stack, including the linkage
2935 // area, and parameter passing area. We start with 24/48 bytes, which is
2936 // prereserved space for [SP][CR][LR][3 x unused].
2937 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2938 unsigned NumOps = Outs.size();
2939 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2941 // Add up all the space actually used.
2942 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2943 // they all go in registers, but we must reserve stack space for them for
2944 // possible use by the caller. In varargs or 64-bit calls, parameters are
2945 // assigned stack space in order, with padding so Altivec parameters are
2947 nAltivecParamsAtEnd = 0;
2948 for (unsigned i = 0; i != NumOps; ++i) {
2949 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2950 EVT ArgVT = Outs[i].VT;
2951 // Varargs Altivec parameters are padded to a 16 byte boundary.
2952 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2953 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2954 if (!isVarArg && !isPPC64) {
2955 // Non-varargs Altivec parameters go after all the non-Altivec
2956 // parameters; handle those later so we know how much padding we need.
2957 nAltivecParamsAtEnd++;
2960 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2961 NumBytes = ((NumBytes+15)/16)*16;
2963 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2966 // Allow for Altivec parameters at the end, if needed.
2967 if (nAltivecParamsAtEnd) {
2968 NumBytes = ((NumBytes+15)/16)*16;
2969 NumBytes += 16*nAltivecParamsAtEnd;
2972 // The prolog code of the callee may store up to 8 GPR argument registers to
2973 // the stack, allowing va_start to index over them in memory if its varargs.
2974 // Because we cannot tell if this is needed on the caller side, we have to
2975 // conservatively assume that it is needed. As such, make sure we have at
2976 // least enough stack space for the caller to store the 8 GPRs.
2977 NumBytes = std::max(NumBytes,
2978 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2980 // Tail call needs the stack to be aligned.
2981 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2982 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2983 getFrameLowering()->getStackAlignment();
2984 unsigned AlignMask = TargetAlign-1;
2985 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2991 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2992 /// adjusted to accommodate the arguments for the tailcall.
2993 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2994 unsigned ParamSize) {
2996 if (!isTailCall) return 0;
2998 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2999 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3000 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3001 // Remember only if the new adjustement is bigger.
3002 if (SPDiff < FI->getTailCallSPDelta())
3003 FI->setTailCallSPDelta(SPDiff);
3008 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3009 /// for tail call optimization. Targets which want to do tail call
3010 /// optimization should implement this function.
3012 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3013 CallingConv::ID CalleeCC,
3015 const SmallVectorImpl<ISD::InputArg> &Ins,
3016 SelectionDAG& DAG) const {
3017 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3020 // Variable argument functions are not supported.
3024 MachineFunction &MF = DAG.getMachineFunction();
3025 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3026 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3027 // Functions containing by val parameters are not supported.
3028 for (unsigned i = 0; i != Ins.size(); i++) {
3029 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3030 if (Flags.isByVal()) return false;
3033 // Non-PIC/GOT tail calls are supported.
3034 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3037 // At the moment we can only do local tail calls (in same module, hidden
3038 // or protected) if we are generating PIC.
3039 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3040 return G->getGlobal()->hasHiddenVisibility()
3041 || G->getGlobal()->hasProtectedVisibility();
3047 /// isCallCompatibleAddress - Return the immediate to use if the specified
3048 /// 32-bit value is representable in the immediate field of a BxA instruction.
3049 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3050 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3053 int Addr = C->getZExtValue();
3054 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3055 SignExtend32<26>(Addr) != Addr)
3056 return 0; // Top 6 bits have to be sext of immediate.
3058 return DAG.getConstant((int)C->getZExtValue() >> 2,
3059 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3064 struct TailCallArgumentInfo {
3069 TailCallArgumentInfo() : FrameIdx(0) {}
3074 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3076 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3078 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3079 SmallVectorImpl<SDValue> &MemOpChains,
3081 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3082 SDValue Arg = TailCallArgs[i].Arg;
3083 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3084 int FI = TailCallArgs[i].FrameIdx;
3085 // Store relative to framepointer.
3086 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3087 MachinePointerInfo::getFixedStack(FI),
3092 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3093 /// the appropriate stack slot for the tail call optimized function call.
3094 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3095 MachineFunction &MF,
3104 // Calculate the new stack slot for the return address.
3105 int SlotSize = isPPC64 ? 8 : 4;
3106 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3108 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3109 NewRetAddrLoc, true);
3110 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3111 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3112 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3113 MachinePointerInfo::getFixedStack(NewRetAddr),
3116 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3117 // slot as the FP is never overwritten.
3120 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3121 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3123 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3124 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3125 MachinePointerInfo::getFixedStack(NewFPIdx),
3132 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3133 /// the position of the argument.
3135 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3136 SDValue Arg, int SPDiff, unsigned ArgOffset,
3137 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3138 int Offset = ArgOffset + SPDiff;
3139 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3140 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3141 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3142 SDValue FIN = DAG.getFrameIndex(FI, VT);
3143 TailCallArgumentInfo Info;
3145 Info.FrameIdxOp = FIN;
3147 TailCallArguments.push_back(Info);
3150 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3151 /// stack slot. Returns the chain as result and the loaded frame pointers in
3152 /// LROpOut/FPOpout. Used when tail calling.
3153 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3161 // Load the LR and FP stack slot for later adjusting.
3162 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3163 LROpOut = getReturnAddrFrameIndex(DAG);
3164 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3165 false, false, false, 0);
3166 Chain = SDValue(LROpOut.getNode(), 1);
3168 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3169 // slot as the FP is never overwritten.
3171 FPOpOut = getFramePointerFrameIndex(DAG);
3172 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3173 false, false, false, 0);
3174 Chain = SDValue(FPOpOut.getNode(), 1);
3180 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3181 /// by "Src" to address "Dst" of size "Size". Alignment information is
3182 /// specified by the specific parameter attribute. The copy will be passed as
3183 /// a byval function parameter.
3184 /// Sometimes what we are copying is the end of a larger object, the part that
3185 /// does not fit in registers.
3187 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3188 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3190 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3191 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3192 false, false, MachinePointerInfo(0),
3193 MachinePointerInfo(0));
3196 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3199 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3200 SDValue Arg, SDValue PtrOff, int SPDiff,
3201 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3202 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3203 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3205 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3210 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3212 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3213 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3214 DAG.getConstant(ArgOffset, PtrVT));
3216 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3217 MachinePointerInfo(), false, false, 0));
3218 // Calculate and remember argument location.
3219 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3224 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3225 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3226 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3227 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3228 MachineFunction &MF = DAG.getMachineFunction();
3230 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3231 // might overwrite each other in case of tail call optimization.
3232 SmallVector<SDValue, 8> MemOpChains2;
3233 // Do not flag preceding copytoreg stuff together with the following stuff.
3235 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3237 if (!MemOpChains2.empty())
3238 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3239 &MemOpChains2[0], MemOpChains2.size());
3241 // Store the return address to the appropriate stack slot.
3242 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3243 isPPC64, isDarwinABI, dl);
3245 // Emit callseq_end just before tailcall node.
3246 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3247 DAG.getIntPtrConstant(0, true), InFlag, dl);
3248 InFlag = Chain.getValue(1);
3252 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3253 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3254 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3255 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3256 const PPCSubtarget &PPCSubTarget) {
3258 bool isPPC64 = PPCSubTarget.isPPC64();
3259 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3261 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3262 NodeTys.push_back(MVT::Other); // Returns a chain
3263 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3265 unsigned CallOpc = PPCISD::CALL;
3267 bool needIndirectCall = true;
3268 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3269 // If this is an absolute destination address, use the munged value.
3270 Callee = SDValue(Dest, 0);
3271 needIndirectCall = false;
3274 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3275 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3276 // Use indirect calls for ALL functions calls in JIT mode, since the
3277 // far-call stubs may be outside relocation limits for a BL instruction.
3278 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3279 unsigned OpFlags = 0;
3280 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3281 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3282 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3283 (G->getGlobal()->isDeclaration() ||
3284 G->getGlobal()->isWeakForLinker())) {
3285 // PC-relative references to external symbols should go through $stub,
3286 // unless we're building with the leopard linker or later, which
3287 // automatically synthesizes these stubs.
3288 OpFlags = PPCII::MO_DARWIN_STUB;
3291 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3292 // every direct call is) turn it into a TargetGlobalAddress /
3293 // TargetExternalSymbol node so that legalize doesn't hack it.
3294 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3295 Callee.getValueType(),
3297 needIndirectCall = false;
3301 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3302 unsigned char OpFlags = 0;
3304 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3305 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3306 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3307 // PC-relative references to external symbols should go through $stub,
3308 // unless we're building with the leopard linker or later, which
3309 // automatically synthesizes these stubs.
3310 OpFlags = PPCII::MO_DARWIN_STUB;
3313 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3315 needIndirectCall = false;
3318 if (needIndirectCall) {
3319 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3320 // to do the call, we can't use PPCISD::CALL.
3321 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3323 if (isSVR4ABI && isPPC64) {
3324 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3325 // entry point, but to the function descriptor (the function entry point
3326 // address is part of the function descriptor though).
3327 // The function descriptor is a three doubleword structure with the
3328 // following fields: function entry point, TOC base address and
3329 // environment pointer.
3330 // Thus for a call through a function pointer, the following actions need
3332 // 1. Save the TOC of the caller in the TOC save area of its stack
3333 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3334 // 2. Load the address of the function entry point from the function
3336 // 3. Load the TOC of the callee from the function descriptor into r2.
3337 // 4. Load the environment pointer from the function descriptor into
3339 // 5. Branch to the function entry point address.
3340 // 6. On return of the callee, the TOC of the caller needs to be
3341 // restored (this is done in FinishCall()).
3343 // All those operations are flagged together to ensure that no other
3344 // operations can be scheduled in between. E.g. without flagging the
3345 // operations together, a TOC access in the caller could be scheduled
3346 // between the load of the callee TOC and the branch to the callee, which
3347 // results in the TOC access going through the TOC of the callee instead
3348 // of going through the TOC of the caller, which leads to incorrect code.
3350 // Load the address of the function entry point from the function
3352 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3353 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3354 InFlag.getNode() ? 3 : 2);
3355 Chain = LoadFuncPtr.getValue(1);
3356 InFlag = LoadFuncPtr.getValue(2);
3358 // Load environment pointer into r11.
3359 // Offset of the environment pointer within the function descriptor.
3360 SDValue PtrOff = DAG.getIntPtrConstant(16);
3362 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3363 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3365 Chain = LoadEnvPtr.getValue(1);
3366 InFlag = LoadEnvPtr.getValue(2);
3368 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3370 Chain = EnvVal.getValue(0);
3371 InFlag = EnvVal.getValue(1);
3373 // Load TOC of the callee into r2. We are using a target-specific load
3374 // with r2 hard coded, because the result of a target-independent load
3375 // would never go directly into r2, since r2 is a reserved register (which
3376 // prevents the register allocator from allocating it), resulting in an
3377 // additional register being allocated and an unnecessary move instruction
3379 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3380 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3382 Chain = LoadTOCPtr.getValue(0);
3383 InFlag = LoadTOCPtr.getValue(1);
3385 MTCTROps[0] = Chain;
3386 MTCTROps[1] = LoadFuncPtr;
3387 MTCTROps[2] = InFlag;
3390 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3391 2 + (InFlag.getNode() != 0));
3392 InFlag = Chain.getValue(1);
3395 NodeTys.push_back(MVT::Other);
3396 NodeTys.push_back(MVT::Glue);
3397 Ops.push_back(Chain);
3398 CallOpc = PPCISD::BCTRL;
3400 // Add use of X11 (holding environment pointer)
3401 if (isSVR4ABI && isPPC64)
3402 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3403 // Add CTR register as callee so a bctr can be emitted later.
3405 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3408 // If this is a direct call, pass the chain and the callee.
3409 if (Callee.getNode()) {
3410 Ops.push_back(Chain);
3411 Ops.push_back(Callee);
3413 // If this is a tail call add stack pointer delta.
3415 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3417 // Add argument registers to the end of the list so that they are known live
3419 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3420 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3421 RegsToPass[i].second.getValueType()));
3427 bool isLocalCall(const SDValue &Callee)
3429 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3430 return !G->getGlobal()->isDeclaration() &&
3431 !G->getGlobal()->isWeakForLinker();
3436 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3437 CallingConv::ID CallConv, bool isVarArg,
3438 const SmallVectorImpl<ISD::InputArg> &Ins,
3439 SDLoc dl, SelectionDAG &DAG,
3440 SmallVectorImpl<SDValue> &InVals) const {
3442 SmallVector<CCValAssign, 16> RVLocs;
3443 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3444 getTargetMachine(), RVLocs, *DAG.getContext());
3445 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3447 // Copy all of the result registers out of their specified physreg.
3448 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3449 CCValAssign &VA = RVLocs[i];
3450 assert(VA.isRegLoc() && "Can only return in registers!");
3452 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3453 VA.getLocReg(), VA.getLocVT(), InFlag);
3454 Chain = Val.getValue(1);
3455 InFlag = Val.getValue(2);
3457 switch (VA.getLocInfo()) {
3458 default: llvm_unreachable("Unknown loc info!");
3459 case CCValAssign::Full: break;
3460 case CCValAssign::AExt:
3461 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3463 case CCValAssign::ZExt:
3464 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3465 DAG.getValueType(VA.getValVT()));
3466 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3468 case CCValAssign::SExt:
3469 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3470 DAG.getValueType(VA.getValVT()));
3471 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3475 InVals.push_back(Val);
3482 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3483 bool isTailCall, bool isVarArg,
3485 SmallVector<std::pair<unsigned, SDValue>, 8>
3487 SDValue InFlag, SDValue Chain,
3489 int SPDiff, unsigned NumBytes,
3490 const SmallVectorImpl<ISD::InputArg> &Ins,
3491 SmallVectorImpl<SDValue> &InVals) const {
3492 std::vector<EVT> NodeTys;
3493 SmallVector<SDValue, 8> Ops;
3494 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3495 isTailCall, RegsToPass, Ops, NodeTys,
3498 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3499 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3500 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3502 // When performing tail call optimization the callee pops its arguments off
3503 // the stack. Account for this here so these bytes can be pushed back on in
3504 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3505 int BytesCalleePops =
3506 (CallConv == CallingConv::Fast &&
3507 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3509 // Add a register mask operand representing the call-preserved registers.
3510 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3511 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3512 assert(Mask && "Missing call preserved mask for calling convention");
3513 Ops.push_back(DAG.getRegisterMask(Mask));
3515 if (InFlag.getNode())
3516 Ops.push_back(InFlag);
3520 assert(((Callee.getOpcode() == ISD::Register &&
3521 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3522 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3523 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3524 isa<ConstantSDNode>(Callee)) &&
3525 "Expecting an global address, external symbol, absolute value or register");
3527 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3530 // Add a NOP immediately after the branch instruction when using the 64-bit
3531 // SVR4 ABI. At link time, if caller and callee are in a different module and
3532 // thus have a different TOC, the call will be replaced with a call to a stub
3533 // function which saves the current TOC, loads the TOC of the callee and
3534 // branches to the callee. The NOP will be replaced with a load instruction
3535 // which restores the TOC of the caller from the TOC save slot of the current
3536 // stack frame. If caller and callee belong to the same module (and have the
3537 // same TOC), the NOP will remain unchanged.
3539 bool needsTOCRestore = false;
3540 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3541 if (CallOpc == PPCISD::BCTRL) {
3542 // This is a call through a function pointer.
3543 // Restore the caller TOC from the save area into R2.
3544 // See PrepareCall() for more information about calls through function
3545 // pointers in the 64-bit SVR4 ABI.
3546 // We are using a target-specific load with r2 hard coded, because the
3547 // result of a target-independent load would never go directly into r2,
3548 // since r2 is a reserved register (which prevents the register allocator
3549 // from allocating it), resulting in an additional register being
3550 // allocated and an unnecessary move instruction being generated.
3551 needsTOCRestore = true;
3552 } else if ((CallOpc == PPCISD::CALL) &&
3553 (!isLocalCall(Callee) ||
3554 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3555 // Otherwise insert NOP for non-local calls.
3556 CallOpc = PPCISD::CALL_NOP;
3560 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3561 InFlag = Chain.getValue(1);
3563 if (needsTOCRestore) {
3564 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3565 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3566 InFlag = Chain.getValue(1);
3569 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3570 DAG.getIntPtrConstant(BytesCalleePops, true),
3573 InFlag = Chain.getValue(1);
3575 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3576 Ins, dl, DAG, InVals);
3580 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3581 SmallVectorImpl<SDValue> &InVals) const {
3582 SelectionDAG &DAG = CLI.DAG;
3584 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3585 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3586 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3587 SDValue Chain = CLI.Chain;
3588 SDValue Callee = CLI.Callee;
3589 bool &isTailCall = CLI.IsTailCall;
3590 CallingConv::ID CallConv = CLI.CallConv;
3591 bool isVarArg = CLI.IsVarArg;
3594 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3597 if (PPCSubTarget.isSVR4ABI()) {
3598 if (PPCSubTarget.isPPC64())
3599 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3600 isTailCall, Outs, OutVals, Ins,
3603 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3604 isTailCall, Outs, OutVals, Ins,
3608 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3609 isTailCall, Outs, OutVals, Ins,
3614 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3615 CallingConv::ID CallConv, bool isVarArg,
3617 const SmallVectorImpl<ISD::OutputArg> &Outs,
3618 const SmallVectorImpl<SDValue> &OutVals,
3619 const SmallVectorImpl<ISD::InputArg> &Ins,
3620 SDLoc dl, SelectionDAG &DAG,
3621 SmallVectorImpl<SDValue> &InVals) const {
3622 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3623 // of the 32-bit SVR4 ABI stack frame layout.
3625 assert((CallConv == CallingConv::C ||
3626 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3628 unsigned PtrByteSize = 4;
3630 MachineFunction &MF = DAG.getMachineFunction();
3632 // Mark this function as potentially containing a function that contains a
3633 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3634 // and restoring the callers stack pointer in this functions epilog. This is
3635 // done because by tail calling the called function might overwrite the value
3636 // in this function's (MF) stack pointer stack slot 0(SP).
3637 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3638 CallConv == CallingConv::Fast)
3639 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3641 // Count how many bytes are to be pushed on the stack, including the linkage
3642 // area, parameter list area and the part of the local variable space which
3643 // contains copies of aggregates which are passed by value.
3645 // Assign locations to all of the outgoing arguments.
3646 SmallVector<CCValAssign, 16> ArgLocs;
3647 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3648 getTargetMachine(), ArgLocs, *DAG.getContext());
3650 // Reserve space for the linkage area on the stack.
3651 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3654 // Handle fixed and variable vector arguments differently.
3655 // Fixed vector arguments go into registers as long as registers are
3656 // available. Variable vector arguments always go into memory.
3657 unsigned NumArgs = Outs.size();
3659 for (unsigned i = 0; i != NumArgs; ++i) {
3660 MVT ArgVT = Outs[i].VT;
3661 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3664 if (Outs[i].IsFixed) {
3665 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3668 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3674 errs() << "Call operand #" << i << " has unhandled type "
3675 << EVT(ArgVT).getEVTString() << "\n";
3677 llvm_unreachable(0);
3681 // All arguments are treated the same.
3682 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3685 // Assign locations to all of the outgoing aggregate by value arguments.
3686 SmallVector<CCValAssign, 16> ByValArgLocs;
3687 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3688 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3690 // Reserve stack space for the allocations in CCInfo.
3691 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3693 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3695 // Size of the linkage area, parameter list area and the part of the local
3696 // space variable where copies of aggregates which are passed by value are
3698 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3700 // Calculate by how many bytes the stack has to be adjusted in case of tail
3701 // call optimization.
3702 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3704 // Adjust the stack pointer for the new arguments...
3705 // These operations are automatically eliminated by the prolog/epilog pass
3706 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3708 SDValue CallSeqStart = Chain;
3710 // Load the return address and frame pointer so it can be moved somewhere else
3713 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3716 // Set up a copy of the stack pointer for use loading and storing any
3717 // arguments that may not fit in the registers available for argument
3719 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3721 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3722 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3723 SmallVector<SDValue, 8> MemOpChains;
3725 bool seenFloatArg = false;
3726 // Walk the register/memloc assignments, inserting copies/loads.
3727 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3730 CCValAssign &VA = ArgLocs[i];
3731 SDValue Arg = OutVals[i];
3732 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3734 if (Flags.isByVal()) {
3735 // Argument is an aggregate which is passed by value, thus we need to
3736 // create a copy of it in the local variable space of the current stack
3737 // frame (which is the stack frame of the caller) and pass the address of
3738 // this copy to the callee.
3739 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3740 CCValAssign &ByValVA = ByValArgLocs[j++];
3741 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3743 // Memory reserved in the local variable space of the callers stack frame.
3744 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3746 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3747 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3749 // Create a copy of the argument in the local area of the current
3751 SDValue MemcpyCall =
3752 CreateCopyOfByValArgument(Arg, PtrOff,
3753 CallSeqStart.getNode()->getOperand(0),
3756 // This must go outside the CALLSEQ_START..END.
3757 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3758 CallSeqStart.getNode()->getOperand(1),
3760 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3761 NewCallSeqStart.getNode());
3762 Chain = CallSeqStart = NewCallSeqStart;
3764 // Pass the address of the aggregate copy on the stack either in a
3765 // physical register or in the parameter list area of the current stack
3766 // frame to the callee.
3770 if (VA.isRegLoc()) {
3771 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3772 // Put argument in a physical register.
3773 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3775 // Put argument in the parameter list area of the current stack frame.
3776 assert(VA.isMemLoc());
3777 unsigned LocMemOffset = VA.getLocMemOffset();
3780 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3781 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3783 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3784 MachinePointerInfo(),
3787 // Calculate and remember argument location.
3788 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3794 if (!MemOpChains.empty())
3795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3796 &MemOpChains[0], MemOpChains.size());
3798 // Build a sequence of copy-to-reg nodes chained together with token chain
3799 // and flag operands which copy the outgoing args into the appropriate regs.
3801 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3802 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3803 RegsToPass[i].second, InFlag);
3804 InFlag = Chain.getValue(1);
3807 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3810 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3811 SDValue Ops[] = { Chain, InFlag };
3813 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3814 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3816 InFlag = Chain.getValue(1);
3820 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3821 false, TailCallArguments);
3823 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3824 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3828 // Copy an argument into memory, being careful to do this outside the
3829 // call sequence for the call to which the argument belongs.
3831 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3832 SDValue CallSeqStart,
3833 ISD::ArgFlagsTy Flags,
3836 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3837 CallSeqStart.getNode()->getOperand(0),
3839 // The MEMCPY must go outside the CALLSEQ_START..END.
3840 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3841 CallSeqStart.getNode()->getOperand(1),
3843 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3844 NewCallSeqStart.getNode());
3845 return NewCallSeqStart;
3849 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3850 CallingConv::ID CallConv, bool isVarArg,
3852 const SmallVectorImpl<ISD::OutputArg> &Outs,
3853 const SmallVectorImpl<SDValue> &OutVals,
3854 const SmallVectorImpl<ISD::InputArg> &Ins,
3855 SDLoc dl, SelectionDAG &DAG,
3856 SmallVectorImpl<SDValue> &InVals) const {
3858 unsigned NumOps = Outs.size();
3860 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3861 unsigned PtrByteSize = 8;
3863 MachineFunction &MF = DAG.getMachineFunction();
3865 // Mark this function as potentially containing a function that contains a
3866 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3867 // and restoring the callers stack pointer in this functions epilog. This is
3868 // done because by tail calling the called function might overwrite the value
3869 // in this function's (MF) stack pointer stack slot 0(SP).
3870 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3871 CallConv == CallingConv::Fast)
3872 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3874 unsigned nAltivecParamsAtEnd = 0;
3876 // Count how many bytes are to be pushed on the stack, including the linkage
3877 // area, and parameter passing area. We start with at least 48 bytes, which
3878 // is reserved space for [SP][CR][LR][3 x unused].
3879 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3882 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3883 Outs, OutVals, nAltivecParamsAtEnd);
3885 // Calculate by how many bytes the stack has to be adjusted in case of tail
3886 // call optimization.
3887 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3889 // To protect arguments on the stack from being clobbered in a tail call,
3890 // force all the loads to happen before doing any other lowering.
3892 Chain = DAG.getStackArgumentTokenFactor(Chain);
3894 // Adjust the stack pointer for the new arguments...
3895 // These operations are automatically eliminated by the prolog/epilog pass
3896 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3898 SDValue CallSeqStart = Chain;
3900 // Load the return address and frame pointer so it can be move somewhere else
3903 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3906 // Set up a copy of the stack pointer for use loading and storing any
3907 // arguments that may not fit in the registers available for argument
3909 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3911 // Figure out which arguments are going to go in registers, and which in
3912 // memory. Also, if this is a vararg function, floating point operations
3913 // must be stored to our stack, and loaded into integer regs as well, if
3914 // any integer regs are available for argument passing.
3915 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3916 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3918 static const uint16_t GPR[] = {
3919 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3920 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3922 static const uint16_t *FPR = GetFPR();
3924 static const uint16_t VR[] = {
3925 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3926 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3928 const unsigned NumGPRs = array_lengthof(GPR);
3929 const unsigned NumFPRs = 13;
3930 const unsigned NumVRs = array_lengthof(VR);
3932 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3933 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3935 SmallVector<SDValue, 8> MemOpChains;
3936 for (unsigned i = 0; i != NumOps; ++i) {
3937 SDValue Arg = OutVals[i];
3938 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3940 // PtrOff will be used to store the current argument to the stack if a
3941 // register cannot be found for it.
3944 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3946 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3948 // Promote integers to 64-bit values.
3949 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
3950 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3951 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3952 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3955 // FIXME memcpy is used way more than necessary. Correctness first.
3956 // Note: "by value" is code for passing a structure by value, not
3958 if (Flags.isByVal()) {
3959 // Note: Size includes alignment padding, so
3960 // struct x { short a; char b; }
3961 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3962 // These are the proper values we need for right-justifying the
3963 // aggregate in a parameter register.
3964 unsigned Size = Flags.getByValSize();
3966 // An empty aggregate parameter takes up no storage and no
3971 unsigned BVAlign = Flags.getByValAlign();
3973 if (BVAlign % PtrByteSize != 0)
3975 "ByVal alignment is not a multiple of the pointer size");
3977 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
3980 // All aggregates smaller than 8 bytes must be passed right-justified.
3981 if (Size==1 || Size==2 || Size==4) {
3982 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3983 if (GPR_idx != NumGPRs) {
3984 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3985 MachinePointerInfo(), VT,
3987 MemOpChains.push_back(Load.getValue(1));
3988 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3990 ArgOffset += PtrByteSize;
3995 if (GPR_idx == NumGPRs && Size < 8) {
3996 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3997 PtrOff.getValueType());
3998 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3999 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4002 ArgOffset += PtrByteSize;
4005 // Copy entire object into memory. There are cases where gcc-generated
4006 // code assumes it is there, even if it could be put entirely into
4007 // registers. (This is not what the doc says.)
4009 // FIXME: The above statement is likely due to a misunderstanding of the
4010 // documents. All arguments must be copied into the parameter area BY
4011 // THE CALLEE in the event that the callee takes the address of any
4012 // formal argument. That has not yet been implemented. However, it is
4013 // reasonable to use the stack area as a staging area for the register
4016 // Skip this for small aggregates, as we will use the same slot for a
4017 // right-justified copy, below.
4019 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4023 // When a register is available, pass a small aggregate right-justified.
4024 if (Size < 8 && GPR_idx != NumGPRs) {
4025 // The easiest way to get this right-justified in a register
4026 // is to copy the structure into the rightmost portion of a
4027 // local variable slot, then load the whole slot into the
4029 // FIXME: The memcpy seems to produce pretty awful code for
4030 // small aggregates, particularly for packed ones.
4031 // FIXME: It would be preferable to use the slot in the
4032 // parameter save area instead of a new local variable.
4033 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4034 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4035 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4039 // Load the slot into the register.
4040 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4041 MachinePointerInfo(),
4042 false, false, false, 0);
4043 MemOpChains.push_back(Load.getValue(1));
4044 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4046 // Done with this argument.
4047 ArgOffset += PtrByteSize;
4051 // For aggregates larger than PtrByteSize, copy the pieces of the
4052 // object that fit into registers from the parameter save area.
4053 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4054 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4055 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4056 if (GPR_idx != NumGPRs) {
4057 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4058 MachinePointerInfo(),
4059 false, false, false, 0);
4060 MemOpChains.push_back(Load.getValue(1));
4061 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4062 ArgOffset += PtrByteSize;
4064 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4071 switch (Arg.getSimpleValueType().SimpleTy) {
4072 default: llvm_unreachable("Unexpected ValueType for argument!");
4076 if (GPR_idx != NumGPRs) {
4077 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4079 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4080 true, isTailCall, false, MemOpChains,
4081 TailCallArguments, dl);
4083 ArgOffset += PtrByteSize;
4087 if (FPR_idx != NumFPRs) {
4088 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4091 // A single float or an aggregate containing only a single float
4092 // must be passed right-justified in the stack doubleword, and
4093 // in the GPR, if one is available.
4095 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4096 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4097 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4101 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4102 MachinePointerInfo(), false, false, 0);
4103 MemOpChains.push_back(Store);
4105 // Float varargs are always shadowed in available integer registers
4106 if (GPR_idx != NumGPRs) {
4107 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4108 MachinePointerInfo(), false, false,
4110 MemOpChains.push_back(Load.getValue(1));
4111 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4113 } else if (GPR_idx != NumGPRs)
4114 // If we have any FPRs remaining, we may also have GPRs remaining.
4117 // Single-precision floating-point values are mapped to the
4118 // second (rightmost) word of the stack doubleword.
4119 if (Arg.getValueType() == MVT::f32) {
4120 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4121 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4124 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4125 true, isTailCall, false, MemOpChains,
4126 TailCallArguments, dl);
4135 // These go aligned on the stack, or in the corresponding R registers
4136 // when within range. The Darwin PPC ABI doc claims they also go in
4137 // V registers; in fact gcc does this only for arguments that are
4138 // prototyped, not for those that match the ... We do it for all
4139 // arguments, seems to work.
4140 while (ArgOffset % 16 !=0) {
4141 ArgOffset += PtrByteSize;
4142 if (GPR_idx != NumGPRs)
4145 // We could elide this store in the case where the object fits
4146 // entirely in R registers. Maybe later.
4147 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4148 DAG.getConstant(ArgOffset, PtrVT));
4149 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4150 MachinePointerInfo(), false, false, 0);
4151 MemOpChains.push_back(Store);
4152 if (VR_idx != NumVRs) {
4153 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4154 MachinePointerInfo(),
4155 false, false, false, 0);
4156 MemOpChains.push_back(Load.getValue(1));
4157 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4160 for (unsigned i=0; i<16; i+=PtrByteSize) {
4161 if (GPR_idx == NumGPRs)
4163 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4164 DAG.getConstant(i, PtrVT));
4165 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4166 false, false, false, 0);
4167 MemOpChains.push_back(Load.getValue(1));
4168 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4173 // Non-varargs Altivec params generally go in registers, but have
4174 // stack space allocated at the end.
4175 if (VR_idx != NumVRs) {
4176 // Doesn't have GPR space allocated.
4177 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4179 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4180 true, isTailCall, true, MemOpChains,
4181 TailCallArguments, dl);
4188 if (!MemOpChains.empty())
4189 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4190 &MemOpChains[0], MemOpChains.size());
4192 // Check if this is an indirect call (MTCTR/BCTRL).
4193 // See PrepareCall() for more information about calls through function
4194 // pointers in the 64-bit SVR4 ABI.
4196 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4197 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4198 !isBLACompatibleAddress(Callee, DAG)) {
4199 // Load r2 into a virtual register and store it to the TOC save area.
4200 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4201 // TOC save area offset.
4202 SDValue PtrOff = DAG.getIntPtrConstant(40);
4203 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4204 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4206 // R12 must contain the address of an indirect callee. This does not
4207 // mean the MTCTR instruction must use R12; it's easier to model this
4208 // as an extra parameter, so do that.
4209 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4212 // Build a sequence of copy-to-reg nodes chained together with token chain
4213 // and flag operands which copy the outgoing args into the appropriate regs.
4215 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4216 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4217 RegsToPass[i].second, InFlag);
4218 InFlag = Chain.getValue(1);
4222 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4223 FPOp, true, TailCallArguments);
4225 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4226 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4231 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4232 CallingConv::ID CallConv, bool isVarArg,
4234 const SmallVectorImpl<ISD::OutputArg> &Outs,
4235 const SmallVectorImpl<SDValue> &OutVals,
4236 const SmallVectorImpl<ISD::InputArg> &Ins,
4237 SDLoc dl, SelectionDAG &DAG,
4238 SmallVectorImpl<SDValue> &InVals) const {
4240 unsigned NumOps = Outs.size();
4242 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4243 bool isPPC64 = PtrVT == MVT::i64;
4244 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4246 MachineFunction &MF = DAG.getMachineFunction();
4248 // Mark this function as potentially containing a function that contains a
4249 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4250 // and restoring the callers stack pointer in this functions epilog. This is
4251 // done because by tail calling the called function might overwrite the value
4252 // in this function's (MF) stack pointer stack slot 0(SP).
4253 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4254 CallConv == CallingConv::Fast)
4255 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4257 unsigned nAltivecParamsAtEnd = 0;
4259 // Count how many bytes are to be pushed on the stack, including the linkage
4260 // area, and parameter passing area. We start with 24/48 bytes, which is
4261 // prereserved space for [SP][CR][LR][3 x unused].
4263 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4265 nAltivecParamsAtEnd);
4267 // Calculate by how many bytes the stack has to be adjusted in case of tail
4268 // call optimization.
4269 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4271 // To protect arguments on the stack from being clobbered in a tail call,
4272 // force all the loads to happen before doing any other lowering.
4274 Chain = DAG.getStackArgumentTokenFactor(Chain);
4276 // Adjust the stack pointer for the new arguments...
4277 // These operations are automatically eliminated by the prolog/epilog pass
4278 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4280 SDValue CallSeqStart = Chain;
4282 // Load the return address and frame pointer so it can be move somewhere else
4285 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4288 // Set up a copy of the stack pointer for use loading and storing any
4289 // arguments that may not fit in the registers available for argument
4293 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4295 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4297 // Figure out which arguments are going to go in registers, and which in
4298 // memory. Also, if this is a vararg function, floating point operations
4299 // must be stored to our stack, and loaded into integer regs as well, if
4300 // any integer regs are available for argument passing.
4301 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4302 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4304 static const uint16_t GPR_32[] = { // 32-bit registers.
4305 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4306 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4308 static const uint16_t GPR_64[] = { // 64-bit registers.
4309 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4310 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4312 static const uint16_t *FPR = GetFPR();
4314 static const uint16_t VR[] = {
4315 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4316 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4318 const unsigned NumGPRs = array_lengthof(GPR_32);
4319 const unsigned NumFPRs = 13;
4320 const unsigned NumVRs = array_lengthof(VR);
4322 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4324 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4325 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4327 SmallVector<SDValue, 8> MemOpChains;
4328 for (unsigned i = 0; i != NumOps; ++i) {
4329 SDValue Arg = OutVals[i];
4330 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4332 // PtrOff will be used to store the current argument to the stack if a
4333 // register cannot be found for it.
4336 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4338 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4340 // On PPC64, promote integers to 64-bit values.
4341 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4342 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4343 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4344 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4347 // FIXME memcpy is used way more than necessary. Correctness first.
4348 // Note: "by value" is code for passing a structure by value, not
4350 if (Flags.isByVal()) {
4351 unsigned Size = Flags.getByValSize();
4352 // Very small objects are passed right-justified. Everything else is
4353 // passed left-justified.
4354 if (Size==1 || Size==2) {
4355 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4356 if (GPR_idx != NumGPRs) {
4357 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4358 MachinePointerInfo(), VT,
4360 MemOpChains.push_back(Load.getValue(1));
4361 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4363 ArgOffset += PtrByteSize;
4365 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4366 PtrOff.getValueType());
4367 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4368 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4371 ArgOffset += PtrByteSize;
4375 // Copy entire object into memory. There are cases where gcc-generated
4376 // code assumes it is there, even if it could be put entirely into
4377 // registers. (This is not what the doc says.)
4378 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4382 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4383 // copy the pieces of the object that fit into registers from the
4384 // parameter save area.
4385 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4386 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4387 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4388 if (GPR_idx != NumGPRs) {
4389 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4390 MachinePointerInfo(),
4391 false, false, false, 0);
4392 MemOpChains.push_back(Load.getValue(1));
4393 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4394 ArgOffset += PtrByteSize;
4396 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4403 switch (Arg.getSimpleValueType().SimpleTy) {
4404 default: llvm_unreachable("Unexpected ValueType for argument!");
4408 if (GPR_idx != NumGPRs) {
4409 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4411 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4412 isPPC64, isTailCall, false, MemOpChains,
4413 TailCallArguments, dl);
4415 ArgOffset += PtrByteSize;
4419 if (FPR_idx != NumFPRs) {
4420 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4423 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4424 MachinePointerInfo(), false, false, 0);
4425 MemOpChains.push_back(Store);
4427 // Float varargs are always shadowed in available integer registers
4428 if (GPR_idx != NumGPRs) {
4429 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4430 MachinePointerInfo(), false, false,
4432 MemOpChains.push_back(Load.getValue(1));
4433 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4435 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4436 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4437 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4438 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4439 MachinePointerInfo(),
4440 false, false, false, 0);
4441 MemOpChains.push_back(Load.getValue(1));
4442 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4445 // If we have any FPRs remaining, we may also have GPRs remaining.
4446 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4448 if (GPR_idx != NumGPRs)
4450 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4451 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4455 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4456 isPPC64, isTailCall, false, MemOpChains,
4457 TailCallArguments, dl);
4461 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4468 // These go aligned on the stack, or in the corresponding R registers
4469 // when within range. The Darwin PPC ABI doc claims they also go in
4470 // V registers; in fact gcc does this only for arguments that are
4471 // prototyped, not for those that match the ... We do it for all
4472 // arguments, seems to work.
4473 while (ArgOffset % 16 !=0) {
4474 ArgOffset += PtrByteSize;
4475 if (GPR_idx != NumGPRs)
4478 // We could elide this store in the case where the object fits
4479 // entirely in R registers. Maybe later.
4480 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4481 DAG.getConstant(ArgOffset, PtrVT));
4482 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4483 MachinePointerInfo(), false, false, 0);
4484 MemOpChains.push_back(Store);
4485 if (VR_idx != NumVRs) {
4486 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4487 MachinePointerInfo(),
4488 false, false, false, 0);
4489 MemOpChains.push_back(Load.getValue(1));
4490 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4493 for (unsigned i=0; i<16; i+=PtrByteSize) {
4494 if (GPR_idx == NumGPRs)
4496 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4497 DAG.getConstant(i, PtrVT));
4498 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4499 false, false, false, 0);
4500 MemOpChains.push_back(Load.getValue(1));
4501 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4506 // Non-varargs Altivec params generally go in registers, but have
4507 // stack space allocated at the end.
4508 if (VR_idx != NumVRs) {
4509 // Doesn't have GPR space allocated.
4510 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4511 } else if (nAltivecParamsAtEnd==0) {
4512 // We are emitting Altivec params in order.
4513 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4514 isPPC64, isTailCall, true, MemOpChains,
4515 TailCallArguments, dl);
4521 // If all Altivec parameters fit in registers, as they usually do,
4522 // they get stack space following the non-Altivec parameters. We
4523 // don't track this here because nobody below needs it.
4524 // If there are more Altivec parameters than fit in registers emit
4526 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4528 // Offset is aligned; skip 1st 12 params which go in V registers.
4529 ArgOffset = ((ArgOffset+15)/16)*16;
4531 for (unsigned i = 0; i != NumOps; ++i) {
4532 SDValue Arg = OutVals[i];
4533 EVT ArgType = Outs[i].VT;
4534 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4535 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4538 // We are emitting Altivec params in order.
4539 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4540 isPPC64, isTailCall, true, MemOpChains,
4541 TailCallArguments, dl);
4548 if (!MemOpChains.empty())
4549 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4550 &MemOpChains[0], MemOpChains.size());
4552 // On Darwin, R12 must contain the address of an indirect callee. This does
4553 // not mean the MTCTR instruction must use R12; it's easier to model this as
4554 // an extra parameter, so do that.
4556 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4557 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4558 !isBLACompatibleAddress(Callee, DAG))
4559 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4560 PPC::R12), Callee));
4562 // Build a sequence of copy-to-reg nodes chained together with token chain
4563 // and flag operands which copy the outgoing args into the appropriate regs.
4565 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4566 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4567 RegsToPass[i].second, InFlag);
4568 InFlag = Chain.getValue(1);
4572 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4573 FPOp, true, TailCallArguments);
4575 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4576 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4581 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4582 MachineFunction &MF, bool isVarArg,
4583 const SmallVectorImpl<ISD::OutputArg> &Outs,
4584 LLVMContext &Context) const {
4585 SmallVector<CCValAssign, 16> RVLocs;
4586 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4588 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4592 PPCTargetLowering::LowerReturn(SDValue Chain,
4593 CallingConv::ID CallConv, bool isVarArg,
4594 const SmallVectorImpl<ISD::OutputArg> &Outs,
4595 const SmallVectorImpl<SDValue> &OutVals,
4596 SDLoc dl, SelectionDAG &DAG) const {
4598 SmallVector<CCValAssign, 16> RVLocs;
4599 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4600 getTargetMachine(), RVLocs, *DAG.getContext());
4601 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4604 SmallVector<SDValue, 4> RetOps(1, Chain);
4606 // Copy the result values into the output registers.
4607 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4608 CCValAssign &VA = RVLocs[i];
4609 assert(VA.isRegLoc() && "Can only return in registers!");
4611 SDValue Arg = OutVals[i];
4613 switch (VA.getLocInfo()) {
4614 default: llvm_unreachable("Unknown loc info!");
4615 case CCValAssign::Full: break;
4616 case CCValAssign::AExt:
4617 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4619 case CCValAssign::ZExt:
4620 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4622 case CCValAssign::SExt:
4623 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4627 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4628 Flag = Chain.getValue(1);
4629 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4632 RetOps[0] = Chain; // Update chain.
4634 // Add the flag if we have it.
4636 RetOps.push_back(Flag);
4638 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4639 &RetOps[0], RetOps.size());
4642 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4643 const PPCSubtarget &Subtarget) const {
4644 // When we pop the dynamic allocation we need to restore the SP link.
4647 // Get the corect type for pointers.
4648 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4650 // Construct the stack pointer operand.
4651 bool isPPC64 = Subtarget.isPPC64();
4652 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4653 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4655 // Get the operands for the STACKRESTORE.
4656 SDValue Chain = Op.getOperand(0);
4657 SDValue SaveSP = Op.getOperand(1);
4659 // Load the old link SP.
4660 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4661 MachinePointerInfo(),
4662 false, false, false, 0);
4664 // Restore the stack pointer.
4665 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4667 // Store the old link SP.
4668 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4675 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4676 MachineFunction &MF = DAG.getMachineFunction();
4677 bool isPPC64 = PPCSubTarget.isPPC64();
4678 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4679 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4681 // Get current frame pointer save index. The users of this index will be
4682 // primarily DYNALLOC instructions.
4683 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4684 int RASI = FI->getReturnAddrSaveIndex();
4686 // If the frame pointer save index hasn't been defined yet.
4688 // Find out what the fix offset of the frame pointer save area.
4689 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4690 // Allocate the frame index for frame pointer save area.
4691 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4693 FI->setReturnAddrSaveIndex(RASI);
4695 return DAG.getFrameIndex(RASI, PtrVT);
4699 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4700 MachineFunction &MF = DAG.getMachineFunction();
4701 bool isPPC64 = PPCSubTarget.isPPC64();
4702 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4703 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4705 // Get current frame pointer save index. The users of this index will be
4706 // primarily DYNALLOC instructions.
4707 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4708 int FPSI = FI->getFramePointerSaveIndex();
4710 // If the frame pointer save index hasn't been defined yet.
4712 // Find out what the fix offset of the frame pointer save area.
4713 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4716 // Allocate the frame index for frame pointer save area.
4717 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4719 FI->setFramePointerSaveIndex(FPSI);
4721 return DAG.getFrameIndex(FPSI, PtrVT);
4724 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4726 const PPCSubtarget &Subtarget) const {
4728 SDValue Chain = Op.getOperand(0);
4729 SDValue Size = Op.getOperand(1);
4732 // Get the corect type for pointers.
4733 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4735 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4736 DAG.getConstant(0, PtrVT), Size);
4737 // Construct a node for the frame pointer save index.
4738 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4739 // Build a DYNALLOC node.
4740 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4741 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4742 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4745 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4746 SelectionDAG &DAG) const {
4748 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4749 DAG.getVTList(MVT::i32, MVT::Other),
4750 Op.getOperand(0), Op.getOperand(1));
4753 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4754 SelectionDAG &DAG) const {
4756 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4757 Op.getOperand(0), Op.getOperand(1));
4760 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4761 assert(Op.getValueType() == MVT::i1 &&
4762 "Custom lowering only for i1 loads");
4764 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4767 LoadSDNode *LD = cast<LoadSDNode>(Op);
4769 SDValue Chain = LD->getChain();
4770 SDValue BasePtr = LD->getBasePtr();
4771 MachineMemOperand *MMO = LD->getMemOperand();
4773 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4774 BasePtr, MVT::i8, MMO);
4775 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4777 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4778 return DAG.getMergeValues(Ops, 2, dl);
4781 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4782 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4783 "Custom lowering only for i1 stores");
4785 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4788 StoreSDNode *ST = cast<StoreSDNode>(Op);
4790 SDValue Chain = ST->getChain();
4791 SDValue BasePtr = ST->getBasePtr();
4792 SDValue Value = ST->getValue();
4793 MachineMemOperand *MMO = ST->getMemOperand();
4795 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4796 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4799 // FIXME: Remove this once the ANDI glue bug is fixed:
4800 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4801 assert(Op.getValueType() == MVT::i1 &&
4802 "Custom lowering only for i1 results");
4805 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4809 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4811 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4812 // Not FP? Not a fsel.
4813 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4814 !Op.getOperand(2).getValueType().isFloatingPoint())
4817 // We might be able to do better than this under some circumstances, but in
4818 // general, fsel-based lowering of select is a finite-math-only optimization.
4819 // For more information, see section F.3 of the 2.06 ISA specification.
4820 if (!DAG.getTarget().Options.NoInfsFPMath ||
4821 !DAG.getTarget().Options.NoNaNsFPMath)
4824 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4826 EVT ResVT = Op.getValueType();
4827 EVT CmpVT = Op.getOperand(0).getValueType();
4828 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4829 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4832 // If the RHS of the comparison is a 0.0, we don't need to do the
4833 // subtraction at all.
4835 if (isFloatingPointZero(RHS))
4837 default: break; // SETUO etc aren't handled by fsel.
4841 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4842 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4843 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4844 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4845 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4846 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4847 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4850 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4853 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4854 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4855 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4858 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4861 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4862 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4863 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4864 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4869 default: break; // SETUO etc aren't handled by fsel.
4873 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4874 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4875 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4876 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4877 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4878 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4879 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4880 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4883 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4884 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4885 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4886 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4889 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4890 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4891 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4892 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4895 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4896 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4897 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4898 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4901 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4902 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4903 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4904 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4909 // FIXME: Split this code up when LegalizeDAGTypes lands.
4910 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4912 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4913 SDValue Src = Op.getOperand(0);
4914 if (Src.getValueType() == MVT::f32)
4915 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4918 switch (Op.getSimpleValueType().SimpleTy) {
4919 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4921 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4922 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4927 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4928 "i64 FP_TO_UINT is supported only with FPCVT");
4929 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4935 // Convert the FP value to an int value through memory.
4936 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4937 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4938 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4939 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4940 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4942 // Emit a store to the stack slot.
4945 MachineFunction &MF = DAG.getMachineFunction();
4946 MachineMemOperand *MMO =
4947 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4948 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4949 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4950 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4953 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4954 MPI, false, false, 0);
4956 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4958 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4959 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4960 DAG.getConstant(4, FIPtr.getValueType()));
4961 MPI = MachinePointerInfo();
4964 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4965 false, false, false, 0);
4968 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4969 SelectionDAG &DAG) const {
4971 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4972 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4975 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4976 "UINT_TO_FP is supported only with FPCVT");
4978 // If we have FCFIDS, then use it when converting to single-precision.
4979 // Otherwise, convert to double-precision and then round.
4980 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4981 (Op.getOpcode() == ISD::UINT_TO_FP ?
4982 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
4983 (Op.getOpcode() == ISD::UINT_TO_FP ?
4984 PPCISD::FCFIDU : PPCISD::FCFID);
4985 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4986 MVT::f32 : MVT::f64;
4988 if (Op.getOperand(0).getValueType() == MVT::i64) {
4989 SDValue SINT = Op.getOperand(0);
4990 // When converting to single-precision, we actually need to convert
4991 // to double-precision first and then round to single-precision.
4992 // To avoid double-rounding effects during that operation, we have
4993 // to prepare the input operand. Bits that might be truncated when
4994 // converting to double-precision are replaced by a bit that won't
4995 // be lost at this stage, but is below the single-precision rounding
4998 // However, if -enable-unsafe-fp-math is in effect, accept double
4999 // rounding to avoid the extra overhead.
5000 if (Op.getValueType() == MVT::f32 &&
5001 !PPCSubTarget.hasFPCVT() &&
5002 !DAG.getTarget().Options.UnsafeFPMath) {
5004 // Twiddle input to make sure the low 11 bits are zero. (If this
5005 // is the case, we are guaranteed the value will fit into the 53 bit
5006 // mantissa of an IEEE double-precision value without rounding.)
5007 // If any of those low 11 bits were not zero originally, make sure
5008 // bit 12 (value 2048) is set instead, so that the final rounding
5009 // to single-precision gets the correct result.
5010 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5011 SINT, DAG.getConstant(2047, MVT::i64));
5012 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5013 Round, DAG.getConstant(2047, MVT::i64));
5014 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5015 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5016 Round, DAG.getConstant(-2048, MVT::i64));
5018 // However, we cannot use that value unconditionally: if the magnitude
5019 // of the input value is small, the bit-twiddling we did above might
5020 // end up visibly changing the output. Fortunately, in that case, we
5021 // don't need to twiddle bits since the original input will convert
5022 // exactly to double-precision floating-point already. Therefore,
5023 // construct a conditional to use the original value if the top 11
5024 // bits are all sign-bit copies, and use the rounded value computed
5026 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5027 SINT, DAG.getConstant(53, MVT::i32));
5028 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5029 Cond, DAG.getConstant(1, MVT::i64));
5030 Cond = DAG.getSetCC(dl, MVT::i32,
5031 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5033 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5036 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5037 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5039 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5040 FP = DAG.getNode(ISD::FP_ROUND, dl,
5041 MVT::f32, FP, DAG.getIntPtrConstant(0));
5045 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5046 "Unhandled INT_TO_FP type in custom expander!");
5047 // Since we only generate this in 64-bit mode, we can take advantage of
5048 // 64-bit registers. In particular, sign extend the input value into the
5049 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5050 // then lfd it and fcfid it.
5051 MachineFunction &MF = DAG.getMachineFunction();
5052 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5053 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5056 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5057 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5058 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5060 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5061 MachinePointerInfo::getFixedStack(FrameIdx),
5064 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5065 "Expected an i32 store");
5066 MachineMemOperand *MMO =
5067 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5068 MachineMemOperand::MOLoad, 4, 4);
5069 SDValue Ops[] = { Store, FIdx };
5070 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5071 PPCISD::LFIWZX : PPCISD::LFIWAX,
5072 dl, DAG.getVTList(MVT::f64, MVT::Other),
5073 Ops, 2, MVT::i32, MMO);
5075 assert(PPCSubTarget.isPPC64() &&
5076 "i32->FP without LFIWAX supported only on PPC64");
5078 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5079 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5081 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5084 // STD the extended value into the stack slot.
5085 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5086 MachinePointerInfo::getFixedStack(FrameIdx),
5089 // Load the value as a double.
5090 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5091 MachinePointerInfo::getFixedStack(FrameIdx),
5092 false, false, false, 0);
5095 // FCFID it and return it.
5096 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5097 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5098 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5102 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5103 SelectionDAG &DAG) const {
5106 The rounding mode is in bits 30:31 of FPSR, and has the following
5113 FLT_ROUNDS, on the other hand, expects the following:
5120 To perform the conversion, we do:
5121 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5124 MachineFunction &MF = DAG.getMachineFunction();
5125 EVT VT = Op.getValueType();
5126 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5127 SDValue MFFSreg, InFlag;
5129 // Save FP Control Word to register
5131 MVT::f64, // return register
5132 MVT::Glue // unused in this context
5134 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5136 // Save FP register to stack slot
5137 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5138 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5139 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5140 StackSlot, MachinePointerInfo(), false, false,0);
5142 // Load FP Control Word from low 32 bits of stack slot.
5143 SDValue Four = DAG.getConstant(4, PtrVT);
5144 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5145 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5146 false, false, false, 0);
5148 // Transform as necessary
5150 DAG.getNode(ISD::AND, dl, MVT::i32,
5151 CWD, DAG.getConstant(3, MVT::i32));
5153 DAG.getNode(ISD::SRL, dl, MVT::i32,
5154 DAG.getNode(ISD::AND, dl, MVT::i32,
5155 DAG.getNode(ISD::XOR, dl, MVT::i32,
5156 CWD, DAG.getConstant(3, MVT::i32)),
5157 DAG.getConstant(3, MVT::i32)),
5158 DAG.getConstant(1, MVT::i32));
5161 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5163 return DAG.getNode((VT.getSizeInBits() < 16 ?
5164 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5167 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5168 EVT VT = Op.getValueType();
5169 unsigned BitWidth = VT.getSizeInBits();
5171 assert(Op.getNumOperands() == 3 &&
5172 VT == Op.getOperand(1).getValueType() &&
5175 // Expand into a bunch of logical ops. Note that these ops
5176 // depend on the PPC behavior for oversized shift amounts.
5177 SDValue Lo = Op.getOperand(0);
5178 SDValue Hi = Op.getOperand(1);
5179 SDValue Amt = Op.getOperand(2);
5180 EVT AmtVT = Amt.getValueType();
5182 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5183 DAG.getConstant(BitWidth, AmtVT), Amt);
5184 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5185 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5186 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5187 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5188 DAG.getConstant(-BitWidth, AmtVT));
5189 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5190 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5191 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5192 SDValue OutOps[] = { OutLo, OutHi };
5193 return DAG.getMergeValues(OutOps, 2, dl);
5196 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5197 EVT VT = Op.getValueType();
5199 unsigned BitWidth = VT.getSizeInBits();
5200 assert(Op.getNumOperands() == 3 &&
5201 VT == Op.getOperand(1).getValueType() &&
5204 // Expand into a bunch of logical ops. Note that these ops
5205 // depend on the PPC behavior for oversized shift amounts.
5206 SDValue Lo = Op.getOperand(0);
5207 SDValue Hi = Op.getOperand(1);
5208 SDValue Amt = Op.getOperand(2);
5209 EVT AmtVT = Amt.getValueType();
5211 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5212 DAG.getConstant(BitWidth, AmtVT), Amt);
5213 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5214 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5215 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5216 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5217 DAG.getConstant(-BitWidth, AmtVT));
5218 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5219 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5220 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5221 SDValue OutOps[] = { OutLo, OutHi };
5222 return DAG.getMergeValues(OutOps, 2, dl);
5225 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5227 EVT VT = Op.getValueType();
5228 unsigned BitWidth = VT.getSizeInBits();
5229 assert(Op.getNumOperands() == 3 &&
5230 VT == Op.getOperand(1).getValueType() &&
5233 // Expand into a bunch of logical ops, followed by a select_cc.
5234 SDValue Lo = Op.getOperand(0);
5235 SDValue Hi = Op.getOperand(1);
5236 SDValue Amt = Op.getOperand(2);
5237 EVT AmtVT = Amt.getValueType();
5239 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5240 DAG.getConstant(BitWidth, AmtVT), Amt);
5241 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5242 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5243 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5244 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5245 DAG.getConstant(-BitWidth, AmtVT));
5246 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5247 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5248 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5249 Tmp4, Tmp6, ISD::SETLE);
5250 SDValue OutOps[] = { OutLo, OutHi };
5251 return DAG.getMergeValues(OutOps, 2, dl);
5254 //===----------------------------------------------------------------------===//
5255 // Vector related lowering.
5258 /// BuildSplatI - Build a canonical splati of Val with an element size of
5259 /// SplatSize. Cast the result to VT.
5260 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5261 SelectionDAG &DAG, SDLoc dl) {
5262 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5264 static const EVT VTys[] = { // canonical VT to use for each size.
5265 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5268 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5270 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5274 EVT CanonicalVT = VTys[SplatSize-1];
5276 // Build a canonical splat for this value.
5277 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5278 SmallVector<SDValue, 8> Ops;
5279 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5280 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5281 &Ops[0], Ops.size());
5282 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5285 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5286 /// specified intrinsic ID.
5287 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5288 SelectionDAG &DAG, SDLoc dl,
5289 EVT DestVT = MVT::Other) {
5290 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5291 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5292 DAG.getConstant(IID, MVT::i32), Op);
5295 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5296 /// specified intrinsic ID.
5297 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5298 SelectionDAG &DAG, SDLoc dl,
5299 EVT DestVT = MVT::Other) {
5300 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5301 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5302 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5305 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5306 /// specified intrinsic ID.
5307 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5308 SDValue Op2, SelectionDAG &DAG,
5309 SDLoc dl, EVT DestVT = MVT::Other) {
5310 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5311 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5312 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5316 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5317 /// amount. The result has the specified value type.
5318 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5319 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5320 // Force LHS/RHS to be the right type.
5321 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5322 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5325 for (unsigned i = 0; i != 16; ++i)
5327 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5328 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5331 // If this is a case we can't handle, return null and let the default
5332 // expansion code take care of it. If we CAN select this case, and if it
5333 // selects to a single instruction, return Op. Otherwise, if we can codegen
5334 // this case more efficiently than a constant pool load, lower it to the
5335 // sequence of ops that should be used.
5336 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5337 SelectionDAG &DAG) const {
5339 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5340 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5342 // Check if this is a splat of a constant value.
5343 APInt APSplatBits, APSplatUndef;
5344 unsigned SplatBitSize;
5346 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5347 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5350 unsigned SplatBits = APSplatBits.getZExtValue();
5351 unsigned SplatUndef = APSplatUndef.getZExtValue();
5352 unsigned SplatSize = SplatBitSize / 8;
5354 // First, handle single instruction cases.
5357 if (SplatBits == 0) {
5358 // Canonicalize all zero vectors to be v4i32.
5359 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5360 SDValue Z = DAG.getConstant(0, MVT::i32);
5361 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5362 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5367 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5368 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5370 if (SextVal >= -16 && SextVal <= 15)
5371 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5374 // Two instruction sequences.
5376 // If this value is in the range [-32,30] and is even, use:
5377 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5378 // If this value is in the range [17,31] and is odd, use:
5379 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5380 // If this value is in the range [-31,-17] and is odd, use:
5381 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5382 // Note the last two are three-instruction sequences.
5383 if (SextVal >= -32 && SextVal <= 31) {
5384 // To avoid having these optimizations undone by constant folding,
5385 // we convert to a pseudo that will be expanded later into one of
5387 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5388 EVT VT = Op.getValueType();
5389 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5390 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5391 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5394 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5395 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5397 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5398 // Make -1 and vspltisw -1:
5399 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5401 // Make the VSLW intrinsic, computing 0x8000_0000.
5402 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5405 // xor by OnesV to invert it.
5406 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5407 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5410 // Check to see if this is a wide variety of vsplti*, binop self cases.
5411 static const signed char SplatCsts[] = {
5412 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5413 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5416 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5417 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5418 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5419 int i = SplatCsts[idx];
5421 // Figure out what shift amount will be used by altivec if shifted by i in
5423 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5425 // vsplti + shl self.
5426 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5427 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5428 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5429 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5430 Intrinsic::ppc_altivec_vslw
5432 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5433 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5436 // vsplti + srl self.
5437 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5438 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5439 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5440 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5441 Intrinsic::ppc_altivec_vsrw
5443 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5444 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5447 // vsplti + sra self.
5448 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5449 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5450 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5451 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5452 Intrinsic::ppc_altivec_vsraw
5454 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5455 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5458 // vsplti + rol self.
5459 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5460 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5461 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5462 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5463 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5464 Intrinsic::ppc_altivec_vrlw
5466 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5467 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5470 // t = vsplti c, result = vsldoi t, t, 1
5471 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5472 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5473 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5475 // t = vsplti c, result = vsldoi t, t, 2
5476 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5477 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5478 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5480 // t = vsplti c, result = vsldoi t, t, 3
5481 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5482 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5483 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5490 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5491 /// the specified operations to build the shuffle.
5492 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5493 SDValue RHS, SelectionDAG &DAG,
5495 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5496 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5497 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5500 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5512 if (OpNum == OP_COPY) {
5513 if (LHSID == (1*9+2)*9+3) return LHS;
5514 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5518 SDValue OpLHS, OpRHS;
5519 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5520 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5524 default: llvm_unreachable("Unknown i32 permute!");
5526 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5527 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5528 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5529 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5532 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5533 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5534 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5535 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5538 for (unsigned i = 0; i != 16; ++i)
5539 ShufIdxs[i] = (i&3)+0;
5542 for (unsigned i = 0; i != 16; ++i)
5543 ShufIdxs[i] = (i&3)+4;
5546 for (unsigned i = 0; i != 16; ++i)
5547 ShufIdxs[i] = (i&3)+8;
5550 for (unsigned i = 0; i != 16; ++i)
5551 ShufIdxs[i] = (i&3)+12;
5554 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5556 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5558 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5560 EVT VT = OpLHS.getValueType();
5561 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5562 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5563 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5564 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5567 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5568 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5569 /// return the code it can be lowered into. Worst case, it can always be
5570 /// lowered into a vperm.
5571 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5572 SelectionDAG &DAG) const {
5574 SDValue V1 = Op.getOperand(0);
5575 SDValue V2 = Op.getOperand(1);
5576 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5577 EVT VT = Op.getValueType();
5579 // Cases that are handled by instructions that take permute immediates
5580 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5581 // selected by the instruction selector.
5582 if (V2.getOpcode() == ISD::UNDEF) {
5583 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5584 PPC::isSplatShuffleMask(SVOp, 2) ||
5585 PPC::isSplatShuffleMask(SVOp, 4) ||
5586 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5587 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5588 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5589 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5590 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5591 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5592 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5593 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5594 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5599 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5600 // and produce a fixed permutation. If any of these match, do not lower to
5602 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5603 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5604 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5605 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5606 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5607 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5608 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5609 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5610 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5613 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5614 // perfect shuffle table to emit an optimal matching sequence.
5615 ArrayRef<int> PermMask = SVOp->getMask();
5617 unsigned PFIndexes[4];
5618 bool isFourElementShuffle = true;
5619 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5620 unsigned EltNo = 8; // Start out undef.
5621 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5622 if (PermMask[i*4+j] < 0)
5623 continue; // Undef, ignore it.
5625 unsigned ByteSource = PermMask[i*4+j];
5626 if ((ByteSource & 3) != j) {
5627 isFourElementShuffle = false;
5632 EltNo = ByteSource/4;
5633 } else if (EltNo != ByteSource/4) {
5634 isFourElementShuffle = false;
5638 PFIndexes[i] = EltNo;
5641 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5642 // perfect shuffle vector to determine if it is cost effective to do this as
5643 // discrete instructions, or whether we should use a vperm.
5644 if (isFourElementShuffle) {
5645 // Compute the index in the perfect shuffle table.
5646 unsigned PFTableIndex =
5647 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5649 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5650 unsigned Cost = (PFEntry >> 30);
5652 // Determining when to avoid vperm is tricky. Many things affect the cost
5653 // of vperm, particularly how many times the perm mask needs to be computed.
5654 // For example, if the perm mask can be hoisted out of a loop or is already
5655 // used (perhaps because there are multiple permutes with the same shuffle
5656 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5657 // the loop requires an extra register.
5659 // As a compromise, we only emit discrete instructions if the shuffle can be
5660 // generated in 3 or fewer operations. When we have loop information
5661 // available, if this block is within a loop, we should avoid using vperm
5662 // for 3-operation perms and use a constant pool load instead.
5664 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5667 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5668 // vector that will get spilled to the constant pool.
5669 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5671 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5672 // that it is in input element units, not in bytes. Convert now.
5673 EVT EltVT = V1.getValueType().getVectorElementType();
5674 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5676 SmallVector<SDValue, 16> ResultMask;
5677 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5678 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5680 for (unsigned j = 0; j != BytesPerElement; ++j)
5681 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5685 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5686 &ResultMask[0], ResultMask.size());
5687 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5690 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5691 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5692 /// information about the intrinsic.
5693 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5695 unsigned IntrinsicID =
5696 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5699 switch (IntrinsicID) {
5700 default: return false;
5701 // Comparison predicates.
5702 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5703 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5704 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5705 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5706 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5707 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5708 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5709 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5710 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5711 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5712 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5713 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5714 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5716 // Normal Comparisons.
5717 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5718 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5719 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5720 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5721 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5722 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5723 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5724 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5725 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5726 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5727 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5728 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5729 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5734 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5735 /// lower, do it, otherwise return null.
5736 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5737 SelectionDAG &DAG) const {
5738 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5739 // opcode number of the comparison.
5743 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5744 return SDValue(); // Don't custom lower most intrinsics.
5746 // If this is a non-dot comparison, make the VCMP node and we are done.
5748 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5749 Op.getOperand(1), Op.getOperand(2),
5750 DAG.getConstant(CompareOpc, MVT::i32));
5751 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5754 // Create the PPCISD altivec 'dot' comparison node.
5756 Op.getOperand(2), // LHS
5757 Op.getOperand(3), // RHS
5758 DAG.getConstant(CompareOpc, MVT::i32)
5760 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5761 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5763 // Now that we have the comparison, emit a copy from the CR to a GPR.
5764 // This is flagged to the above dot comparison.
5765 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5766 DAG.getRegister(PPC::CR6, MVT::i32),
5767 CompNode.getValue(1));
5769 // Unpack the result based on how the target uses it.
5770 unsigned BitNo; // Bit # of CR6.
5771 bool InvertBit; // Invert result?
5772 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5773 default: // Can't happen, don't crash on invalid number though.
5774 case 0: // Return the value of the EQ bit of CR6.
5775 BitNo = 0; InvertBit = false;
5777 case 1: // Return the inverted value of the EQ bit of CR6.
5778 BitNo = 0; InvertBit = true;
5780 case 2: // Return the value of the LT bit of CR6.
5781 BitNo = 2; InvertBit = false;
5783 case 3: // Return the inverted value of the LT bit of CR6.
5784 BitNo = 2; InvertBit = true;
5788 // Shift the bit into the low position.
5789 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5790 DAG.getConstant(8-(3-BitNo), MVT::i32));
5792 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5793 DAG.getConstant(1, MVT::i32));
5795 // If we are supposed to, toggle the bit.
5797 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5798 DAG.getConstant(1, MVT::i32));
5802 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5803 SelectionDAG &DAG) const {
5805 // Create a stack slot that is 16-byte aligned.
5806 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5807 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5808 EVT PtrVT = getPointerTy();
5809 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5811 // Store the input value into Value#0 of the stack slot.
5812 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5813 Op.getOperand(0), FIdx, MachinePointerInfo(),
5816 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5817 false, false, false, 0);
5820 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5822 if (Op.getValueType() == MVT::v4i32) {
5823 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5825 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5826 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5828 SDValue RHSSwap = // = vrlw RHS, 16
5829 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5831 // Shrinkify inputs to v8i16.
5832 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5833 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5834 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5836 // Low parts multiplied together, generating 32-bit results (we ignore the
5838 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5839 LHS, RHS, DAG, dl, MVT::v4i32);
5841 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5842 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5843 // Shift the high parts up 16 bits.
5844 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5846 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5847 } else if (Op.getValueType() == MVT::v8i16) {
5848 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5850 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5852 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5853 LHS, RHS, Zero, DAG, dl);
5854 } else if (Op.getValueType() == MVT::v16i8) {
5855 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5857 // Multiply the even 8-bit parts, producing 16-bit sums.
5858 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5859 LHS, RHS, DAG, dl, MVT::v8i16);
5860 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5862 // Multiply the odd 8-bit parts, producing 16-bit sums.
5863 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5864 LHS, RHS, DAG, dl, MVT::v8i16);
5865 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5867 // Merge the results together.
5869 for (unsigned i = 0; i != 8; ++i) {
5871 Ops[i*2+1] = 2*i+1+16;
5873 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5875 llvm_unreachable("Unknown mul to lower!");
5879 /// LowerOperation - Provide custom lowering hooks for some operations.
5881 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5882 switch (Op.getOpcode()) {
5883 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5884 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5885 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5886 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5887 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5888 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5889 case ISD::SETCC: return LowerSETCC(Op, DAG);
5890 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5891 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5893 return LowerVASTART(Op, DAG, PPCSubTarget);
5896 return LowerVAARG(Op, DAG, PPCSubTarget);
5899 return LowerVACOPY(Op, DAG, PPCSubTarget);
5901 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5902 case ISD::DYNAMIC_STACKALLOC:
5903 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5905 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5906 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5908 case ISD::LOAD: return LowerLOAD(Op, DAG);
5909 case ISD::STORE: return LowerSTORE(Op, DAG);
5910 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
5911 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5912 case ISD::FP_TO_UINT:
5913 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5915 case ISD::UINT_TO_FP:
5916 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5917 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5919 // Lower 64-bit shifts.
5920 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5921 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5922 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5924 // Vector-related lowering.
5925 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5926 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5927 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5928 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5929 case ISD::MUL: return LowerMUL(Op, DAG);
5931 // For counter-based loop handling.
5932 case ISD::INTRINSIC_W_CHAIN: return SDValue();
5934 // Frame & Return address.
5935 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5936 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5940 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5941 SmallVectorImpl<SDValue>&Results,
5942 SelectionDAG &DAG) const {
5943 const TargetMachine &TM = getTargetMachine();
5945 switch (N->getOpcode()) {
5947 llvm_unreachable("Do not know how to custom type legalize this operation!");
5948 case ISD::INTRINSIC_W_CHAIN: {
5949 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
5950 Intrinsic::ppc_is_decremented_ctr_nonzero)
5953 assert(N->getValueType(0) == MVT::i1 &&
5954 "Unexpected result type for CTR decrement intrinsic");
5955 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
5956 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
5957 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
5960 Results.push_back(NewInt);
5961 Results.push_back(NewInt.getValue(1));
5965 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5966 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5969 EVT VT = N->getValueType(0);
5971 if (VT == MVT::i64) {
5972 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5974 Results.push_back(NewNode);
5975 Results.push_back(NewNode.getValue(1));
5979 case ISD::FP_ROUND_INREG: {
5980 assert(N->getValueType(0) == MVT::ppcf128);
5981 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5982 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5983 MVT::f64, N->getOperand(0),
5984 DAG.getIntPtrConstant(0));
5985 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5986 MVT::f64, N->getOperand(0),
5987 DAG.getIntPtrConstant(1));
5989 // Add the two halves of the long double in round-to-zero mode.
5990 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5992 // We know the low half is about to be thrown away, so just use something
5994 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5998 case ISD::FP_TO_SINT:
5999 // LowerFP_TO_INT() can only handle f32 and f64.
6000 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6002 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6008 //===----------------------------------------------------------------------===//
6009 // Other Lowering Code
6010 //===----------------------------------------------------------------------===//
6013 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6014 bool is64bit, unsigned BinOpcode) const {
6015 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6016 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6018 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6019 MachineFunction *F = BB->getParent();
6020 MachineFunction::iterator It = BB;
6023 unsigned dest = MI->getOperand(0).getReg();
6024 unsigned ptrA = MI->getOperand(1).getReg();
6025 unsigned ptrB = MI->getOperand(2).getReg();
6026 unsigned incr = MI->getOperand(3).getReg();
6027 DebugLoc dl = MI->getDebugLoc();
6029 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6030 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6031 F->insert(It, loopMBB);
6032 F->insert(It, exitMBB);
6033 exitMBB->splice(exitMBB->begin(), BB,
6034 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6035 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6037 MachineRegisterInfo &RegInfo = F->getRegInfo();
6038 unsigned TmpReg = (!BinOpcode) ? incr :
6039 RegInfo.createVirtualRegister(
6040 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6041 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6045 // fallthrough --> loopMBB
6046 BB->addSuccessor(loopMBB);
6049 // l[wd]arx dest, ptr
6050 // add r0, dest, incr
6051 // st[wd]cx. r0, ptr
6053 // fallthrough --> exitMBB
6055 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6056 .addReg(ptrA).addReg(ptrB);
6058 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6059 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6060 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6061 BuildMI(BB, dl, TII->get(PPC::BCC))
6062 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6063 BB->addSuccessor(loopMBB);
6064 BB->addSuccessor(exitMBB);
6073 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6074 MachineBasicBlock *BB,
6075 bool is8bit, // operation
6076 unsigned BinOpcode) const {
6077 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6078 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6079 // In 64 bit mode we have to use 64 bits for addresses, even though the
6080 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6081 // registers without caring whether they're 32 or 64, but here we're
6082 // doing actual arithmetic on the addresses.
6083 bool is64bit = PPCSubTarget.isPPC64();
6084 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6086 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6087 MachineFunction *F = BB->getParent();
6088 MachineFunction::iterator It = BB;
6091 unsigned dest = MI->getOperand(0).getReg();
6092 unsigned ptrA = MI->getOperand(1).getReg();
6093 unsigned ptrB = MI->getOperand(2).getReg();
6094 unsigned incr = MI->getOperand(3).getReg();
6095 DebugLoc dl = MI->getDebugLoc();
6097 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6098 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6099 F->insert(It, loopMBB);
6100 F->insert(It, exitMBB);
6101 exitMBB->splice(exitMBB->begin(), BB,
6102 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6103 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6105 MachineRegisterInfo &RegInfo = F->getRegInfo();
6106 const TargetRegisterClass *RC =
6107 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6108 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6109 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6110 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6111 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6112 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6113 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6114 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6115 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6116 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6117 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6118 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6119 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6121 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6125 // fallthrough --> loopMBB
6126 BB->addSuccessor(loopMBB);
6128 // The 4-byte load must be aligned, while a char or short may be
6129 // anywhere in the word. Hence all this nasty bookkeeping code.
6130 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6131 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6132 // xori shift, shift1, 24 [16]
6133 // rlwinm ptr, ptr1, 0, 0, 29
6134 // slw incr2, incr, shift
6135 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6136 // slw mask, mask2, shift
6138 // lwarx tmpDest, ptr
6139 // add tmp, tmpDest, incr2
6140 // andc tmp2, tmpDest, mask
6141 // and tmp3, tmp, mask
6142 // or tmp4, tmp3, tmp2
6145 // fallthrough --> exitMBB
6146 // srw dest, tmpDest, shift
6147 if (ptrA != ZeroReg) {
6148 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6149 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6150 .addReg(ptrA).addReg(ptrB);
6154 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6155 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6156 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6157 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6159 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6160 .addReg(Ptr1Reg).addImm(0).addImm(61);
6162 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6163 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6164 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6165 .addReg(incr).addReg(ShiftReg);
6167 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6169 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6170 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6172 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6173 .addReg(Mask2Reg).addReg(ShiftReg);
6176 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6177 .addReg(ZeroReg).addReg(PtrReg);
6179 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6180 .addReg(Incr2Reg).addReg(TmpDestReg);
6181 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6182 .addReg(TmpDestReg).addReg(MaskReg);
6183 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6184 .addReg(TmpReg).addReg(MaskReg);
6185 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6186 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6187 BuildMI(BB, dl, TII->get(PPC::STWCX))
6188 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6189 BuildMI(BB, dl, TII->get(PPC::BCC))
6190 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6191 BB->addSuccessor(loopMBB);
6192 BB->addSuccessor(exitMBB);
6197 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6202 llvm::MachineBasicBlock*
6203 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6204 MachineBasicBlock *MBB) const {
6205 DebugLoc DL = MI->getDebugLoc();
6206 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6208 MachineFunction *MF = MBB->getParent();
6209 MachineRegisterInfo &MRI = MF->getRegInfo();
6211 const BasicBlock *BB = MBB->getBasicBlock();
6212 MachineFunction::iterator I = MBB;
6216 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6217 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6219 unsigned DstReg = MI->getOperand(0).getReg();
6220 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6221 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6222 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6223 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6225 MVT PVT = getPointerTy();
6226 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6227 "Invalid Pointer Size!");
6228 // For v = setjmp(buf), we generate
6231 // SjLjSetup mainMBB
6237 // buf[LabelOffset] = LR
6241 // v = phi(main, restore)
6244 MachineBasicBlock *thisMBB = MBB;
6245 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6246 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6247 MF->insert(I, mainMBB);
6248 MF->insert(I, sinkMBB);
6250 MachineInstrBuilder MIB;
6252 // Transfer the remainder of BB and its successor edges to sinkMBB.
6253 sinkMBB->splice(sinkMBB->begin(), MBB,
6254 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6255 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6257 // Note that the structure of the jmp_buf used here is not compatible
6258 // with that used by libc, and is not designed to be. Specifically, it
6259 // stores only those 'reserved' registers that LLVM does not otherwise
6260 // understand how to spill. Also, by convention, by the time this
6261 // intrinsic is called, Clang has already stored the frame address in the
6262 // first slot of the buffer and stack address in the third. Following the
6263 // X86 target code, we'll store the jump address in the second slot. We also
6264 // need to save the TOC pointer (R2) to handle jumps between shared
6265 // libraries, and that will be stored in the fourth slot. The thread
6266 // identifier (R13) is not affected.
6269 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6270 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6271 const int64_t BPOffset = 4 * PVT.getStoreSize();
6273 // Prepare IP either in reg.
6274 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6275 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6276 unsigned BufReg = MI->getOperand(1).getReg();
6278 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6279 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6283 MIB.setMemRefs(MMOBegin, MMOEnd);
6286 // Naked functions never have a base pointer, and so we use r1. For all
6287 // other functions, this decision must be delayed until during PEI.
6289 if (MF->getFunction()->getAttributes().hasAttribute(
6290 AttributeSet::FunctionIndex, Attribute::Naked))
6291 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6293 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6295 MIB = BuildMI(*thisMBB, MI, DL,
6296 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6300 MIB.setMemRefs(MMOBegin, MMOEnd);
6303 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6304 const PPCRegisterInfo *TRI =
6305 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6306 MIB.addRegMask(TRI->getNoPreservedMask());
6308 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6310 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6312 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6314 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6315 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6319 MIB = BuildMI(mainMBB, DL,
6320 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6323 if (PPCSubTarget.isPPC64()) {
6324 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6326 .addImm(LabelOffset)
6329 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6331 .addImm(LabelOffset)
6335 MIB.setMemRefs(MMOBegin, MMOEnd);
6337 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6338 mainMBB->addSuccessor(sinkMBB);
6341 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6342 TII->get(PPC::PHI), DstReg)
6343 .addReg(mainDstReg).addMBB(mainMBB)
6344 .addReg(restoreDstReg).addMBB(thisMBB);
6346 MI->eraseFromParent();
6351 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6352 MachineBasicBlock *MBB) const {
6353 DebugLoc DL = MI->getDebugLoc();
6354 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6356 MachineFunction *MF = MBB->getParent();
6357 MachineRegisterInfo &MRI = MF->getRegInfo();
6360 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6361 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6363 MVT PVT = getPointerTy();
6364 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6365 "Invalid Pointer Size!");
6367 const TargetRegisterClass *RC =
6368 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6369 unsigned Tmp = MRI.createVirtualRegister(RC);
6370 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6371 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6372 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6373 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6375 MachineInstrBuilder MIB;
6377 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6378 const int64_t SPOffset = 2 * PVT.getStoreSize();
6379 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6380 const int64_t BPOffset = 4 * PVT.getStoreSize();
6382 unsigned BufReg = MI->getOperand(0).getReg();
6384 // Reload FP (the jumped-to function may not have had a
6385 // frame pointer, and if so, then its r31 will be restored
6387 if (PVT == MVT::i64) {
6388 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6392 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6396 MIB.setMemRefs(MMOBegin, MMOEnd);
6399 if (PVT == MVT::i64) {
6400 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6401 .addImm(LabelOffset)
6404 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6405 .addImm(LabelOffset)
6408 MIB.setMemRefs(MMOBegin, MMOEnd);
6411 if (PVT == MVT::i64) {
6412 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6416 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6420 MIB.setMemRefs(MMOBegin, MMOEnd);
6423 if (PVT == MVT::i64) {
6424 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6428 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6432 MIB.setMemRefs(MMOBegin, MMOEnd);
6435 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6436 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6440 MIB.setMemRefs(MMOBegin, MMOEnd);
6444 BuildMI(*MBB, MI, DL,
6445 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6446 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6448 MI->eraseFromParent();
6453 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6454 MachineBasicBlock *BB) const {
6455 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6456 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6457 return emitEHSjLjSetJmp(MI, BB);
6458 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6459 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6460 return emitEHSjLjLongJmp(MI, BB);
6463 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6465 // To "insert" these instructions we actually have to insert their
6466 // control-flow patterns.
6467 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6468 MachineFunction::iterator It = BB;
6471 MachineFunction *F = BB->getParent();
6473 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6474 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6475 MI->getOpcode() == PPC::SELECT_I4 ||
6476 MI->getOpcode() == PPC::SELECT_I8)) {
6477 SmallVector<MachineOperand, 2> Cond;
6478 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6479 MI->getOpcode() == PPC::SELECT_CC_I8)
6480 Cond.push_back(MI->getOperand(4));
6482 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6483 Cond.push_back(MI->getOperand(1));
6485 DebugLoc dl = MI->getDebugLoc();
6486 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6487 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6488 Cond, MI->getOperand(2).getReg(),
6489 MI->getOperand(3).getReg());
6490 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6491 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6492 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6493 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6494 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6495 MI->getOpcode() == PPC::SELECT_I4 ||
6496 MI->getOpcode() == PPC::SELECT_I8 ||
6497 MI->getOpcode() == PPC::SELECT_F4 ||
6498 MI->getOpcode() == PPC::SELECT_F8 ||
6499 MI->getOpcode() == PPC::SELECT_VRRC) {
6500 // The incoming instruction knows the destination vreg to set, the
6501 // condition code register to branch on, the true/false values to
6502 // select between, and a branch opcode to use.
6507 // cmpTY ccX, r1, r2
6509 // fallthrough --> copy0MBB
6510 MachineBasicBlock *thisMBB = BB;
6511 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6512 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6513 DebugLoc dl = MI->getDebugLoc();
6514 F->insert(It, copy0MBB);
6515 F->insert(It, sinkMBB);
6517 // Transfer the remainder of BB and its successor edges to sinkMBB.
6518 sinkMBB->splice(sinkMBB->begin(), BB,
6519 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6520 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6522 // Next, add the true and fallthrough blocks as its successors.
6523 BB->addSuccessor(copy0MBB);
6524 BB->addSuccessor(sinkMBB);
6526 if (MI->getOpcode() == PPC::SELECT_I4 ||
6527 MI->getOpcode() == PPC::SELECT_I8 ||
6528 MI->getOpcode() == PPC::SELECT_F4 ||
6529 MI->getOpcode() == PPC::SELECT_F8 ||
6530 MI->getOpcode() == PPC::SELECT_VRRC) {
6531 BuildMI(BB, dl, TII->get(PPC::BC))
6532 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6534 unsigned SelectPred = MI->getOperand(4).getImm();
6535 BuildMI(BB, dl, TII->get(PPC::BCC))
6536 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6540 // %FalseValue = ...
6541 // # fallthrough to sinkMBB
6544 // Update machine-CFG edges
6545 BB->addSuccessor(sinkMBB);
6548 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6551 BuildMI(*BB, BB->begin(), dl,
6552 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6553 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6554 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6556 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6557 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6558 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6559 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6560 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6561 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6562 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6563 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6565 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6566 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6567 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6568 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6569 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6570 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6571 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6572 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6574 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6575 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6576 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6577 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6578 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6579 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6580 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6581 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6583 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6584 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6585 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6586 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6587 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6588 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6589 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6590 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6592 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6593 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6594 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6595 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6596 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6597 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6598 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6599 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6601 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6602 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6603 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6604 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6605 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6606 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6607 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6608 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6610 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6611 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6612 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6613 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6614 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6615 BB = EmitAtomicBinary(MI, BB, false, 0);
6616 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6617 BB = EmitAtomicBinary(MI, BB, true, 0);
6619 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6620 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6621 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6623 unsigned dest = MI->getOperand(0).getReg();
6624 unsigned ptrA = MI->getOperand(1).getReg();
6625 unsigned ptrB = MI->getOperand(2).getReg();
6626 unsigned oldval = MI->getOperand(3).getReg();
6627 unsigned newval = MI->getOperand(4).getReg();
6628 DebugLoc dl = MI->getDebugLoc();
6630 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6631 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6632 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6633 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6634 F->insert(It, loop1MBB);
6635 F->insert(It, loop2MBB);
6636 F->insert(It, midMBB);
6637 F->insert(It, exitMBB);
6638 exitMBB->splice(exitMBB->begin(), BB,
6639 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6640 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6644 // fallthrough --> loopMBB
6645 BB->addSuccessor(loop1MBB);
6648 // l[wd]arx dest, ptr
6649 // cmp[wd] dest, oldval
6652 // st[wd]cx. newval, ptr
6656 // st[wd]cx. dest, ptr
6659 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6660 .addReg(ptrA).addReg(ptrB);
6661 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6662 .addReg(oldval).addReg(dest);
6663 BuildMI(BB, dl, TII->get(PPC::BCC))
6664 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6665 BB->addSuccessor(loop2MBB);
6666 BB->addSuccessor(midMBB);
6669 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6670 .addReg(newval).addReg(ptrA).addReg(ptrB);
6671 BuildMI(BB, dl, TII->get(PPC::BCC))
6672 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6673 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6674 BB->addSuccessor(loop1MBB);
6675 BB->addSuccessor(exitMBB);
6678 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6679 .addReg(dest).addReg(ptrA).addReg(ptrB);
6680 BB->addSuccessor(exitMBB);
6685 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6686 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6687 // We must use 64-bit registers for addresses when targeting 64-bit,
6688 // since we're actually doing arithmetic on them. Other registers
6690 bool is64bit = PPCSubTarget.isPPC64();
6691 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6693 unsigned dest = MI->getOperand(0).getReg();
6694 unsigned ptrA = MI->getOperand(1).getReg();
6695 unsigned ptrB = MI->getOperand(2).getReg();
6696 unsigned oldval = MI->getOperand(3).getReg();
6697 unsigned newval = MI->getOperand(4).getReg();
6698 DebugLoc dl = MI->getDebugLoc();
6700 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6701 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6702 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6703 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6704 F->insert(It, loop1MBB);
6705 F->insert(It, loop2MBB);
6706 F->insert(It, midMBB);
6707 F->insert(It, exitMBB);
6708 exitMBB->splice(exitMBB->begin(), BB,
6709 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6710 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6712 MachineRegisterInfo &RegInfo = F->getRegInfo();
6713 const TargetRegisterClass *RC =
6714 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6715 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6716 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6717 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6718 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6719 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6720 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6721 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6722 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6723 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6724 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6725 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6726 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6727 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6728 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6730 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6731 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6734 // fallthrough --> loopMBB
6735 BB->addSuccessor(loop1MBB);
6737 // The 4-byte load must be aligned, while a char or short may be
6738 // anywhere in the word. Hence all this nasty bookkeeping code.
6739 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6740 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6741 // xori shift, shift1, 24 [16]
6742 // rlwinm ptr, ptr1, 0, 0, 29
6743 // slw newval2, newval, shift
6744 // slw oldval2, oldval,shift
6745 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6746 // slw mask, mask2, shift
6747 // and newval3, newval2, mask
6748 // and oldval3, oldval2, mask
6750 // lwarx tmpDest, ptr
6751 // and tmp, tmpDest, mask
6752 // cmpw tmp, oldval3
6755 // andc tmp2, tmpDest, mask
6756 // or tmp4, tmp2, newval3
6761 // stwcx. tmpDest, ptr
6763 // srw dest, tmpDest, shift
6764 if (ptrA != ZeroReg) {
6765 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6766 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6767 .addReg(ptrA).addReg(ptrB);
6771 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6772 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6773 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6774 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6776 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6777 .addReg(Ptr1Reg).addImm(0).addImm(61);
6779 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6780 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6781 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6782 .addReg(newval).addReg(ShiftReg);
6783 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6784 .addReg(oldval).addReg(ShiftReg);
6786 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6788 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6789 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6790 .addReg(Mask3Reg).addImm(65535);
6792 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6793 .addReg(Mask2Reg).addReg(ShiftReg);
6794 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6795 .addReg(NewVal2Reg).addReg(MaskReg);
6796 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6797 .addReg(OldVal2Reg).addReg(MaskReg);
6800 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6801 .addReg(ZeroReg).addReg(PtrReg);
6802 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6803 .addReg(TmpDestReg).addReg(MaskReg);
6804 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6805 .addReg(TmpReg).addReg(OldVal3Reg);
6806 BuildMI(BB, dl, TII->get(PPC::BCC))
6807 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6808 BB->addSuccessor(loop2MBB);
6809 BB->addSuccessor(midMBB);
6812 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6813 .addReg(TmpDestReg).addReg(MaskReg);
6814 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6815 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6816 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6817 .addReg(ZeroReg).addReg(PtrReg);
6818 BuildMI(BB, dl, TII->get(PPC::BCC))
6819 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6820 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6821 BB->addSuccessor(loop1MBB);
6822 BB->addSuccessor(exitMBB);
6825 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6826 .addReg(ZeroReg).addReg(PtrReg);
6827 BB->addSuccessor(exitMBB);
6832 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6834 } else if (MI->getOpcode() == PPC::FADDrtz) {
6835 // This pseudo performs an FADD with rounding mode temporarily forced
6836 // to round-to-zero. We emit this via custom inserter since the FPSCR
6837 // is not modeled at the SelectionDAG level.
6838 unsigned Dest = MI->getOperand(0).getReg();
6839 unsigned Src1 = MI->getOperand(1).getReg();
6840 unsigned Src2 = MI->getOperand(2).getReg();
6841 DebugLoc dl = MI->getDebugLoc();
6843 MachineRegisterInfo &RegInfo = F->getRegInfo();
6844 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6846 // Save FPSCR value.
6847 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6849 // Set rounding mode to round-to-zero.
6850 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6851 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6853 // Perform addition.
6854 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6856 // Restore FPSCR value.
6857 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6858 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6859 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6860 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6861 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6862 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6863 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6864 PPC::ANDIo8 : PPC::ANDIo;
6865 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6866 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6868 MachineRegisterInfo &RegInfo = F->getRegInfo();
6869 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6870 &PPC::GPRCRegClass :
6871 &PPC::G8RCRegClass);
6873 DebugLoc dl = MI->getDebugLoc();
6874 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6875 .addReg(MI->getOperand(1).getReg()).addImm(1);
6876 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6877 MI->getOperand(0).getReg())
6878 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6880 llvm_unreachable("Unexpected instr type to insert");
6883 MI->eraseFromParent(); // The pseudo instruction is gone now.
6887 //===----------------------------------------------------------------------===//
6888 // Target Optimization Hooks
6889 //===----------------------------------------------------------------------===//
6891 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6892 DAGCombinerInfo &DCI) const {
6893 if (DCI.isAfterLegalizeVectorOps())
6896 EVT VT = Op.getValueType();
6898 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6899 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6900 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6902 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6903 // For the reciprocal, we need to find the zero of the function:
6904 // F(X) = A X - 1 [which has a zero at X = 1/A]
6906 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6907 // does not require additional intermediate precision]
6909 // Convergence is quadratic, so we essentially double the number of digits
6910 // correct after every iteration. The minimum architected relative
6911 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6912 // 23 digits and double has 52 digits.
6913 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6914 if (VT.getScalarType() == MVT::f64)
6917 SelectionDAG &DAG = DCI.DAG;
6921 DAG.getConstantFP(1.0, VT.getScalarType());
6922 if (VT.isVector()) {
6923 assert(VT.getVectorNumElements() == 4 &&
6924 "Unknown vector type");
6925 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6926 FPOne, FPOne, FPOne, FPOne);
6929 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6930 DCI.AddToWorklist(Est.getNode());
6932 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6933 for (int i = 0; i < Iterations; ++i) {
6934 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6935 DCI.AddToWorklist(NewEst.getNode());
6937 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6938 DCI.AddToWorklist(NewEst.getNode());
6940 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6941 DCI.AddToWorklist(NewEst.getNode());
6943 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6944 DCI.AddToWorklist(Est.getNode());
6953 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6954 DAGCombinerInfo &DCI) const {
6955 if (DCI.isAfterLegalizeVectorOps())
6958 EVT VT = Op.getValueType();
6960 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6961 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6962 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6964 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6965 // For the reciprocal sqrt, we need to find the zero of the function:
6966 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6968 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6969 // As a result, we precompute A/2 prior to the iteration loop.
6971 // Convergence is quadratic, so we essentially double the number of digits
6972 // correct after every iteration. The minimum architected relative
6973 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6974 // 23 digits and double has 52 digits.
6975 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6976 if (VT.getScalarType() == MVT::f64)
6979 SelectionDAG &DAG = DCI.DAG;
6982 SDValue FPThreeHalves =
6983 DAG.getConstantFP(1.5, VT.getScalarType());
6984 if (VT.isVector()) {
6985 assert(VT.getVectorNumElements() == 4 &&
6986 "Unknown vector type");
6987 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6988 FPThreeHalves, FPThreeHalves,
6989 FPThreeHalves, FPThreeHalves);
6992 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
6993 DCI.AddToWorklist(Est.getNode());
6995 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
6996 // this entire sequence requires only one FP constant.
6997 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
6998 DCI.AddToWorklist(HalfArg.getNode());
7000 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7001 DCI.AddToWorklist(HalfArg.getNode());
7003 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7004 for (int i = 0; i < Iterations; ++i) {
7005 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7006 DCI.AddToWorklist(NewEst.getNode());
7008 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7009 DCI.AddToWorklist(NewEst.getNode());
7011 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7012 DCI.AddToWorklist(NewEst.getNode());
7014 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7015 DCI.AddToWorklist(Est.getNode());
7024 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7025 // not enforce equality of the chain operands.
7026 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7027 unsigned Bytes, int Dist,
7028 SelectionDAG &DAG) {
7029 EVT VT = LS->getMemoryVT();
7030 if (VT.getSizeInBits() / 8 != Bytes)
7033 SDValue Loc = LS->getBasePtr();
7034 SDValue BaseLoc = Base->getBasePtr();
7035 if (Loc.getOpcode() == ISD::FrameIndex) {
7036 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7038 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7039 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7040 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7041 int FS = MFI->getObjectSize(FI);
7042 int BFS = MFI->getObjectSize(BFI);
7043 if (FS != BFS || FS != (int)Bytes) return false;
7044 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7048 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7049 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7052 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7053 const GlobalValue *GV1 = NULL;
7054 const GlobalValue *GV2 = NULL;
7055 int64_t Offset1 = 0;
7056 int64_t Offset2 = 0;
7057 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7058 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7059 if (isGA1 && isGA2 && GV1 == GV2)
7060 return Offset1 == (Offset2 + Dist*Bytes);
7064 // Return true is there is a nearyby consecutive load to the one provided
7065 // (regardless of alignment). We search up and down the chain, looking though
7066 // token factors and other loads (but nothing else). As a result, a true
7067 // results indicates that it is safe to create a new consecutive load adjacent
7068 // to the load provided.
7069 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7070 SDValue Chain = LD->getChain();
7071 EVT VT = LD->getMemoryVT();
7073 SmallSet<SDNode *, 16> LoadRoots;
7074 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7075 SmallSet<SDNode *, 16> Visited;
7077 // First, search up the chain, branching to follow all token-factor operands.
7078 // If we find a consecutive load, then we're done, otherwise, record all
7079 // nodes just above the top-level loads and token factors.
7080 while (!Queue.empty()) {
7081 SDNode *ChainNext = Queue.pop_back_val();
7082 if (!Visited.insert(ChainNext))
7085 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7086 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7089 if (!Visited.count(ChainLD->getChain().getNode()))
7090 Queue.push_back(ChainLD->getChain().getNode());
7091 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7092 for (SDNode::op_iterator O = ChainNext->op_begin(),
7093 OE = ChainNext->op_end(); O != OE; ++O)
7094 if (!Visited.count(O->getNode()))
7095 Queue.push_back(O->getNode());
7097 LoadRoots.insert(ChainNext);
7100 // Second, search down the chain, starting from the top-level nodes recorded
7101 // in the first phase. These top-level nodes are the nodes just above all
7102 // loads and token factors. Starting with their uses, recursively look though
7103 // all loads (just the chain uses) and token factors to find a consecutive
7108 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7109 IE = LoadRoots.end(); I != IE; ++I) {
7110 Queue.push_back(*I);
7112 while (!Queue.empty()) {
7113 SDNode *LoadRoot = Queue.pop_back_val();
7114 if (!Visited.insert(LoadRoot))
7117 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7118 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7121 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7122 UE = LoadRoot->use_end(); UI != UE; ++UI)
7123 if (((isa<LoadSDNode>(*UI) &&
7124 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7125 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7126 Queue.push_back(*UI);
7133 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7134 DAGCombinerInfo &DCI) const {
7135 SelectionDAG &DAG = DCI.DAG;
7138 assert(PPCSubTarget.useCRBits() &&
7139 "Expecting to be tracking CR bits");
7140 // If we're tracking CR bits, we need to be careful that we don't have:
7141 // trunc(binary-ops(zext(x), zext(y)))
7143 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7144 // such that we're unnecessarily moving things into GPRs when it would be
7145 // better to keep them in CR bits.
7147 // Note that trunc here can be an actual i1 trunc, or can be the effective
7148 // truncation that comes from a setcc or select_cc.
7149 if (N->getOpcode() == ISD::TRUNCATE &&
7150 N->getValueType(0) != MVT::i1)
7153 if (N->getOperand(0).getValueType() != MVT::i32 &&
7154 N->getOperand(0).getValueType() != MVT::i64)
7157 if (N->getOpcode() == ISD::SETCC ||
7158 N->getOpcode() == ISD::SELECT_CC) {
7159 // If we're looking at a comparison, then we need to make sure that the
7160 // high bits (all except for the first) don't matter the result.
7162 cast<CondCodeSDNode>(N->getOperand(
7163 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7164 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7166 if (ISD::isSignedIntSetCC(CC)) {
7167 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7168 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7170 } else if (ISD::isUnsignedIntSetCC(CC)) {
7171 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7172 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7173 !DAG.MaskedValueIsZero(N->getOperand(1),
7174 APInt::getHighBitsSet(OpBits, OpBits-1)))
7177 // This is neither a signed nor an unsigned comparison, just make sure
7178 // that the high bits are equal.
7179 APInt Op1Zero, Op1One;
7180 APInt Op2Zero, Op2One;
7181 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7182 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7184 // We don't really care about what is known about the first bit (if
7185 // anything), so clear it in all masks prior to comparing them.
7186 Op1Zero.clearBit(0); Op1One.clearBit(0);
7187 Op2Zero.clearBit(0); Op2One.clearBit(0);
7189 if (Op1Zero != Op2Zero || Op1One != Op2One)
7194 // We now know that the higher-order bits are irrelevant, we just need to
7195 // make sure that all of the intermediate operations are bit operations, and
7196 // all inputs are extensions.
7197 if (N->getOperand(0).getOpcode() != ISD::AND &&
7198 N->getOperand(0).getOpcode() != ISD::OR &&
7199 N->getOperand(0).getOpcode() != ISD::XOR &&
7200 N->getOperand(0).getOpcode() != ISD::SELECT &&
7201 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7202 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7203 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7204 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7205 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7208 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7209 N->getOperand(1).getOpcode() != ISD::AND &&
7210 N->getOperand(1).getOpcode() != ISD::OR &&
7211 N->getOperand(1).getOpcode() != ISD::XOR &&
7212 N->getOperand(1).getOpcode() != ISD::SELECT &&
7213 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7214 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7215 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7216 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7217 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7220 SmallVector<SDValue, 4> Inputs;
7221 SmallVector<SDValue, 8> BinOps, PromOps;
7222 SmallPtrSet<SDNode *, 16> Visited;
7224 for (unsigned i = 0; i < 2; ++i) {
7225 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7226 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7227 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7228 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7229 isa<ConstantSDNode>(N->getOperand(i)))
7230 Inputs.push_back(N->getOperand(i));
7232 BinOps.push_back(N->getOperand(i));
7234 if (N->getOpcode() == ISD::TRUNCATE)
7238 // Visit all inputs, collect all binary operations (and, or, xor and
7239 // select) that are all fed by extensions.
7240 while (!BinOps.empty()) {
7241 SDValue BinOp = BinOps.back();
7244 if (!Visited.insert(BinOp.getNode()))
7247 PromOps.push_back(BinOp);
7249 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7250 // The condition of the select is not promoted.
7251 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7253 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7256 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7257 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7258 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7259 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7260 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7261 Inputs.push_back(BinOp.getOperand(i));
7262 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7263 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7264 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7265 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7266 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7267 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7268 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7269 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7270 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7271 BinOps.push_back(BinOp.getOperand(i));
7273 // We have an input that is not an extension or another binary
7274 // operation; we'll abort this transformation.
7280 // Make sure that this is a self-contained cluster of operations (which
7281 // is not quite the same thing as saying that everything has only one
7283 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7284 if (isa<ConstantSDNode>(Inputs[i]))
7287 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7288 UE = Inputs[i].getNode()->use_end();
7291 if (User != N && !Visited.count(User))
7294 // Make sure that we're not going to promote the non-output-value
7295 // operand(s) or SELECT or SELECT_CC.
7296 // FIXME: Although we could sometimes handle this, and it does occur in
7297 // practice that one of the condition inputs to the select is also one of
7298 // the outputs, we currently can't deal with this.
7299 if (User->getOpcode() == ISD::SELECT) {
7300 if (User->getOperand(0) == Inputs[i])
7302 } else if (User->getOpcode() == ISD::SELECT_CC) {
7303 if (User->getOperand(0) == Inputs[i] ||
7304 User->getOperand(1) == Inputs[i])
7310 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7311 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7312 UE = PromOps[i].getNode()->use_end();
7315 if (User != N && !Visited.count(User))
7318 // Make sure that we're not going to promote the non-output-value
7319 // operand(s) or SELECT or SELECT_CC.
7320 // FIXME: Although we could sometimes handle this, and it does occur in
7321 // practice that one of the condition inputs to the select is also one of
7322 // the outputs, we currently can't deal with this.
7323 if (User->getOpcode() == ISD::SELECT) {
7324 if (User->getOperand(0) == PromOps[i])
7326 } else if (User->getOpcode() == ISD::SELECT_CC) {
7327 if (User->getOperand(0) == PromOps[i] ||
7328 User->getOperand(1) == PromOps[i])
7334 // Replace all inputs with the extension operand.
7335 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7336 // Constants may have users outside the cluster of to-be-promoted nodes,
7337 // and so we need to replace those as we do the promotions.
7338 if (isa<ConstantSDNode>(Inputs[i]))
7341 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7344 // Replace all operations (these are all the same, but have a different
7345 // (i1) return type). DAG.getNode will validate that the types of
7346 // a binary operator match, so go through the list in reverse so that
7347 // we've likely promoted both operands first. Any intermediate truncations or
7348 // extensions disappear.
7349 while (!PromOps.empty()) {
7350 SDValue PromOp = PromOps.back();
7353 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7354 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7355 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7356 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7357 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7358 PromOp.getOperand(0).getValueType() != MVT::i1) {
7359 // The operand is not yet ready (see comment below).
7360 PromOps.insert(PromOps.begin(), PromOp);
7364 SDValue RepValue = PromOp.getOperand(0);
7365 if (isa<ConstantSDNode>(RepValue))
7366 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7368 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7373 switch (PromOp.getOpcode()) {
7374 default: C = 0; break;
7375 case ISD::SELECT: C = 1; break;
7376 case ISD::SELECT_CC: C = 2; break;
7379 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7380 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7381 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7382 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7383 // The to-be-promoted operands of this node have not yet been
7384 // promoted (this should be rare because we're going through the
7385 // list backward, but if one of the operands has several users in
7386 // this cluster of to-be-promoted nodes, it is possible).
7387 PromOps.insert(PromOps.begin(), PromOp);
7391 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7392 PromOp.getNode()->op_end());
7394 // If there are any constant inputs, make sure they're replaced now.
7395 for (unsigned i = 0; i < 2; ++i)
7396 if (isa<ConstantSDNode>(Ops[C+i]))
7397 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7399 DAG.ReplaceAllUsesOfValueWith(PromOp,
7400 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7401 Ops.data(), Ops.size()));
7404 // Now we're left with the initial truncation itself.
7405 if (N->getOpcode() == ISD::TRUNCATE)
7406 return N->getOperand(0);
7408 // Otherwise, this is a comparison. The operands to be compared have just
7409 // changed type (to i1), but everything else is the same.
7410 return SDValue(N, 0);
7413 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7414 DAGCombinerInfo &DCI) const {
7415 SelectionDAG &DAG = DCI.DAG;
7418 // If we're tracking CR bits, we need to be careful that we don't have:
7419 // zext(binary-ops(trunc(x), trunc(y)))
7421 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7422 // such that we're unnecessarily moving things into CR bits that can more
7423 // efficiently stay in GPRs. Note that if we're not certain that the high
7424 // bits are set as required by the final extension, we still may need to do
7425 // some masking to get the proper behavior.
7427 // This same functionality is important on PPC64 when dealing with
7428 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7429 // the return values of functions. Because it is so similar, it is handled
7432 if (N->getValueType(0) != MVT::i32 &&
7433 N->getValueType(0) != MVT::i64)
7436 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7437 PPCSubTarget.useCRBits()) ||
7438 (N->getOperand(0).getValueType() == MVT::i32 &&
7439 PPCSubTarget.isPPC64())))
7442 if (N->getOperand(0).getOpcode() != ISD::AND &&
7443 N->getOperand(0).getOpcode() != ISD::OR &&
7444 N->getOperand(0).getOpcode() != ISD::XOR &&
7445 N->getOperand(0).getOpcode() != ISD::SELECT &&
7446 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7449 SmallVector<SDValue, 4> Inputs;
7450 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7451 SmallPtrSet<SDNode *, 16> Visited;
7453 // Visit all inputs, collect all binary operations (and, or, xor and
7454 // select) that are all fed by truncations.
7455 while (!BinOps.empty()) {
7456 SDValue BinOp = BinOps.back();
7459 if (!Visited.insert(BinOp.getNode()))
7462 PromOps.push_back(BinOp);
7464 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7465 // The condition of the select is not promoted.
7466 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7468 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7471 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7472 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7473 Inputs.push_back(BinOp.getOperand(i));
7474 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7475 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7476 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7477 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7478 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7479 BinOps.push_back(BinOp.getOperand(i));
7481 // We have an input that is not a truncation or another binary
7482 // operation; we'll abort this transformation.
7488 // Make sure that this is a self-contained cluster of operations (which
7489 // is not quite the same thing as saying that everything has only one
7491 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7492 if (isa<ConstantSDNode>(Inputs[i]))
7495 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7496 UE = Inputs[i].getNode()->use_end();
7499 if (User != N && !Visited.count(User))
7502 // Make sure that we're not going to promote the non-output-value
7503 // operand(s) or SELECT or SELECT_CC.
7504 // FIXME: Although we could sometimes handle this, and it does occur in
7505 // practice that one of the condition inputs to the select is also one of
7506 // the outputs, we currently can't deal with this.
7507 if (User->getOpcode() == ISD::SELECT) {
7508 if (User->getOperand(0) == Inputs[i])
7510 } else if (User->getOpcode() == ISD::SELECT_CC) {
7511 if (User->getOperand(0) == Inputs[i] ||
7512 User->getOperand(1) == Inputs[i])
7518 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7519 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7520 UE = PromOps[i].getNode()->use_end();
7523 if (User != N && !Visited.count(User))
7526 // Make sure that we're not going to promote the non-output-value
7527 // operand(s) or SELECT or SELECT_CC.
7528 // FIXME: Although we could sometimes handle this, and it does occur in
7529 // practice that one of the condition inputs to the select is also one of
7530 // the outputs, we currently can't deal with this.
7531 if (User->getOpcode() == ISD::SELECT) {
7532 if (User->getOperand(0) == PromOps[i])
7534 } else if (User->getOpcode() == ISD::SELECT_CC) {
7535 if (User->getOperand(0) == PromOps[i] ||
7536 User->getOperand(1) == PromOps[i])
7542 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7543 bool ReallyNeedsExt = false;
7544 if (N->getOpcode() != ISD::ANY_EXTEND) {
7545 // If all of the inputs are not already sign/zero extended, then
7546 // we'll still need to do that at the end.
7547 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7548 if (isa<ConstantSDNode>(Inputs[i]))
7552 Inputs[i].getOperand(0).getValueSizeInBits();
7553 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7555 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7556 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7557 APInt::getHighBitsSet(OpBits,
7558 OpBits-PromBits))) ||
7559 (N->getOpcode() == ISD::SIGN_EXTEND &&
7560 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7561 (OpBits-(PromBits-1)))) {
7562 ReallyNeedsExt = true;
7568 // Replace all inputs, either with the truncation operand, or a
7569 // truncation or extension to the final output type.
7570 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7571 // Constant inputs need to be replaced with the to-be-promoted nodes that
7572 // use them because they might have users outside of the cluster of
7574 if (isa<ConstantSDNode>(Inputs[i]))
7577 SDValue InSrc = Inputs[i].getOperand(0);
7578 if (Inputs[i].getValueType() == N->getValueType(0))
7579 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7580 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7581 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7582 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7583 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7584 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7585 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7587 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7588 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7591 // Replace all operations (these are all the same, but have a different
7592 // (promoted) return type). DAG.getNode will validate that the types of
7593 // a binary operator match, so go through the list in reverse so that
7594 // we've likely promoted both operands first.
7595 while (!PromOps.empty()) {
7596 SDValue PromOp = PromOps.back();
7600 switch (PromOp.getOpcode()) {
7601 default: C = 0; break;
7602 case ISD::SELECT: C = 1; break;
7603 case ISD::SELECT_CC: C = 2; break;
7606 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7607 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7608 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7609 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7610 // The to-be-promoted operands of this node have not yet been
7611 // promoted (this should be rare because we're going through the
7612 // list backward, but if one of the operands has several users in
7613 // this cluster of to-be-promoted nodes, it is possible).
7614 PromOps.insert(PromOps.begin(), PromOp);
7618 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7619 PromOp.getNode()->op_end());
7621 // If this node has constant inputs, then they'll need to be promoted here.
7622 for (unsigned i = 0; i < 2; ++i) {
7623 if (!isa<ConstantSDNode>(Ops[C+i]))
7625 if (Ops[C+i].getValueType() == N->getValueType(0))
7628 if (N->getOpcode() == ISD::SIGN_EXTEND)
7629 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7630 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7631 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7633 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7636 DAG.ReplaceAllUsesOfValueWith(PromOp,
7637 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7638 Ops.data(), Ops.size()));
7641 // Now we're left with the initial extension itself.
7642 if (!ReallyNeedsExt)
7643 return N->getOperand(0);
7645 // To zero extend, just mask off everything except for the first bit (in the
7647 if (N->getOpcode() == ISD::ZERO_EXTEND)
7648 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7649 DAG.getConstant(APInt::getLowBitsSet(
7650 N->getValueSizeInBits(0), PromBits),
7651 N->getValueType(0)));
7653 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7654 "Invalid extension type");
7655 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7657 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7658 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7659 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7660 N->getOperand(0), ShiftCst), ShiftCst);
7663 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7664 DAGCombinerInfo &DCI) const {
7665 const TargetMachine &TM = getTargetMachine();
7666 SelectionDAG &DAG = DCI.DAG;
7668 switch (N->getOpcode()) {
7671 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7672 if (C->isNullValue()) // 0 << V -> 0.
7673 return N->getOperand(0);
7677 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7678 if (C->isNullValue()) // 0 >>u V -> 0.
7679 return N->getOperand(0);
7683 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7684 if (C->isNullValue() || // 0 >>s V -> 0.
7685 C->isAllOnesValue()) // -1 >>s V -> -1.
7686 return N->getOperand(0);
7689 case ISD::SIGN_EXTEND:
7690 case ISD::ZERO_EXTEND:
7691 case ISD::ANY_EXTEND:
7692 return DAGCombineExtBoolTrunc(N, DCI);
7695 case ISD::SELECT_CC:
7696 return DAGCombineTruncBoolExt(N, DCI);
7698 assert(TM.Options.UnsafeFPMath &&
7699 "Reciprocal estimates require UnsafeFPMath");
7701 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7703 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7704 if (RV.getNode() != 0) {
7705 DCI.AddToWorklist(RV.getNode());
7706 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7707 N->getOperand(0), RV);
7709 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7710 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7712 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7714 if (RV.getNode() != 0) {
7715 DCI.AddToWorklist(RV.getNode());
7716 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7717 N->getValueType(0), RV);
7718 DCI.AddToWorklist(RV.getNode());
7719 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7720 N->getOperand(0), RV);
7722 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7723 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7725 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7727 if (RV.getNode() != 0) {
7728 DCI.AddToWorklist(RV.getNode());
7729 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7730 N->getValueType(0), RV,
7731 N->getOperand(1).getOperand(1));
7732 DCI.AddToWorklist(RV.getNode());
7733 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7734 N->getOperand(0), RV);
7738 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7739 if (RV.getNode() != 0) {
7740 DCI.AddToWorklist(RV.getNode());
7741 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7742 N->getOperand(0), RV);
7748 assert(TM.Options.UnsafeFPMath &&
7749 "Reciprocal estimates require UnsafeFPMath");
7751 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7753 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7754 if (RV.getNode() != 0) {
7755 DCI.AddToWorklist(RV.getNode());
7756 RV = DAGCombineFastRecip(RV, DCI);
7757 if (RV.getNode() != 0) {
7758 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7759 // this case and force the answer to 0.
7761 EVT VT = RV.getValueType();
7763 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7764 if (VT.isVector()) {
7765 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7766 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7770 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7771 N->getOperand(0), Zero, ISD::SETEQ);
7772 DCI.AddToWorklist(ZeroCmp.getNode());
7773 DCI.AddToWorklist(RV.getNode());
7775 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7783 case ISD::SINT_TO_FP:
7784 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7785 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7786 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7787 // We allow the src/dst to be either f32/f64, but the intermediate
7788 // type must be i64.
7789 if (N->getOperand(0).getValueType() == MVT::i64 &&
7790 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7791 SDValue Val = N->getOperand(0).getOperand(0);
7792 if (Val.getValueType() == MVT::f32) {
7793 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7794 DCI.AddToWorklist(Val.getNode());
7797 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7798 DCI.AddToWorklist(Val.getNode());
7799 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7800 DCI.AddToWorklist(Val.getNode());
7801 if (N->getValueType(0) == MVT::f32) {
7802 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7803 DAG.getIntPtrConstant(0));
7804 DCI.AddToWorklist(Val.getNode());
7807 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7808 // If the intermediate type is i32, we can avoid the load/store here
7815 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7816 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7817 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7818 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7819 N->getOperand(1).getValueType() == MVT::i32 &&
7820 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7821 SDValue Val = N->getOperand(1).getOperand(0);
7822 if (Val.getValueType() == MVT::f32) {
7823 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7824 DCI.AddToWorklist(Val.getNode());
7826 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7827 DCI.AddToWorklist(Val.getNode());
7830 N->getOperand(0), Val, N->getOperand(2),
7831 DAG.getValueType(N->getOperand(1).getValueType())
7834 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7835 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7836 cast<StoreSDNode>(N)->getMemoryVT(),
7837 cast<StoreSDNode>(N)->getMemOperand());
7838 DCI.AddToWorklist(Val.getNode());
7842 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7843 if (cast<StoreSDNode>(N)->isUnindexed() &&
7844 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7845 N->getOperand(1).getNode()->hasOneUse() &&
7846 (N->getOperand(1).getValueType() == MVT::i32 ||
7847 N->getOperand(1).getValueType() == MVT::i16 ||
7848 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7849 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7850 N->getOperand(1).getValueType() == MVT::i64))) {
7851 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7852 // Do an any-extend to 32-bits if this is a half-word input.
7853 if (BSwapOp.getValueType() == MVT::i16)
7854 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7857 N->getOperand(0), BSwapOp, N->getOperand(2),
7858 DAG.getValueType(N->getOperand(1).getValueType())
7861 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7862 Ops, array_lengthof(Ops),
7863 cast<StoreSDNode>(N)->getMemoryVT(),
7864 cast<StoreSDNode>(N)->getMemOperand());
7868 LoadSDNode *LD = cast<LoadSDNode>(N);
7869 EVT VT = LD->getValueType(0);
7870 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7871 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7872 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7873 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7874 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7875 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7876 LD->getAlignment() < ABIAlignment) {
7877 // This is a type-legal unaligned Altivec load.
7878 SDValue Chain = LD->getChain();
7879 SDValue Ptr = LD->getBasePtr();
7881 // This implements the loading of unaligned vectors as described in
7882 // the venerable Apple Velocity Engine overview. Specifically:
7883 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7884 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7886 // The general idea is to expand a sequence of one or more unaligned
7887 // loads into a alignment-based permutation-control instruction (lvsl),
7888 // a series of regular vector loads (which always truncate their
7889 // input address to an aligned address), and a series of permutations.
7890 // The results of these permutations are the requested loaded values.
7891 // The trick is that the last "extra" load is not taken from the address
7892 // you might suspect (sizeof(vector) bytes after the last requested
7893 // load), but rather sizeof(vector) - 1 bytes after the last
7894 // requested vector. The point of this is to avoid a page fault if the
7895 // base address happened to be aligned. This works because if the base
7896 // address is aligned, then adding less than a full vector length will
7897 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7898 // the next vector will be fetched as you might suspect was necessary.
7900 // We might be able to reuse the permutation generation from
7901 // a different base address offset from this one by an aligned amount.
7902 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
7903 // optimization later.
7904 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
7905 DAG, dl, MVT::v16i8);
7907 // Refine the alignment of the original load (a "new" load created here
7908 // which was identical to the first except for the alignment would be
7909 // merged with the existing node regardless).
7910 MachineFunction &MF = DAG.getMachineFunction();
7911 MachineMemOperand *MMO =
7912 MF.getMachineMemOperand(LD->getPointerInfo(),
7913 LD->getMemOperand()->getFlags(),
7914 LD->getMemoryVT().getStoreSize(),
7916 LD->refineAlignment(MMO);
7917 SDValue BaseLoad = SDValue(LD, 0);
7919 // Note that the value of IncOffset (which is provided to the next
7920 // load's pointer info offset value, and thus used to calculate the
7921 // alignment), and the value of IncValue (which is actually used to
7922 // increment the pointer value) are different! This is because we
7923 // require the next load to appear to be aligned, even though it
7924 // is actually offset from the base pointer by a lesser amount.
7925 int IncOffset = VT.getSizeInBits() / 8;
7926 int IncValue = IncOffset;
7928 // Walk (both up and down) the chain looking for another load at the real
7929 // (aligned) offset (the alignment of the other load does not matter in
7930 // this case). If found, then do not use the offset reduction trick, as
7931 // that will prevent the loads from being later combined (as they would
7932 // otherwise be duplicates).
7933 if (!findConsecutiveLoad(LD, DAG))
7936 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
7937 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
7940 DAG.getLoad(VT, dl, Chain, Ptr,
7941 LD->getPointerInfo().getWithOffset(IncOffset),
7942 LD->isVolatile(), LD->isNonTemporal(),
7943 LD->isInvariant(), ABIAlignment);
7945 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7946 BaseLoad.getValue(1), ExtraLoad.getValue(1));
7948 if (BaseLoad.getValueType() != MVT::v4i32)
7949 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
7951 if (ExtraLoad.getValueType() != MVT::v4i32)
7952 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
7954 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
7955 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
7957 if (VT != MVT::v4i32)
7958 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
7960 // Now we need to be really careful about how we update the users of the
7961 // original load. We cannot just call DCI.CombineTo (or
7962 // DAG.ReplaceAllUsesWith for that matter), because the load still has
7963 // uses created here (the permutation for example) that need to stay.
7964 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7966 SDUse &Use = UI.getUse();
7968 // Note: BaseLoad is checked here because it might not be N, but a
7970 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
7971 User == TF.getNode() || Use.getResNo() > 1) {
7976 SDValue To = Use.getResNo() ? TF : Perm;
7979 SmallVector<SDValue, 8> Ops;
7980 for (SDNode::op_iterator O = User->op_begin(),
7981 OE = User->op_end(); O != OE; ++O) {
7988 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
7991 return SDValue(N, 0);
7995 case ISD::INTRINSIC_WO_CHAIN:
7996 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
7997 Intrinsic::ppc_altivec_lvsl &&
7998 N->getOperand(1)->getOpcode() == ISD::ADD) {
7999 SDValue Add = N->getOperand(1);
8001 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8002 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8003 Add.getValueType().getScalarType().getSizeInBits()))) {
8004 SDNode *BasePtr = Add->getOperand(0).getNode();
8005 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8006 UE = BasePtr->use_end(); UI != UE; ++UI) {
8007 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8008 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8009 Intrinsic::ppc_altivec_lvsl) {
8010 // We've found another LVSL, and this address if an aligned
8011 // multiple of that one. The results will be the same, so use the
8012 // one we've just found instead.
8014 return SDValue(*UI, 0);
8022 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8023 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8024 N->getOperand(0).hasOneUse() &&
8025 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8026 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8027 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8028 N->getValueType(0) == MVT::i64))) {
8029 SDValue Load = N->getOperand(0);
8030 LoadSDNode *LD = cast<LoadSDNode>(Load);
8031 // Create the byte-swapping load.
8033 LD->getChain(), // Chain
8034 LD->getBasePtr(), // Ptr
8035 DAG.getValueType(N->getValueType(0)) // VT
8038 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8039 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8040 MVT::i64 : MVT::i32, MVT::Other),
8041 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8043 // If this is an i16 load, insert the truncate.
8044 SDValue ResVal = BSLoad;
8045 if (N->getValueType(0) == MVT::i16)
8046 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8048 // First, combine the bswap away. This makes the value produced by the
8050 DCI.CombineTo(N, ResVal);
8052 // Next, combine the load away, we give it a bogus result value but a real
8053 // chain result. The result value is dead because the bswap is dead.
8054 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8056 // Return N so it doesn't get rechecked!
8057 return SDValue(N, 0);
8061 case PPCISD::VCMP: {
8062 // If a VCMPo node already exists with exactly the same operands as this
8063 // node, use its result instead of this node (VCMPo computes both a CR6 and
8064 // a normal output).
8066 if (!N->getOperand(0).hasOneUse() &&
8067 !N->getOperand(1).hasOneUse() &&
8068 !N->getOperand(2).hasOneUse()) {
8070 // Scan all of the users of the LHS, looking for VCMPo's that match.
8071 SDNode *VCMPoNode = 0;
8073 SDNode *LHSN = N->getOperand(0).getNode();
8074 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8076 if (UI->getOpcode() == PPCISD::VCMPo &&
8077 UI->getOperand(1) == N->getOperand(1) &&
8078 UI->getOperand(2) == N->getOperand(2) &&
8079 UI->getOperand(0) == N->getOperand(0)) {
8084 // If there is no VCMPo node, or if the flag value has a single use, don't
8086 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8089 // Look at the (necessarily single) use of the flag value. If it has a
8090 // chain, this transformation is more complex. Note that multiple things
8091 // could use the value result, which we should ignore.
8092 SDNode *FlagUser = 0;
8093 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8094 FlagUser == 0; ++UI) {
8095 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8097 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8098 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8105 // If the user is a MFOCRF instruction, we know this is safe.
8106 // Otherwise we give up for right now.
8107 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8108 return SDValue(VCMPoNode, 0);
8113 SDValue Cond = N->getOperand(1);
8114 SDValue Target = N->getOperand(2);
8116 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8117 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8118 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8120 // We now need to make the intrinsic dead (it cannot be instruction
8122 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8123 assert(Cond.getNode()->hasOneUse() &&
8124 "Counter decrement has more than one use");
8126 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8127 N->getOperand(0), Target);
8132 // If this is a branch on an altivec predicate comparison, lower this so
8133 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8134 // lowering is done pre-legalize, because the legalizer lowers the predicate
8135 // compare down to code that is difficult to reassemble.
8136 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8137 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8139 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8140 // value. If so, pass-through the AND to get to the intrinsic.
8141 if (LHS.getOpcode() == ISD::AND &&
8142 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8143 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8144 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8145 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8146 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8148 LHS = LHS.getOperand(0);
8150 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8151 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8152 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8153 isa<ConstantSDNode>(RHS)) {
8154 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8155 "Counter decrement comparison is not EQ or NE");
8157 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8158 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8159 (CC == ISD::SETNE && !Val);
8161 // We now need to make the intrinsic dead (it cannot be instruction
8163 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8164 assert(LHS.getNode()->hasOneUse() &&
8165 "Counter decrement has more than one use");
8167 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8168 N->getOperand(0), N->getOperand(4));
8174 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8175 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8176 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8177 assert(isDot && "Can't compare against a vector result!");
8179 // If this is a comparison against something other than 0/1, then we know
8180 // that the condition is never/always true.
8181 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8182 if (Val != 0 && Val != 1) {
8183 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8184 return N->getOperand(0);
8185 // Always !=, turn it into an unconditional branch.
8186 return DAG.getNode(ISD::BR, dl, MVT::Other,
8187 N->getOperand(0), N->getOperand(4));
8190 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8192 // Create the PPCISD altivec 'dot' comparison node.
8194 LHS.getOperand(2), // LHS of compare
8195 LHS.getOperand(3), // RHS of compare
8196 DAG.getConstant(CompareOpc, MVT::i32)
8198 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8199 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8201 // Unpack the result based on how the target uses it.
8202 PPC::Predicate CompOpc;
8203 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8204 default: // Can't happen, don't crash on invalid number though.
8205 case 0: // Branch on the value of the EQ bit of CR6.
8206 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8208 case 1: // Branch on the inverted value of the EQ bit of CR6.
8209 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8211 case 2: // Branch on the value of the LT bit of CR6.
8212 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8214 case 3: // Branch on the inverted value of the LT bit of CR6.
8215 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8219 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8220 DAG.getConstant(CompOpc, MVT::i32),
8221 DAG.getRegister(PPC::CR6, MVT::i32),
8222 N->getOperand(4), CompNode.getValue(1));
8231 //===----------------------------------------------------------------------===//
8232 // Inline Assembly Support
8233 //===----------------------------------------------------------------------===//
8235 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8238 const SelectionDAG &DAG,
8239 unsigned Depth) const {
8240 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8241 switch (Op.getOpcode()) {
8243 case PPCISD::LBRX: {
8244 // lhbrx is known to have the top bits cleared out.
8245 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8246 KnownZero = 0xFFFF0000;
8249 case ISD::INTRINSIC_WO_CHAIN: {
8250 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8252 case Intrinsic::ppc_altivec_vcmpbfp_p:
8253 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8254 case Intrinsic::ppc_altivec_vcmpequb_p:
8255 case Intrinsic::ppc_altivec_vcmpequh_p:
8256 case Intrinsic::ppc_altivec_vcmpequw_p:
8257 case Intrinsic::ppc_altivec_vcmpgefp_p:
8258 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8259 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8260 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8261 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8262 case Intrinsic::ppc_altivec_vcmpgtub_p:
8263 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8264 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8265 KnownZero = ~1U; // All bits but the low one are known to be zero.
8273 /// getConstraintType - Given a constraint, return the type of
8274 /// constraint it is for this target.
8275 PPCTargetLowering::ConstraintType
8276 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8277 if (Constraint.size() == 1) {
8278 switch (Constraint[0]) {
8285 return C_RegisterClass;
8287 // FIXME: While Z does indicate a memory constraint, it specifically
8288 // indicates an r+r address (used in conjunction with the 'y' modifier
8289 // in the replacement string). Currently, we're forcing the base
8290 // register to be r0 in the asm printer (which is interpreted as zero)
8291 // and forming the complete address in the second register. This is
8295 } else if (Constraint == "wc") { // individual CR bits.
8296 return C_RegisterClass;
8298 return TargetLowering::getConstraintType(Constraint);
8301 /// Examine constraint type and operand type and determine a weight value.
8302 /// This object must already have been set up with the operand type
8303 /// and the current alternative constraint selected.
8304 TargetLowering::ConstraintWeight
8305 PPCTargetLowering::getSingleConstraintMatchWeight(
8306 AsmOperandInfo &info, const char *constraint) const {
8307 ConstraintWeight weight = CW_Invalid;
8308 Value *CallOperandVal = info.CallOperandVal;
8309 // If we don't have a value, we can't do a match,
8310 // but allow it at the lowest weight.
8311 if (CallOperandVal == NULL)
8313 Type *type = CallOperandVal->getType();
8315 // Look at the constraint type.
8316 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8317 return CW_Register; // an individual CR bit.
8319 switch (*constraint) {
8321 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8324 if (type->isIntegerTy())
8325 weight = CW_Register;
8328 if (type->isFloatTy())
8329 weight = CW_Register;
8332 if (type->isDoubleTy())
8333 weight = CW_Register;
8336 if (type->isVectorTy())
8337 weight = CW_Register;
8340 weight = CW_Register;
8349 std::pair<unsigned, const TargetRegisterClass*>
8350 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8352 if (Constraint.size() == 1) {
8353 // GCC RS6000 Constraint Letters
8354 switch (Constraint[0]) {
8356 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8357 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8358 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8360 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8361 return std::make_pair(0U, &PPC::G8RCRegClass);
8362 return std::make_pair(0U, &PPC::GPRCRegClass);
8364 if (VT == MVT::f32 || VT == MVT::i32)
8365 return std::make_pair(0U, &PPC::F4RCRegClass);
8366 if (VT == MVT::f64 || VT == MVT::i64)
8367 return std::make_pair(0U, &PPC::F8RCRegClass);
8370 return std::make_pair(0U, &PPC::VRRCRegClass);
8372 return std::make_pair(0U, &PPC::CRRCRegClass);
8374 } else if (Constraint == "wc") { // an individual CR bit.
8375 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8378 std::pair<unsigned, const TargetRegisterClass*> R =
8379 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8381 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8382 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8383 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8385 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8386 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8387 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8388 PPC::GPRCRegClass.contains(R.first)) {
8389 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8390 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8391 PPC::sub_32, &PPC::G8RCRegClass),
8392 &PPC::G8RCRegClass);
8399 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8400 /// vector. If it is invalid, don't add anything to Ops.
8401 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8402 std::string &Constraint,
8403 std::vector<SDValue>&Ops,
8404 SelectionDAG &DAG) const {
8405 SDValue Result(0,0);
8407 // Only support length 1 constraints.
8408 if (Constraint.length() > 1) return;
8410 char Letter = Constraint[0];
8421 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8422 if (!CST) return; // Must be an immediate to match.
8423 unsigned Value = CST->getZExtValue();
8425 default: llvm_unreachable("Unknown constraint letter!");
8426 case 'I': // "I" is a signed 16-bit constant.
8427 if ((short)Value == (int)Value)
8428 Result = DAG.getTargetConstant(Value, Op.getValueType());
8430 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8431 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8432 if ((short)Value == 0)
8433 Result = DAG.getTargetConstant(Value, Op.getValueType());
8435 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8436 if ((Value >> 16) == 0)
8437 Result = DAG.getTargetConstant(Value, Op.getValueType());
8439 case 'M': // "M" is a constant that is greater than 31.
8441 Result = DAG.getTargetConstant(Value, Op.getValueType());
8443 case 'N': // "N" is a positive constant that is an exact power of two.
8444 if ((int)Value > 0 && isPowerOf2_32(Value))
8445 Result = DAG.getTargetConstant(Value, Op.getValueType());
8447 case 'O': // "O" is the constant zero.
8449 Result = DAG.getTargetConstant(Value, Op.getValueType());
8451 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8452 if ((short)-Value == (int)-Value)
8453 Result = DAG.getTargetConstant(Value, Op.getValueType());
8460 if (Result.getNode()) {
8461 Ops.push_back(Result);
8465 // Handle standard constraint letters.
8466 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8469 // isLegalAddressingMode - Return true if the addressing mode represented
8470 // by AM is legal for this target, for a load/store of the specified type.
8471 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8473 // FIXME: PPC does not allow r+i addressing modes for vectors!
8475 // PPC allows a sign-extended 16-bit immediate field.
8476 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8479 // No global is ever allowed as a base.
8483 // PPC only support r+r,
8485 case 0: // "r+i" or just "i", depending on HasBaseReg.
8488 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8490 // Otherwise we have r+r or r+i.
8493 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8495 // Allow 2*r as r+r.
8498 // No other scales are supported.
8505 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8506 SelectionDAG &DAG) const {
8507 MachineFunction &MF = DAG.getMachineFunction();
8508 MachineFrameInfo *MFI = MF.getFrameInfo();
8509 MFI->setReturnAddressIsTaken(true);
8511 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8515 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8517 // Make sure the function does not optimize away the store of the RA to
8519 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8520 FuncInfo->setLRStoreRequired();
8521 bool isPPC64 = PPCSubTarget.isPPC64();
8522 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8525 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8528 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8529 isPPC64? MVT::i64 : MVT::i32);
8530 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8531 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8533 MachinePointerInfo(), false, false, false, 0);
8536 // Just load the return address off the stack.
8537 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8538 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8539 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8542 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8543 SelectionDAG &DAG) const {
8545 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8547 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8548 bool isPPC64 = PtrVT == MVT::i64;
8550 MachineFunction &MF = DAG.getMachineFunction();
8551 MachineFrameInfo *MFI = MF.getFrameInfo();
8552 MFI->setFrameAddressIsTaken(true);
8554 // Naked functions never have a frame pointer, and so we use r1. For all
8555 // other functions, this decision must be delayed until during PEI.
8557 if (MF.getFunction()->getAttributes().hasAttribute(
8558 AttributeSet::FunctionIndex, Attribute::Naked))
8559 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8561 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8563 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8566 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8567 FrameAddr, MachinePointerInfo(), false, false,
8573 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8574 // The PowerPC target isn't yet aware of offsets.
8578 /// getOptimalMemOpType - Returns the target specific optimal type for load
8579 /// and store operations as a result of memset, memcpy, and memmove
8580 /// lowering. If DstAlign is zero that means it's safe to destination
8581 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8582 /// means there isn't a need to check it against alignment requirement,
8583 /// probably because the source does not need to be loaded. If 'IsMemset' is
8584 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8585 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8586 /// source is constant so it does not need to be loaded.
8587 /// It returns EVT::Other if the type should be determined using generic
8588 /// target-independent logic.
8589 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8590 unsigned DstAlign, unsigned SrcAlign,
8591 bool IsMemset, bool ZeroMemset,
8593 MachineFunction &MF) const {
8594 if (this->PPCSubTarget.isPPC64()) {
8601 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8604 if (DisablePPCUnaligned)
8607 // PowerPC supports unaligned memory access for simple non-vector types.
8608 // Although accessing unaligned addresses is not as efficient as accessing
8609 // aligned addresses, it is generally more efficient than manual expansion,
8610 // and generally only traps for software emulation when crossing page
8616 if (VT.getSimpleVT().isVector())
8619 if (VT == MVT::ppcf128)
8628 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8629 VT = VT.getScalarType();
8634 switch (VT.getSimpleVT().SimpleTy) {
8645 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8646 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8647 return TargetLowering::getSchedulingPreference(N);
8652 // Create a fast isel object.
8654 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8655 const TargetLibraryInfo *LibInfo) const {
8656 return PPC::createFastISel(FuncInfo, LibInfo);