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 if (isPPC64 || Subtarget->hasFPCVT()) {
104 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
109 isPPC64 ? MVT::i64 : MVT::i32);
111 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115 // PowerPC does not support direct load / store of condition registers
116 setOperationAction(ISD::LOAD, MVT::i1, Custom);
117 setOperationAction(ISD::STORE, MVT::i1, Custom);
119 // FIXME: Remove this once the ANDI glue bug is fixed:
121 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget->hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget->hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath &&
185 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget->hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget->hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget->hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget->useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget->useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget->useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget->isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget->isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget->has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (PPCSubTarget.hasFPCVT()) {
371 if (Subtarget->has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget->use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget->hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
407 // add/sub are legal for all supported vector VT's.
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
411 // We promote all shuffles to v16i8.
412 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
415 // We promote all non-typed operations to v4i32.
416 setOperationAction(ISD::AND , VT, Promote);
417 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
418 setOperationAction(ISD::OR , VT, Promote);
419 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
420 setOperationAction(ISD::XOR , VT, Promote);
421 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
422 setOperationAction(ISD::LOAD , VT, Promote);
423 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
424 setOperationAction(ISD::SELECT, VT, Promote);
425 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426 setOperationAction(ISD::STORE, VT, Promote);
427 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
429 // No other operations are legal.
430 setOperationAction(ISD::MUL , VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::SREM, VT, Expand);
433 setOperationAction(ISD::UDIV, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
435 setOperationAction(ISD::FDIV, VT, Expand);
436 setOperationAction(ISD::FREM, VT, Expand);
437 setOperationAction(ISD::FNEG, VT, Expand);
438 setOperationAction(ISD::FSQRT, VT, Expand);
439 setOperationAction(ISD::FLOG, VT, Expand);
440 setOperationAction(ISD::FLOG10, VT, Expand);
441 setOperationAction(ISD::FLOG2, VT, Expand);
442 setOperationAction(ISD::FEXP, VT, Expand);
443 setOperationAction(ISD::FEXP2, VT, Expand);
444 setOperationAction(ISD::FSIN, VT, Expand);
445 setOperationAction(ISD::FCOS, VT, Expand);
446 setOperationAction(ISD::FABS, VT, Expand);
447 setOperationAction(ISD::FPOWI, VT, Expand);
448 setOperationAction(ISD::FFLOOR, VT, Expand);
449 setOperationAction(ISD::FCEIL, VT, Expand);
450 setOperationAction(ISD::FTRUNC, VT, Expand);
451 setOperationAction(ISD::FRINT, VT, Expand);
452 setOperationAction(ISD::FNEARBYINT, VT, Expand);
453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458 setOperationAction(ISD::UDIVREM, VT, Expand);
459 setOperationAction(ISD::SDIVREM, VT, Expand);
460 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461 setOperationAction(ISD::FPOW, VT, Expand);
462 setOperationAction(ISD::CTPOP, VT, Expand);
463 setOperationAction(ISD::CTLZ, VT, Expand);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
465 setOperationAction(ISD::CTTZ, VT, Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
467 setOperationAction(ISD::VSELECT, VT, Expand);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
471 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
472 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
473 setTruncStoreAction(VT, InnerVT, Expand);
475 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
476 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
477 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
480 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
481 // with merges, splats, etc.
482 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
484 setOperationAction(ISD::AND , MVT::v4i32, Legal);
485 setOperationAction(ISD::OR , MVT::v4i32, Legal);
486 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
487 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
488 setOperationAction(ISD::SELECT, MVT::v4i32,
489 Subtarget->useCRBits() ? Legal : Expand);
490 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
491 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
492 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
493 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
494 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
495 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
496 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
497 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
500 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
501 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
502 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
503 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
505 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
506 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
508 if (TM.Options.UnsafeFPMath || Subtarget->hasVSX()) {
509 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
510 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
513 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
515 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
517 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
518 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
522 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
523 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
525 // Altivec does not contain unordered floating-point compare instructions
526 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
527 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
531 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536 if (Subtarget->hasVSX()) {
537 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
540 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
541 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
543 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
545 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
547 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
548 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
550 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
551 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
553 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
554 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
559 // Share the Altivec comparison restrictions.
560 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
561 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
562 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
567 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
570 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
571 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
573 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
575 addRegisterClass(MVT::f64, &PPC::VSRCRegClass);
577 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
578 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
580 // VSX v2i64 only supports non-arithmetic operations.
581 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
582 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
584 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
585 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
586 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
588 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
589 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
590 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
591 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
593 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
595 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
596 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
597 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
598 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
600 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
604 if (Subtarget->has64BitSupport()) {
605 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
606 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
609 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
610 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
611 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
612 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
614 setBooleanContents(ZeroOrOneBooleanContent);
615 // Altivec instructions set fields to all zeros or all ones.
616 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
619 setStackPointerRegisterToSaveRestore(PPC::X1);
620 setExceptionPointerRegister(PPC::X3);
621 setExceptionSelectorRegister(PPC::X4);
623 setStackPointerRegisterToSaveRestore(PPC::R1);
624 setExceptionPointerRegister(PPC::R3);
625 setExceptionSelectorRegister(PPC::R4);
628 // We have target-specific dag combine patterns for the following nodes:
629 setTargetDAGCombine(ISD::SINT_TO_FP);
630 setTargetDAGCombine(ISD::LOAD);
631 setTargetDAGCombine(ISD::STORE);
632 setTargetDAGCombine(ISD::BR_CC);
633 if (Subtarget->useCRBits())
634 setTargetDAGCombine(ISD::BRCOND);
635 setTargetDAGCombine(ISD::BSWAP);
636 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
638 setTargetDAGCombine(ISD::SIGN_EXTEND);
639 setTargetDAGCombine(ISD::ZERO_EXTEND);
640 setTargetDAGCombine(ISD::ANY_EXTEND);
642 if (Subtarget->useCRBits()) {
643 setTargetDAGCombine(ISD::TRUNCATE);
644 setTargetDAGCombine(ISD::SETCC);
645 setTargetDAGCombine(ISD::SELECT_CC);
648 // Use reciprocal estimates.
649 if (TM.Options.UnsafeFPMath) {
650 setTargetDAGCombine(ISD::FDIV);
651 setTargetDAGCombine(ISD::FSQRT);
654 // Darwin long double math library functions have $LDBL128 appended.
655 if (Subtarget->isDarwin()) {
656 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
657 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
658 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
659 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
660 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
661 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
662 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
663 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
664 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
665 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
668 // With 32 condition bits, we don't need to sink (and duplicate) compares
669 // aggressively in CodeGenPrep.
670 if (Subtarget->useCRBits())
671 setHasMultipleConditionRegisters();
673 setMinFunctionAlignment(2);
674 if (PPCSubTarget.isDarwin())
675 setPrefFunctionAlignment(4);
677 if (isPPC64 && Subtarget->isJITCodeModel())
678 // Temporary workaround for the inability of PPC64 JIT to handle jump
680 setSupportJumpTables(false);
682 setInsertFencesForAtomic(true);
684 if (Subtarget->enableMachineScheduler())
685 setSchedulingPreference(Sched::Source);
687 setSchedulingPreference(Sched::Hybrid);
689 computeRegisterProperties();
691 // The Freescale cores does better with aggressive inlining of memcpy and
692 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
693 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
694 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
695 MaxStoresPerMemset = 32;
696 MaxStoresPerMemsetOptSize = 16;
697 MaxStoresPerMemcpy = 32;
698 MaxStoresPerMemcpyOptSize = 8;
699 MaxStoresPerMemmove = 32;
700 MaxStoresPerMemmoveOptSize = 8;
702 setPrefFunctionAlignment(4);
706 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
707 /// the desired ByVal argument alignment.
708 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
709 unsigned MaxMaxAlign) {
710 if (MaxAlign == MaxMaxAlign)
712 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
713 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
715 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
717 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
718 unsigned EltAlign = 0;
719 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
720 if (EltAlign > MaxAlign)
722 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
723 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
724 unsigned EltAlign = 0;
725 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
726 if (EltAlign > MaxAlign)
728 if (MaxAlign == MaxMaxAlign)
734 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
735 /// function arguments in the caller parameter area.
736 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
737 // Darwin passes everything on 4 byte boundary.
738 if (PPCSubTarget.isDarwin())
741 // 16byte and wider vectors are passed on 16byte boundary.
742 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
743 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
744 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
745 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
749 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
752 case PPCISD::FSEL: return "PPCISD::FSEL";
753 case PPCISD::FCFID: return "PPCISD::FCFID";
754 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
755 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
756 case PPCISD::FRE: return "PPCISD::FRE";
757 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
758 case PPCISD::STFIWX: return "PPCISD::STFIWX";
759 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
760 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
761 case PPCISD::VPERM: return "PPCISD::VPERM";
762 case PPCISD::Hi: return "PPCISD::Hi";
763 case PPCISD::Lo: return "PPCISD::Lo";
764 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
765 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
766 case PPCISD::LOAD: return "PPCISD::LOAD";
767 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
768 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
769 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
770 case PPCISD::SRL: return "PPCISD::SRL";
771 case PPCISD::SRA: return "PPCISD::SRA";
772 case PPCISD::SHL: return "PPCISD::SHL";
773 case PPCISD::CALL: return "PPCISD::CALL";
774 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
775 case PPCISD::MTCTR: return "PPCISD::MTCTR";
776 case PPCISD::BCTRL: return "PPCISD::BCTRL";
777 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
778 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
779 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
780 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
781 case PPCISD::VCMP: return "PPCISD::VCMP";
782 case PPCISD::VCMPo: return "PPCISD::VCMPo";
783 case PPCISD::LBRX: return "PPCISD::LBRX";
784 case PPCISD::STBRX: return "PPCISD::STBRX";
785 case PPCISD::LARX: return "PPCISD::LARX";
786 case PPCISD::STCX: return "PPCISD::STCX";
787 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
788 case PPCISD::BDNZ: return "PPCISD::BDNZ";
789 case PPCISD::BDZ: return "PPCISD::BDZ";
790 case PPCISD::MFFS: return "PPCISD::MFFS";
791 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
792 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
793 case PPCISD::CR6SET: return "PPCISD::CR6SET";
794 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
795 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
796 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
797 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
798 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
799 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
800 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
801 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
802 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
803 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
804 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
805 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
806 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
807 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
808 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
809 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
810 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
811 case PPCISD::SC: return "PPCISD::SC";
815 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
817 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
818 return VT.changeVectorElementTypeToInteger();
821 //===----------------------------------------------------------------------===//
822 // Node matching predicates, for use by the tblgen matching code.
823 //===----------------------------------------------------------------------===//
825 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
826 static bool isFloatingPointZero(SDValue Op) {
827 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
828 return CFP->getValueAPF().isZero();
829 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
830 // Maybe this has already been legalized into the constant pool?
831 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
832 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
833 return CFP->getValueAPF().isZero();
838 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
839 /// true if Op is undef or if it matches the specified value.
840 static bool isConstantOrUndef(int Op, int Val) {
841 return Op < 0 || Op == Val;
844 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
845 /// VPKUHUM instruction.
846 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
848 for (unsigned i = 0; i != 16; ++i)
849 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
852 for (unsigned i = 0; i != 8; ++i)
853 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
854 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
860 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
861 /// VPKUWUM instruction.
862 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
864 for (unsigned i = 0; i != 16; i += 2)
865 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
866 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
869 for (unsigned i = 0; i != 8; i += 2)
870 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
871 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
872 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
873 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
879 /// isVMerge - Common function, used to match vmrg* shuffles.
881 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
882 unsigned LHSStart, unsigned RHSStart) {
883 if (N->getValueType(0) != MVT::v16i8)
885 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
886 "Unsupported merge size!");
888 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
889 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
890 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
891 LHSStart+j+i*UnitSize) ||
892 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
893 RHSStart+j+i*UnitSize))
899 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
900 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
901 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
904 return isVMerge(N, UnitSize, 8, 24);
905 return isVMerge(N, UnitSize, 8, 8);
908 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
909 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
910 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
913 return isVMerge(N, UnitSize, 0, 16);
914 return isVMerge(N, UnitSize, 0, 0);
918 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
919 /// amount, otherwise return -1.
920 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
921 if (N->getValueType(0) != MVT::v16i8)
924 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
926 // Find the first non-undef value in the shuffle mask.
928 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
931 if (i == 16) return -1; // all undef.
933 // Otherwise, check to see if the rest of the elements are consecutively
934 // numbered from this value.
935 unsigned ShiftAmt = SVOp->getMaskElt(i);
936 if (ShiftAmt < i) return -1;
940 // Check the rest of the elements to see if they are consecutive.
941 for (++i; i != 16; ++i)
942 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
945 // Check the rest of the elements to see if they are consecutive.
946 for (++i; i != 16; ++i)
947 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
953 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
954 /// specifies a splat of a single element that is suitable for input to
955 /// VSPLTB/VSPLTH/VSPLTW.
956 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
957 assert(N->getValueType(0) == MVT::v16i8 &&
958 (EltSize == 1 || EltSize == 2 || EltSize == 4));
960 // This is a splat operation if each element of the permute is the same, and
961 // if the value doesn't reference the second vector.
962 unsigned ElementBase = N->getMaskElt(0);
964 // FIXME: Handle UNDEF elements too!
965 if (ElementBase >= 16)
968 // Check that the indices are consecutive, in the case of a multi-byte element
969 // splatted with a v16i8 mask.
970 for (unsigned i = 1; i != EltSize; ++i)
971 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
974 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
975 if (N->getMaskElt(i) < 0) continue;
976 for (unsigned j = 0; j != EltSize; ++j)
977 if (N->getMaskElt(i+j) != N->getMaskElt(j))
983 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
985 bool PPC::isAllNegativeZeroVector(SDNode *N) {
986 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
988 APInt APVal, APUndef;
992 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
993 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
994 return CFP->getValueAPF().isNegZero();
999 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1000 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1001 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1002 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1003 assert(isSplatShuffleMask(SVOp, EltSize));
1004 return SVOp->getMaskElt(0) / EltSize;
1007 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1008 /// by using a vspltis[bhw] instruction of the specified element size, return
1009 /// the constant being splatted. The ByteSize field indicates the number of
1010 /// bytes of each element [124] -> [bhw].
1011 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1012 SDValue OpVal(0, 0);
1014 // If ByteSize of the splat is bigger than the element size of the
1015 // build_vector, then we have a case where we are checking for a splat where
1016 // multiple elements of the buildvector are folded together into a single
1017 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1018 unsigned EltSize = 16/N->getNumOperands();
1019 if (EltSize < ByteSize) {
1020 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1021 SDValue UniquedVals[4];
1022 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1024 // See if all of the elements in the buildvector agree across.
1025 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1026 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1027 // If the element isn't a constant, bail fully out.
1028 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1031 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
1032 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1033 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1034 return SDValue(); // no match.
1037 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1038 // either constant or undef values that are identical for each chunk. See
1039 // if these chunks can form into a larger vspltis*.
1041 // Check to see if all of the leading entries are either 0 or -1. If
1042 // neither, then this won't fit into the immediate field.
1043 bool LeadingZero = true;
1044 bool LeadingOnes = true;
1045 for (unsigned i = 0; i != Multiple-1; ++i) {
1046 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
1048 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1049 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1051 // Finally, check the least significant entry.
1053 if (UniquedVals[Multiple-1].getNode() == 0)
1054 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1055 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1057 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1060 if (UniquedVals[Multiple-1].getNode() == 0)
1061 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1062 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1063 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1064 return DAG.getTargetConstant(Val, MVT::i32);
1070 // Check to see if this buildvec has a single non-undef value in its elements.
1071 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1072 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1073 if (OpVal.getNode() == 0)
1074 OpVal = N->getOperand(i);
1075 else if (OpVal != N->getOperand(i))
1079 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
1081 unsigned ValSizeInBytes = EltSize;
1083 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1084 Value = CN->getZExtValue();
1085 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1086 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1087 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1090 // If the splat value is larger than the element value, then we can never do
1091 // this splat. The only case that we could fit the replicated bits into our
1092 // immediate field for would be zero, and we prefer to use vxor for it.
1093 if (ValSizeInBytes < ByteSize) return SDValue();
1095 // If the element value is larger than the splat value, cut it in half and
1096 // check to see if the two halves are equal. Continue doing this until we
1097 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1098 while (ValSizeInBytes > ByteSize) {
1099 ValSizeInBytes >>= 1;
1101 // If the top half equals the bottom half, we're still ok.
1102 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1103 (Value & ((1 << (8*ValSizeInBytes))-1)))
1107 // Properly sign extend the value.
1108 int MaskVal = SignExtend32(Value, ByteSize * 8);
1110 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1111 if (MaskVal == 0) return SDValue();
1113 // Finally, if this value fits in a 5 bit sext field, return it
1114 if (SignExtend32<5>(MaskVal) == MaskVal)
1115 return DAG.getTargetConstant(MaskVal, MVT::i32);
1119 //===----------------------------------------------------------------------===//
1120 // Addressing Mode Selection
1121 //===----------------------------------------------------------------------===//
1123 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1124 /// or 64-bit immediate, and if the value can be accurately represented as a
1125 /// sign extension from a 16-bit value. If so, this returns true and the
1127 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1128 if (N->getOpcode() != ISD::Constant)
1131 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1132 if (N->getValueType(0) == MVT::i32)
1133 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1135 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1137 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1138 return isIntS16Immediate(Op.getNode(), Imm);
1142 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1143 /// can be represented as an indexed [r+r] operation. Returns false if it
1144 /// can be more efficiently represented with [r+imm].
1145 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1147 SelectionDAG &DAG) const {
1149 if (N.getOpcode() == ISD::ADD) {
1150 if (isIntS16Immediate(N.getOperand(1), imm))
1151 return false; // r+i
1152 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1153 return false; // r+i
1155 Base = N.getOperand(0);
1156 Index = N.getOperand(1);
1158 } else if (N.getOpcode() == ISD::OR) {
1159 if (isIntS16Immediate(N.getOperand(1), imm))
1160 return false; // r+i can fold it if we can.
1162 // If this is an or of disjoint bitfields, we can codegen this as an add
1163 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1165 APInt LHSKnownZero, LHSKnownOne;
1166 APInt RHSKnownZero, RHSKnownOne;
1167 DAG.ComputeMaskedBits(N.getOperand(0),
1168 LHSKnownZero, LHSKnownOne);
1170 if (LHSKnownZero.getBoolValue()) {
1171 DAG.ComputeMaskedBits(N.getOperand(1),
1172 RHSKnownZero, RHSKnownOne);
1173 // If all of the bits are known zero on the LHS or RHS, the add won't
1175 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1176 Base = N.getOperand(0);
1177 Index = N.getOperand(1);
1186 // If we happen to be doing an i64 load or store into a stack slot that has
1187 // less than a 4-byte alignment, then the frame-index elimination may need to
1188 // use an indexed load or store instruction (because the offset may not be a
1189 // multiple of 4). The extra register needed to hold the offset comes from the
1190 // register scavenger, and it is possible that the scavenger will need to use
1191 // an emergency spill slot. As a result, we need to make sure that a spill slot
1192 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1194 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1195 // FIXME: This does not handle the LWA case.
1199 // NOTE: We'll exclude negative FIs here, which come from argument
1200 // lowering, because there are no known test cases triggering this problem
1201 // using packed structures (or similar). We can remove this exclusion if
1202 // we find such a test case. The reason why this is so test-case driven is
1203 // because this entire 'fixup' is only to prevent crashes (from the
1204 // register scavenger) on not-really-valid inputs. For example, if we have:
1206 // %b = bitcast i1* %a to i64*
1207 // store i64* a, i64 b
1208 // then the store should really be marked as 'align 1', but is not. If it
1209 // were marked as 'align 1' then the indexed form would have been
1210 // instruction-selected initially, and the problem this 'fixup' is preventing
1211 // won't happen regardless.
1215 MachineFunction &MF = DAG.getMachineFunction();
1216 MachineFrameInfo *MFI = MF.getFrameInfo();
1218 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1222 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1223 FuncInfo->setHasNonRISpills();
1226 /// Returns true if the address N can be represented by a base register plus
1227 /// a signed 16-bit displacement [r+imm], and if it is not better
1228 /// represented as reg+reg. If Aligned is true, only accept displacements
1229 /// suitable for STD and friends, i.e. multiples of 4.
1230 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1233 bool Aligned) const {
1234 // FIXME dl should come from parent load or store, not from address
1236 // If this can be more profitably realized as r+r, fail.
1237 if (SelectAddressRegReg(N, Disp, Base, DAG))
1240 if (N.getOpcode() == ISD::ADD) {
1242 if (isIntS16Immediate(N.getOperand(1), imm) &&
1243 (!Aligned || (imm & 3) == 0)) {
1244 Disp = DAG.getTargetConstant(imm, N.getValueType());
1245 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1246 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1247 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1249 Base = N.getOperand(0);
1251 return true; // [r+i]
1252 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1253 // Match LOAD (ADD (X, Lo(G))).
1254 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1255 && "Cannot handle constant offsets yet!");
1256 Disp = N.getOperand(1).getOperand(0); // The global address.
1257 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1258 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1259 Disp.getOpcode() == ISD::TargetConstantPool ||
1260 Disp.getOpcode() == ISD::TargetJumpTable);
1261 Base = N.getOperand(0);
1262 return true; // [&g+r]
1264 } else if (N.getOpcode() == ISD::OR) {
1266 if (isIntS16Immediate(N.getOperand(1), imm) &&
1267 (!Aligned || (imm & 3) == 0)) {
1268 // If this is an or of disjoint bitfields, we can codegen this as an add
1269 // (for better address arithmetic) if the LHS and RHS of the OR are
1270 // provably disjoint.
1271 APInt LHSKnownZero, LHSKnownOne;
1272 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1274 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1275 // If all of the bits are known zero on the LHS or RHS, the add won't
1277 Base = N.getOperand(0);
1278 Disp = DAG.getTargetConstant(imm, N.getValueType());
1282 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1283 // Loading from a constant address.
1285 // If this address fits entirely in a 16-bit sext immediate field, codegen
1288 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1289 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1290 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1291 CN->getValueType(0));
1295 // Handle 32-bit sext immediates with LIS + addr mode.
1296 if ((CN->getValueType(0) == MVT::i32 ||
1297 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1298 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1299 int Addr = (int)CN->getZExtValue();
1301 // Otherwise, break this down into an LIS + disp.
1302 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1304 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1305 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1306 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1311 Disp = DAG.getTargetConstant(0, getPointerTy());
1312 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1313 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1314 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1317 return true; // [r+0]
1320 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1321 /// represented as an indexed [r+r] operation.
1322 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1324 SelectionDAG &DAG) const {
1325 // Check to see if we can easily represent this as an [r+r] address. This
1326 // will fail if it thinks that the address is more profitably represented as
1327 // reg+imm, e.g. where imm = 0.
1328 if (SelectAddressRegReg(N, Base, Index, DAG))
1331 // If the operand is an addition, always emit this as [r+r], since this is
1332 // better (for code size, and execution, as the memop does the add for free)
1333 // than emitting an explicit add.
1334 if (N.getOpcode() == ISD::ADD) {
1335 Base = N.getOperand(0);
1336 Index = N.getOperand(1);
1340 // Otherwise, do it the hard way, using R0 as the base register.
1341 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1347 /// getPreIndexedAddressParts - returns true by value, base pointer and
1348 /// offset pointer and addressing mode by reference if the node's address
1349 /// can be legally represented as pre-indexed load / store address.
1350 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1352 ISD::MemIndexedMode &AM,
1353 SelectionDAG &DAG) const {
1354 if (DisablePPCPreinc) return false;
1360 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1361 Ptr = LD->getBasePtr();
1362 VT = LD->getMemoryVT();
1363 Alignment = LD->getAlignment();
1364 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1365 Ptr = ST->getBasePtr();
1366 VT = ST->getMemoryVT();
1367 Alignment = ST->getAlignment();
1372 // PowerPC doesn't have preinc load/store instructions for vectors.
1376 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1378 // Common code will reject creating a pre-inc form if the base pointer
1379 // is a frame index, or if N is a store and the base pointer is either
1380 // the same as or a predecessor of the value being stored. Check for
1381 // those situations here, and try with swapped Base/Offset instead.
1384 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1387 SDValue Val = cast<StoreSDNode>(N)->getValue();
1388 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1393 std::swap(Base, Offset);
1399 // LDU/STU can only handle immediates that are a multiple of 4.
1400 if (VT != MVT::i64) {
1401 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1404 // LDU/STU need an address with at least 4-byte alignment.
1408 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1412 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1413 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1414 // sext i32 to i64 when addr mode is r+i.
1415 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1416 LD->getExtensionType() == ISD::SEXTLOAD &&
1417 isa<ConstantSDNode>(Offset))
1425 //===----------------------------------------------------------------------===//
1426 // LowerOperation implementation
1427 //===----------------------------------------------------------------------===//
1429 /// GetLabelAccessInfo - Return true if we should reference labels using a
1430 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1431 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1432 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1433 HiOpFlags = PPCII::MO_HA;
1434 LoOpFlags = PPCII::MO_LO;
1436 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1437 // non-darwin platform. We don't support PIC on other platforms yet.
1438 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1439 TM.getSubtarget<PPCSubtarget>().isDarwin();
1441 HiOpFlags |= PPCII::MO_PIC_FLAG;
1442 LoOpFlags |= PPCII::MO_PIC_FLAG;
1445 // If this is a reference to a global value that requires a non-lazy-ptr, make
1446 // sure that instruction lowering adds it.
1447 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1448 HiOpFlags |= PPCII::MO_NLP_FLAG;
1449 LoOpFlags |= PPCII::MO_NLP_FLAG;
1451 if (GV->hasHiddenVisibility()) {
1452 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1453 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1460 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1461 SelectionDAG &DAG) {
1462 EVT PtrVT = HiPart.getValueType();
1463 SDValue Zero = DAG.getConstant(0, PtrVT);
1466 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1467 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1469 // With PIC, the first instruction is actually "GR+hi(&G)".
1471 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1472 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1474 // Generate non-pic code that has direct accesses to the constant pool.
1475 // The address of the global is just (hi(&g)+lo(&g)).
1476 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1479 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1480 SelectionDAG &DAG) const {
1481 EVT PtrVT = Op.getValueType();
1482 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1483 const Constant *C = CP->getConstVal();
1485 // 64-bit SVR4 ABI code is always position-independent.
1486 // The actual address of the GlobalValue is stored in the TOC.
1487 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1488 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1489 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1490 DAG.getRegister(PPC::X2, MVT::i64));
1493 unsigned MOHiFlag, MOLoFlag;
1494 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1496 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1498 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1499 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1502 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1503 EVT PtrVT = Op.getValueType();
1504 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1506 // 64-bit SVR4 ABI code is always position-independent.
1507 // The actual address of the GlobalValue is stored in the TOC.
1508 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1509 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1510 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1511 DAG.getRegister(PPC::X2, MVT::i64));
1514 unsigned MOHiFlag, MOLoFlag;
1515 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1516 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1517 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1518 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1521 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1522 SelectionDAG &DAG) const {
1523 EVT PtrVT = Op.getValueType();
1525 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1527 unsigned MOHiFlag, MOLoFlag;
1528 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1529 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1530 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1531 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1534 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1535 SelectionDAG &DAG) const {
1537 // FIXME: TLS addresses currently use medium model code sequences,
1538 // which is the most useful form. Eventually support for small and
1539 // large models could be added if users need it, at the cost of
1540 // additional complexity.
1541 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1543 const GlobalValue *GV = GA->getGlobal();
1544 EVT PtrVT = getPointerTy();
1545 bool is64bit = PPCSubTarget.isPPC64();
1547 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1549 if (Model == TLSModel::LocalExec) {
1550 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1551 PPCII::MO_TPREL_HA);
1552 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1553 PPCII::MO_TPREL_LO);
1554 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1555 is64bit ? MVT::i64 : MVT::i32);
1556 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1557 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1560 if (Model == TLSModel::InitialExec) {
1561 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1562 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1566 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1567 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1568 PtrVT, GOTReg, TGA);
1570 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1571 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1572 PtrVT, TGA, GOTPtr);
1573 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1576 if (Model == TLSModel::GeneralDynamic) {
1577 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1578 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1579 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1581 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1584 // We need a chain node, and don't have one handy. The underlying
1585 // call has no side effects, so using the function entry node
1587 SDValue Chain = DAG.getEntryNode();
1588 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1589 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1590 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1591 PtrVT, ParmReg, TGA);
1592 // The return value from GET_TLS_ADDR really is in X3 already, but
1593 // some hacks are needed here to tie everything together. The extra
1594 // copies dissolve during subsequent transforms.
1595 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1596 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1599 if (Model == TLSModel::LocalDynamic) {
1600 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1601 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1602 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1604 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1607 // We need a chain node, and don't have one handy. The underlying
1608 // call has no side effects, so using the function entry node
1610 SDValue Chain = DAG.getEntryNode();
1611 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1612 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1613 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1614 PtrVT, ParmReg, TGA);
1615 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1616 // some hacks are needed here to tie everything together. The extra
1617 // copies dissolve during subsequent transforms.
1618 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1619 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1620 Chain, ParmReg, TGA);
1621 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1624 llvm_unreachable("Unknown TLS model!");
1627 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1628 SelectionDAG &DAG) const {
1629 EVT PtrVT = Op.getValueType();
1630 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1632 const GlobalValue *GV = GSDN->getGlobal();
1634 // 64-bit SVR4 ABI code is always position-independent.
1635 // The actual address of the GlobalValue is stored in the TOC.
1636 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1637 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1638 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1639 DAG.getRegister(PPC::X2, MVT::i64));
1642 unsigned MOHiFlag, MOLoFlag;
1643 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1646 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1648 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1650 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1652 // If the global reference is actually to a non-lazy-pointer, we have to do an
1653 // extra load to get the address of the global.
1654 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1655 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1656 false, false, false, 0);
1660 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1661 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1664 // If we're comparing for equality to zero, expose the fact that this is
1665 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1666 // fold the new nodes.
1667 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1668 if (C->isNullValue() && CC == ISD::SETEQ) {
1669 EVT VT = Op.getOperand(0).getValueType();
1670 SDValue Zext = Op.getOperand(0);
1671 if (VT.bitsLT(MVT::i32)) {
1673 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1675 unsigned Log2b = Log2_32(VT.getSizeInBits());
1676 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1677 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1678 DAG.getConstant(Log2b, MVT::i32));
1679 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1681 // Leave comparisons against 0 and -1 alone for now, since they're usually
1682 // optimized. FIXME: revisit this when we can custom lower all setcc
1684 if (C->isAllOnesValue() || C->isNullValue())
1688 // If we have an integer seteq/setne, turn it into a compare against zero
1689 // by xor'ing the rhs with the lhs, which is faster than setting a
1690 // condition register, reading it back out, and masking the correct bit. The
1691 // normal approach here uses sub to do this instead of xor. Using xor exposes
1692 // the result to other bit-twiddling opportunities.
1693 EVT LHSVT = Op.getOperand(0).getValueType();
1694 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1695 EVT VT = Op.getValueType();
1696 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1698 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1703 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1704 const PPCSubtarget &Subtarget) const {
1705 SDNode *Node = Op.getNode();
1706 EVT VT = Node->getValueType(0);
1707 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1708 SDValue InChain = Node->getOperand(0);
1709 SDValue VAListPtr = Node->getOperand(1);
1710 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1713 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1716 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1717 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1719 InChain = GprIndex.getValue(1);
1721 if (VT == MVT::i64) {
1722 // Check if GprIndex is even
1723 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1724 DAG.getConstant(1, MVT::i32));
1725 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1726 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1727 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1728 DAG.getConstant(1, MVT::i32));
1729 // Align GprIndex to be even if it isn't
1730 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1734 // fpr index is 1 byte after gpr
1735 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1736 DAG.getConstant(1, MVT::i32));
1739 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1740 FprPtr, MachinePointerInfo(SV), MVT::i8,
1742 InChain = FprIndex.getValue(1);
1744 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1745 DAG.getConstant(8, MVT::i32));
1747 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1748 DAG.getConstant(4, MVT::i32));
1751 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1752 MachinePointerInfo(), false, false,
1754 InChain = OverflowArea.getValue(1);
1756 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1757 MachinePointerInfo(), false, false,
1759 InChain = RegSaveArea.getValue(1);
1761 // select overflow_area if index > 8
1762 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1763 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1765 // adjustment constant gpr_index * 4/8
1766 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1767 VT.isInteger() ? GprIndex : FprIndex,
1768 DAG.getConstant(VT.isInteger() ? 4 : 8,
1771 // OurReg = RegSaveArea + RegConstant
1772 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1775 // Floating types are 32 bytes into RegSaveArea
1776 if (VT.isFloatingPoint())
1777 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1778 DAG.getConstant(32, MVT::i32));
1780 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1781 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1782 VT.isInteger() ? GprIndex : FprIndex,
1783 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1786 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1787 VT.isInteger() ? VAListPtr : FprPtr,
1788 MachinePointerInfo(SV),
1789 MVT::i8, false, false, 0);
1791 // determine if we should load from reg_save_area or overflow_area
1792 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1794 // increase overflow_area by 4/8 if gpr/fpr > 8
1795 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1796 DAG.getConstant(VT.isInteger() ? 4 : 8,
1799 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1802 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1804 MachinePointerInfo(),
1805 MVT::i32, false, false, 0);
1807 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1808 false, false, false, 0);
1811 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1812 const PPCSubtarget &Subtarget) const {
1813 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1815 // We have to copy the entire va_list struct:
1816 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1817 return DAG.getMemcpy(Op.getOperand(0), Op,
1818 Op.getOperand(1), Op.getOperand(2),
1819 DAG.getConstant(12, MVT::i32), 8, false, true,
1820 MachinePointerInfo(), MachinePointerInfo());
1823 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1824 SelectionDAG &DAG) const {
1825 return Op.getOperand(0);
1828 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1829 SelectionDAG &DAG) const {
1830 SDValue Chain = Op.getOperand(0);
1831 SDValue Trmp = Op.getOperand(1); // trampoline
1832 SDValue FPtr = Op.getOperand(2); // nested function
1833 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1836 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1837 bool isPPC64 = (PtrVT == MVT::i64);
1839 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1842 TargetLowering::ArgListTy Args;
1843 TargetLowering::ArgListEntry Entry;
1845 Entry.Ty = IntPtrTy;
1846 Entry.Node = Trmp; Args.push_back(Entry);
1848 // TrampSize == (isPPC64 ? 48 : 40);
1849 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1850 isPPC64 ? MVT::i64 : MVT::i32);
1851 Args.push_back(Entry);
1853 Entry.Node = FPtr; Args.push_back(Entry);
1854 Entry.Node = Nest; Args.push_back(Entry);
1856 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1857 TargetLowering::CallLoweringInfo CLI(Chain,
1858 Type::getVoidTy(*DAG.getContext()),
1859 false, false, false, false, 0,
1861 /*isTailCall=*/false,
1862 /*doesNotRet=*/false,
1863 /*isReturnValueUsed=*/true,
1864 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1866 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1868 return CallResult.second;
1871 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1872 const PPCSubtarget &Subtarget) const {
1873 MachineFunction &MF = DAG.getMachineFunction();
1874 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1878 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1879 // vastart just stores the address of the VarArgsFrameIndex slot into the
1880 // memory location argument.
1881 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1882 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1883 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1884 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1885 MachinePointerInfo(SV),
1889 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1890 // We suppose the given va_list is already allocated.
1893 // char gpr; /* index into the array of 8 GPRs
1894 // * stored in the register save area
1895 // * gpr=0 corresponds to r3,
1896 // * gpr=1 to r4, etc.
1898 // char fpr; /* index into the array of 8 FPRs
1899 // * stored in the register save area
1900 // * fpr=0 corresponds to f1,
1901 // * fpr=1 to f2, etc.
1903 // char *overflow_arg_area;
1904 // /* location on stack that holds
1905 // * the next overflow argument
1907 // char *reg_save_area;
1908 // /* where r3:r10 and f1:f8 (if saved)
1914 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1915 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1918 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1920 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1922 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1925 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1926 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1928 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1929 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1931 uint64_t FPROffset = 1;
1932 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1934 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1936 // Store first byte : number of int regs
1937 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1939 MachinePointerInfo(SV),
1940 MVT::i8, false, false, 0);
1941 uint64_t nextOffset = FPROffset;
1942 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1945 // Store second byte : number of float regs
1946 SDValue secondStore =
1947 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1948 MachinePointerInfo(SV, nextOffset), MVT::i8,
1950 nextOffset += StackOffset;
1951 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1953 // Store second word : arguments given on stack
1954 SDValue thirdStore =
1955 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1956 MachinePointerInfo(SV, nextOffset),
1958 nextOffset += FrameOffset;
1959 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1961 // Store third word : arguments given in registers
1962 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1963 MachinePointerInfo(SV, nextOffset),
1968 #include "PPCGenCallingConv.inc"
1970 // Function whose sole purpose is to kill compiler warnings
1971 // stemming from unused functions included from PPCGenCallingConv.inc.
1972 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1973 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1976 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1977 CCValAssign::LocInfo &LocInfo,
1978 ISD::ArgFlagsTy &ArgFlags,
1983 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1985 CCValAssign::LocInfo &LocInfo,
1986 ISD::ArgFlagsTy &ArgFlags,
1988 static const uint16_t ArgRegs[] = {
1989 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1990 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1992 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1994 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1996 // Skip one register if the first unallocated register has an even register
1997 // number and there are still argument registers available which have not been
1998 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1999 // need to skip a register if RegNum is odd.
2000 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2001 State.AllocateReg(ArgRegs[RegNum]);
2004 // Always return false here, as this function only makes sure that the first
2005 // unallocated register has an odd register number and does not actually
2006 // allocate a register for the current argument.
2010 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2012 CCValAssign::LocInfo &LocInfo,
2013 ISD::ArgFlagsTy &ArgFlags,
2015 static const uint16_t ArgRegs[] = {
2016 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2020 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2022 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2024 // If there is only one Floating-point register left we need to put both f64
2025 // values of a split ppc_fp128 value on the stack.
2026 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2027 State.AllocateReg(ArgRegs[RegNum]);
2030 // Always return false here, as this function only makes sure that the two f64
2031 // values a ppc_fp128 value is split into are both passed in registers or both
2032 // passed on the stack and does not actually allocate a register for the
2033 // current argument.
2037 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2039 static const uint16_t *GetFPR() {
2040 static const uint16_t FPR[] = {
2041 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2042 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2048 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2050 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2051 unsigned PtrByteSize) {
2052 unsigned ArgSize = ArgVT.getStoreSize();
2053 if (Flags.isByVal())
2054 ArgSize = Flags.getByValSize();
2055 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2061 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2062 CallingConv::ID CallConv, bool isVarArg,
2063 const SmallVectorImpl<ISD::InputArg>
2065 SDLoc dl, SelectionDAG &DAG,
2066 SmallVectorImpl<SDValue> &InVals)
2068 if (PPCSubTarget.isSVR4ABI()) {
2069 if (PPCSubTarget.isPPC64())
2070 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2073 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2076 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2082 PPCTargetLowering::LowerFormalArguments_32SVR4(
2084 CallingConv::ID CallConv, bool isVarArg,
2085 const SmallVectorImpl<ISD::InputArg>
2087 SDLoc dl, SelectionDAG &DAG,
2088 SmallVectorImpl<SDValue> &InVals) const {
2090 // 32-bit SVR4 ABI Stack Frame Layout:
2091 // +-----------------------------------+
2092 // +--> | Back chain |
2093 // | +-----------------------------------+
2094 // | | Floating-point register save area |
2095 // | +-----------------------------------+
2096 // | | General register save area |
2097 // | +-----------------------------------+
2098 // | | CR save word |
2099 // | +-----------------------------------+
2100 // | | VRSAVE save word |
2101 // | +-----------------------------------+
2102 // | | Alignment padding |
2103 // | +-----------------------------------+
2104 // | | Vector register save area |
2105 // | +-----------------------------------+
2106 // | | Local variable space |
2107 // | +-----------------------------------+
2108 // | | Parameter list area |
2109 // | +-----------------------------------+
2110 // | | LR save word |
2111 // | +-----------------------------------+
2112 // SP--> +--- | Back chain |
2113 // +-----------------------------------+
2116 // System V Application Binary Interface PowerPC Processor Supplement
2117 // AltiVec Technology Programming Interface Manual
2119 MachineFunction &MF = DAG.getMachineFunction();
2120 MachineFrameInfo *MFI = MF.getFrameInfo();
2121 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2123 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2124 // Potential tail calls could cause overwriting of argument stack slots.
2125 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2126 (CallConv == CallingConv::Fast));
2127 unsigned PtrByteSize = 4;
2129 // Assign locations to all of the incoming arguments.
2130 SmallVector<CCValAssign, 16> ArgLocs;
2131 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2132 getTargetMachine(), ArgLocs, *DAG.getContext());
2134 // Reserve space for the linkage area on the stack.
2135 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2137 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2139 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2140 CCValAssign &VA = ArgLocs[i];
2142 // Arguments stored in registers.
2143 if (VA.isRegLoc()) {
2144 const TargetRegisterClass *RC;
2145 EVT ValVT = VA.getValVT();
2147 switch (ValVT.getSimpleVT().SimpleTy) {
2149 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2152 RC = &PPC::GPRCRegClass;
2155 RC = &PPC::F4RCRegClass;
2158 RC = &PPC::F8RCRegClass;
2166 RC = &PPC::VRRCRegClass;
2170 // Transform the arguments stored in physical registers into virtual ones.
2171 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2172 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2173 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2175 if (ValVT == MVT::i1)
2176 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2178 InVals.push_back(ArgValue);
2180 // Argument stored in memory.
2181 assert(VA.isMemLoc());
2183 unsigned ArgSize = VA.getLocVT().getStoreSize();
2184 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2187 // Create load nodes to retrieve arguments from the stack.
2188 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2189 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2190 MachinePointerInfo(),
2191 false, false, false, 0));
2195 // Assign locations to all of the incoming aggregate by value arguments.
2196 // Aggregates passed by value are stored in the local variable space of the
2197 // caller's stack frame, right above the parameter list area.
2198 SmallVector<CCValAssign, 16> ByValArgLocs;
2199 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2200 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2202 // Reserve stack space for the allocations in CCInfo.
2203 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2205 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2207 // Area that is at least reserved in the caller of this function.
2208 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2210 // Set the size that is at least reserved in caller of this function. Tail
2211 // call optimized function's reserved stack space needs to be aligned so that
2212 // taking the difference between two stack areas will result in an aligned
2214 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2217 std::max(MinReservedArea,
2218 PPCFrameLowering::getMinCallFrameSize(false, false));
2220 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2221 getStackAlignment();
2222 unsigned AlignMask = TargetAlign-1;
2223 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2225 FI->setMinReservedArea(MinReservedArea);
2227 SmallVector<SDValue, 8> MemOps;
2229 // If the function takes variable number of arguments, make a frame index for
2230 // the start of the first vararg value... for expansion of llvm.va_start.
2232 static const uint16_t GPArgRegs[] = {
2233 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2234 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2236 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2238 static const uint16_t FPArgRegs[] = {
2239 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2242 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2244 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2246 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2249 // Make room for NumGPArgRegs and NumFPArgRegs.
2250 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2251 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2253 FuncInfo->setVarArgsStackOffset(
2254 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2255 CCInfo.getNextStackOffset(), true));
2257 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2258 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2260 // The fixed integer arguments of a variadic function are stored to the
2261 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2262 // the result of va_next.
2263 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2264 // Get an existing live-in vreg, or add a new one.
2265 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2267 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2269 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2270 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2271 MachinePointerInfo(), false, false, 0);
2272 MemOps.push_back(Store);
2273 // Increment the address by four for the next argument to store
2274 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2275 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2278 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2280 // The double arguments are stored to the VarArgsFrameIndex
2282 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2283 // Get an existing live-in vreg, or add a new one.
2284 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2286 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2288 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2289 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2290 MachinePointerInfo(), false, false, 0);
2291 MemOps.push_back(Store);
2292 // Increment the address by eight for the next argument to store
2293 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2295 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2299 if (!MemOps.empty())
2300 Chain = DAG.getNode(ISD::TokenFactor, dl,
2301 MVT::Other, &MemOps[0], MemOps.size());
2306 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2307 // value to MVT::i64 and then truncate to the correct register size.
2309 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2310 SelectionDAG &DAG, SDValue ArgVal,
2313 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2314 DAG.getValueType(ObjectVT));
2315 else if (Flags.isZExt())
2316 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2317 DAG.getValueType(ObjectVT));
2319 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2322 // Set the size that is at least reserved in caller of this function. Tail
2323 // call optimized functions' reserved stack space needs to be aligned so that
2324 // taking the difference between two stack areas will result in an aligned
2327 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2328 unsigned nAltivecParamsAtEnd,
2329 unsigned MinReservedArea,
2330 bool isPPC64) const {
2331 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2332 // Add the Altivec parameters at the end, if needed.
2333 if (nAltivecParamsAtEnd) {
2334 MinReservedArea = ((MinReservedArea+15)/16)*16;
2335 MinReservedArea += 16*nAltivecParamsAtEnd;
2338 std::max(MinReservedArea,
2339 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2340 unsigned TargetAlign
2341 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2342 getStackAlignment();
2343 unsigned AlignMask = TargetAlign-1;
2344 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2345 FI->setMinReservedArea(MinReservedArea);
2349 PPCTargetLowering::LowerFormalArguments_64SVR4(
2351 CallingConv::ID CallConv, bool isVarArg,
2352 const SmallVectorImpl<ISD::InputArg>
2354 SDLoc dl, SelectionDAG &DAG,
2355 SmallVectorImpl<SDValue> &InVals) const {
2356 // TODO: add description of PPC stack frame format, or at least some docs.
2358 MachineFunction &MF = DAG.getMachineFunction();
2359 MachineFrameInfo *MFI = MF.getFrameInfo();
2360 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2362 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2363 // Potential tail calls could cause overwriting of argument stack slots.
2364 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2365 (CallConv == CallingConv::Fast));
2366 unsigned PtrByteSize = 8;
2368 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2369 // Area that is at least reserved in caller of this function.
2370 unsigned MinReservedArea = ArgOffset;
2372 static const uint16_t GPR[] = {
2373 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2374 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2377 static const uint16_t *FPR = GetFPR();
2379 static const uint16_t VR[] = {
2380 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2381 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2384 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2385 const unsigned Num_FPR_Regs = 13;
2386 const unsigned Num_VR_Regs = array_lengthof(VR);
2388 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2390 // Add DAG nodes to load the arguments or copy them out of registers. On
2391 // entry to a function on PPC, the arguments start after the linkage area,
2392 // although the first ones are often in registers.
2394 SmallVector<SDValue, 8> MemOps;
2395 unsigned nAltivecParamsAtEnd = 0;
2396 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2397 unsigned CurArgIdx = 0;
2398 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2400 bool needsLoad = false;
2401 EVT ObjectVT = Ins[ArgNo].VT;
2402 unsigned ObjSize = ObjectVT.getStoreSize();
2403 unsigned ArgSize = ObjSize;
2404 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2405 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2406 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2408 unsigned CurArgOffset = ArgOffset;
2410 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2411 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2412 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2413 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2415 MinReservedArea = ((MinReservedArea+15)/16)*16;
2416 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2420 nAltivecParamsAtEnd++;
2422 // Calculate min reserved area.
2423 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2427 // FIXME the codegen can be much improved in some cases.
2428 // We do not have to keep everything in memory.
2429 if (Flags.isByVal()) {
2430 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2431 ObjSize = Flags.getByValSize();
2432 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2433 // Empty aggregate parameters do not take up registers. Examples:
2437 // etc. However, we have to provide a place-holder in InVals, so
2438 // pretend we have an 8-byte item at the current address for that
2441 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2442 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2443 InVals.push_back(FIN);
2447 unsigned BVAlign = Flags.getByValAlign();
2449 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2450 CurArgOffset = ArgOffset;
2453 // All aggregates smaller than 8 bytes must be passed right-justified.
2454 if (ObjSize < PtrByteSize)
2455 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2456 // The value of the object is its address.
2457 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2458 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2459 InVals.push_back(FIN);
2462 if (GPR_idx != Num_GPR_Regs) {
2463 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2464 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2467 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2468 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2469 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2470 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2471 MachinePointerInfo(FuncArg),
2472 ObjType, false, false, 0);
2474 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2475 // store the whole register as-is to the parameter save area
2476 // slot. The address of the parameter was already calculated
2477 // above (InVals.push_back(FIN)) to be the right-justified
2478 // offset within the slot. For this store, we need a new
2479 // frame index that points at the beginning of the slot.
2480 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2481 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2482 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2483 MachinePointerInfo(FuncArg),
2487 MemOps.push_back(Store);
2490 // Whether we copied from a register or not, advance the offset
2491 // into the parameter save area by a full doubleword.
2492 ArgOffset += PtrByteSize;
2496 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2497 // Store whatever pieces of the object are in registers
2498 // to memory. ArgOffset will be the address of the beginning
2500 if (GPR_idx != Num_GPR_Regs) {
2502 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2503 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2504 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2505 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2506 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2507 MachinePointerInfo(FuncArg, j),
2509 MemOps.push_back(Store);
2511 ArgOffset += PtrByteSize;
2513 ArgOffset += ArgSize - j;
2520 switch (ObjectVT.getSimpleVT().SimpleTy) {
2521 default: llvm_unreachable("Unhandled argument type!");
2525 if (GPR_idx != Num_GPR_Regs) {
2526 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2527 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2529 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2530 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2531 // value to MVT::i64 and then truncate to the correct register size.
2532 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2537 ArgSize = PtrByteSize;
2544 // Every 8 bytes of argument space consumes one of the GPRs available for
2545 // argument passing.
2546 if (GPR_idx != Num_GPR_Regs) {
2549 if (FPR_idx != Num_FPR_Regs) {
2552 if (ObjectVT == MVT::f32)
2553 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2555 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2557 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2561 ArgSize = PtrByteSize;
2572 // Note that vector arguments in registers don't reserve stack space,
2573 // except in varargs functions.
2574 if (VR_idx != Num_VR_Regs) {
2575 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2576 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2578 while ((ArgOffset % 16) != 0) {
2579 ArgOffset += PtrByteSize;
2580 if (GPR_idx != Num_GPR_Regs)
2584 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2588 // Vectors are aligned.
2589 ArgOffset = ((ArgOffset+15)/16)*16;
2590 CurArgOffset = ArgOffset;
2597 // We need to load the argument to a virtual register if we determined
2598 // above that we ran out of physical registers of the appropriate type.
2600 int FI = MFI->CreateFixedObject(ObjSize,
2601 CurArgOffset + (ArgSize - ObjSize),
2603 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2604 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2605 false, false, false, 0);
2608 InVals.push_back(ArgVal);
2611 // Set the size that is at least reserved in caller of this function. Tail
2612 // call optimized functions' reserved stack space needs to be aligned so that
2613 // taking the difference between two stack areas will result in an aligned
2615 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2617 // If the function takes variable number of arguments, make a frame index for
2618 // the start of the first vararg value... for expansion of llvm.va_start.
2620 int Depth = ArgOffset;
2622 FuncInfo->setVarArgsFrameIndex(
2623 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2624 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2626 // If this function is vararg, store any remaining integer argument regs
2627 // to their spots on the stack so that they may be loaded by deferencing the
2628 // result of va_next.
2629 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2630 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2631 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2632 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2633 MachinePointerInfo(), false, false, 0);
2634 MemOps.push_back(Store);
2635 // Increment the address by four for the next argument to store
2636 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2637 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2641 if (!MemOps.empty())
2642 Chain = DAG.getNode(ISD::TokenFactor, dl,
2643 MVT::Other, &MemOps[0], MemOps.size());
2649 PPCTargetLowering::LowerFormalArguments_Darwin(
2651 CallingConv::ID CallConv, bool isVarArg,
2652 const SmallVectorImpl<ISD::InputArg>
2654 SDLoc dl, SelectionDAG &DAG,
2655 SmallVectorImpl<SDValue> &InVals) const {
2656 // TODO: add description of PPC stack frame format, or at least some docs.
2658 MachineFunction &MF = DAG.getMachineFunction();
2659 MachineFrameInfo *MFI = MF.getFrameInfo();
2660 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2662 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2663 bool isPPC64 = PtrVT == MVT::i64;
2664 // Potential tail calls could cause overwriting of argument stack slots.
2665 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2666 (CallConv == CallingConv::Fast));
2667 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2669 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2670 // Area that is at least reserved in caller of this function.
2671 unsigned MinReservedArea = ArgOffset;
2673 static const uint16_t GPR_32[] = { // 32-bit registers.
2674 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2675 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2677 static const uint16_t GPR_64[] = { // 64-bit registers.
2678 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2679 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2682 static const uint16_t *FPR = GetFPR();
2684 static const uint16_t VR[] = {
2685 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2686 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2689 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2690 const unsigned Num_FPR_Regs = 13;
2691 const unsigned Num_VR_Regs = array_lengthof( VR);
2693 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2695 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2697 // In 32-bit non-varargs functions, the stack space for vectors is after the
2698 // stack space for non-vectors. We do not use this space unless we have
2699 // too many vectors to fit in registers, something that only occurs in
2700 // constructed examples:), but we have to walk the arglist to figure
2701 // that out...for the pathological case, compute VecArgOffset as the
2702 // start of the vector parameter area. Computing VecArgOffset is the
2703 // entire point of the following loop.
2704 unsigned VecArgOffset = ArgOffset;
2705 if (!isVarArg && !isPPC64) {
2706 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2708 EVT ObjectVT = Ins[ArgNo].VT;
2709 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2711 if (Flags.isByVal()) {
2712 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2713 unsigned ObjSize = Flags.getByValSize();
2715 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2716 VecArgOffset += ArgSize;
2720 switch(ObjectVT.getSimpleVT().SimpleTy) {
2721 default: llvm_unreachable("Unhandled argument type!");
2727 case MVT::i64: // PPC64
2729 // FIXME: We are guaranteed to be !isPPC64 at this point.
2730 // Does MVT::i64 apply?
2737 // Nothing to do, we're only looking at Nonvector args here.
2742 // We've found where the vector parameter area in memory is. Skip the
2743 // first 12 parameters; these don't use that memory.
2744 VecArgOffset = ((VecArgOffset+15)/16)*16;
2745 VecArgOffset += 12*16;
2747 // Add DAG nodes to load the arguments or copy them out of registers. On
2748 // entry to a function on PPC, the arguments start after the linkage area,
2749 // although the first ones are often in registers.
2751 SmallVector<SDValue, 8> MemOps;
2752 unsigned nAltivecParamsAtEnd = 0;
2753 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2754 unsigned CurArgIdx = 0;
2755 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2757 bool needsLoad = false;
2758 EVT ObjectVT = Ins[ArgNo].VT;
2759 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2760 unsigned ArgSize = ObjSize;
2761 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2762 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2763 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2765 unsigned CurArgOffset = ArgOffset;
2767 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2768 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2769 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2770 if (isVarArg || isPPC64) {
2771 MinReservedArea = ((MinReservedArea+15)/16)*16;
2772 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2775 } else nAltivecParamsAtEnd++;
2777 // Calculate min reserved area.
2778 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2782 // FIXME the codegen can be much improved in some cases.
2783 // We do not have to keep everything in memory.
2784 if (Flags.isByVal()) {
2785 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2786 ObjSize = Flags.getByValSize();
2787 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2788 // Objects of size 1 and 2 are right justified, everything else is
2789 // left justified. This means the memory address is adjusted forwards.
2790 if (ObjSize==1 || ObjSize==2) {
2791 CurArgOffset = CurArgOffset + (4 - ObjSize);
2793 // The value of the object is its address.
2794 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2795 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2796 InVals.push_back(FIN);
2797 if (ObjSize==1 || ObjSize==2) {
2798 if (GPR_idx != Num_GPR_Regs) {
2801 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2803 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2804 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2805 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2806 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2807 MachinePointerInfo(FuncArg),
2808 ObjType, false, false, 0);
2809 MemOps.push_back(Store);
2813 ArgOffset += PtrByteSize;
2817 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2818 // Store whatever pieces of the object are in registers
2819 // to memory. ArgOffset will be the address of the beginning
2821 if (GPR_idx != Num_GPR_Regs) {
2824 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2826 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2827 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2828 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2829 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2830 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2831 MachinePointerInfo(FuncArg, j),
2833 MemOps.push_back(Store);
2835 ArgOffset += PtrByteSize;
2837 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2844 switch (ObjectVT.getSimpleVT().SimpleTy) {
2845 default: llvm_unreachable("Unhandled argument type!");
2849 if (GPR_idx != Num_GPR_Regs) {
2850 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2851 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2853 if (ObjectVT == MVT::i1)
2854 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2859 ArgSize = PtrByteSize;
2861 // All int arguments reserve stack space in the Darwin ABI.
2862 ArgOffset += PtrByteSize;
2866 case MVT::i64: // PPC64
2867 if (GPR_idx != Num_GPR_Regs) {
2868 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2869 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2871 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2872 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2873 // value to MVT::i64 and then truncate to the correct register size.
2874 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2879 ArgSize = PtrByteSize;
2881 // All int arguments reserve stack space in the Darwin ABI.
2887 // Every 4 bytes of argument space consumes one of the GPRs available for
2888 // argument passing.
2889 if (GPR_idx != Num_GPR_Regs) {
2891 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2894 if (FPR_idx != Num_FPR_Regs) {
2897 if (ObjectVT == MVT::f32)
2898 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2900 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2902 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2908 // All FP arguments reserve stack space in the Darwin ABI.
2909 ArgOffset += isPPC64 ? 8 : ObjSize;
2915 // Note that vector arguments in registers don't reserve stack space,
2916 // except in varargs functions.
2917 if (VR_idx != Num_VR_Regs) {
2918 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2919 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2921 while ((ArgOffset % 16) != 0) {
2922 ArgOffset += PtrByteSize;
2923 if (GPR_idx != Num_GPR_Regs)
2927 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2931 if (!isVarArg && !isPPC64) {
2932 // Vectors go after all the nonvectors.
2933 CurArgOffset = VecArgOffset;
2936 // Vectors are aligned.
2937 ArgOffset = ((ArgOffset+15)/16)*16;
2938 CurArgOffset = ArgOffset;
2946 // We need to load the argument to a virtual register if we determined above
2947 // that we ran out of physical registers of the appropriate type.
2949 int FI = MFI->CreateFixedObject(ObjSize,
2950 CurArgOffset + (ArgSize - ObjSize),
2952 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2953 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2954 false, false, false, 0);
2957 InVals.push_back(ArgVal);
2960 // Set the size that is at least reserved in caller of this function. Tail
2961 // call optimized functions' reserved stack space needs to be aligned so that
2962 // taking the difference between two stack areas will result in an aligned
2964 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2966 // If the function takes variable number of arguments, make a frame index for
2967 // the start of the first vararg value... for expansion of llvm.va_start.
2969 int Depth = ArgOffset;
2971 FuncInfo->setVarArgsFrameIndex(
2972 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2974 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2976 // If this function is vararg, store any remaining integer argument regs
2977 // to their spots on the stack so that they may be loaded by deferencing the
2978 // result of va_next.
2979 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2983 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2985 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2987 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2988 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2989 MachinePointerInfo(), false, false, 0);
2990 MemOps.push_back(Store);
2991 // Increment the address by four for the next argument to store
2992 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2993 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2997 if (!MemOps.empty())
2998 Chain = DAG.getNode(ISD::TokenFactor, dl,
2999 MVT::Other, &MemOps[0], MemOps.size());
3004 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3005 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3007 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3011 const SmallVectorImpl<ISD::OutputArg>
3013 const SmallVectorImpl<SDValue> &OutVals,
3014 unsigned &nAltivecParamsAtEnd) {
3015 // Count how many bytes are to be pushed on the stack, including the linkage
3016 // area, and parameter passing area. We start with 24/48 bytes, which is
3017 // prereserved space for [SP][CR][LR][3 x unused].
3018 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3019 unsigned NumOps = Outs.size();
3020 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3022 // Add up all the space actually used.
3023 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3024 // they all go in registers, but we must reserve stack space for them for
3025 // possible use by the caller. In varargs or 64-bit calls, parameters are
3026 // assigned stack space in order, with padding so Altivec parameters are
3028 nAltivecParamsAtEnd = 0;
3029 for (unsigned i = 0; i != NumOps; ++i) {
3030 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3031 EVT ArgVT = Outs[i].VT;
3032 // Varargs Altivec parameters are padded to a 16 byte boundary.
3033 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3034 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3035 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3036 if (!isVarArg && !isPPC64) {
3037 // Non-varargs Altivec parameters go after all the non-Altivec
3038 // parameters; handle those later so we know how much padding we need.
3039 nAltivecParamsAtEnd++;
3042 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3043 NumBytes = ((NumBytes+15)/16)*16;
3045 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3048 // Allow for Altivec parameters at the end, if needed.
3049 if (nAltivecParamsAtEnd) {
3050 NumBytes = ((NumBytes+15)/16)*16;
3051 NumBytes += 16*nAltivecParamsAtEnd;
3054 // The prolog code of the callee may store up to 8 GPR argument registers to
3055 // the stack, allowing va_start to index over them in memory if its varargs.
3056 // Because we cannot tell if this is needed on the caller side, we have to
3057 // conservatively assume that it is needed. As such, make sure we have at
3058 // least enough stack space for the caller to store the 8 GPRs.
3059 NumBytes = std::max(NumBytes,
3060 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3062 // Tail call needs the stack to be aligned.
3063 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3064 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3065 getFrameLowering()->getStackAlignment();
3066 unsigned AlignMask = TargetAlign-1;
3067 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3073 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3074 /// adjusted to accommodate the arguments for the tailcall.
3075 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3076 unsigned ParamSize) {
3078 if (!isTailCall) return 0;
3080 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3081 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3082 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3083 // Remember only if the new adjustement is bigger.
3084 if (SPDiff < FI->getTailCallSPDelta())
3085 FI->setTailCallSPDelta(SPDiff);
3090 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3091 /// for tail call optimization. Targets which want to do tail call
3092 /// optimization should implement this function.
3094 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3095 CallingConv::ID CalleeCC,
3097 const SmallVectorImpl<ISD::InputArg> &Ins,
3098 SelectionDAG& DAG) const {
3099 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3102 // Variable argument functions are not supported.
3106 MachineFunction &MF = DAG.getMachineFunction();
3107 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3108 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3109 // Functions containing by val parameters are not supported.
3110 for (unsigned i = 0; i != Ins.size(); i++) {
3111 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3112 if (Flags.isByVal()) return false;
3115 // Non-PIC/GOT tail calls are supported.
3116 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3119 // At the moment we can only do local tail calls (in same module, hidden
3120 // or protected) if we are generating PIC.
3121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3122 return G->getGlobal()->hasHiddenVisibility()
3123 || G->getGlobal()->hasProtectedVisibility();
3129 /// isCallCompatibleAddress - Return the immediate to use if the specified
3130 /// 32-bit value is representable in the immediate field of a BxA instruction.
3131 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3135 int Addr = C->getZExtValue();
3136 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3137 SignExtend32<26>(Addr) != Addr)
3138 return 0; // Top 6 bits have to be sext of immediate.
3140 return DAG.getConstant((int)C->getZExtValue() >> 2,
3141 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3146 struct TailCallArgumentInfo {
3151 TailCallArgumentInfo() : FrameIdx(0) {}
3156 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3158 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3160 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3161 SmallVectorImpl<SDValue> &MemOpChains,
3163 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3164 SDValue Arg = TailCallArgs[i].Arg;
3165 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3166 int FI = TailCallArgs[i].FrameIdx;
3167 // Store relative to framepointer.
3168 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3169 MachinePointerInfo::getFixedStack(FI),
3174 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3175 /// the appropriate stack slot for the tail call optimized function call.
3176 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3177 MachineFunction &MF,
3186 // Calculate the new stack slot for the return address.
3187 int SlotSize = isPPC64 ? 8 : 4;
3188 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3190 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3191 NewRetAddrLoc, true);
3192 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3193 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3194 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3195 MachinePointerInfo::getFixedStack(NewRetAddr),
3198 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3199 // slot as the FP is never overwritten.
3202 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3203 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3205 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3206 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3207 MachinePointerInfo::getFixedStack(NewFPIdx),
3214 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3215 /// the position of the argument.
3217 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3218 SDValue Arg, int SPDiff, unsigned ArgOffset,
3219 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3220 int Offset = ArgOffset + SPDiff;
3221 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3222 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3223 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3224 SDValue FIN = DAG.getFrameIndex(FI, VT);
3225 TailCallArgumentInfo Info;
3227 Info.FrameIdxOp = FIN;
3229 TailCallArguments.push_back(Info);
3232 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3233 /// stack slot. Returns the chain as result and the loaded frame pointers in
3234 /// LROpOut/FPOpout. Used when tail calling.
3235 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3243 // Load the LR and FP stack slot for later adjusting.
3244 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3245 LROpOut = getReturnAddrFrameIndex(DAG);
3246 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3247 false, false, false, 0);
3248 Chain = SDValue(LROpOut.getNode(), 1);
3250 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3251 // slot as the FP is never overwritten.
3253 FPOpOut = getFramePointerFrameIndex(DAG);
3254 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3255 false, false, false, 0);
3256 Chain = SDValue(FPOpOut.getNode(), 1);
3262 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3263 /// by "Src" to address "Dst" of size "Size". Alignment information is
3264 /// specified by the specific parameter attribute. The copy will be passed as
3265 /// a byval function parameter.
3266 /// Sometimes what we are copying is the end of a larger object, the part that
3267 /// does not fit in registers.
3269 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3270 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3272 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3273 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3274 false, false, MachinePointerInfo(0),
3275 MachinePointerInfo(0));
3278 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3281 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3282 SDValue Arg, SDValue PtrOff, int SPDiff,
3283 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3284 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3285 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3287 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3292 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3294 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3295 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3296 DAG.getConstant(ArgOffset, PtrVT));
3298 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3299 MachinePointerInfo(), false, false, 0));
3300 // Calculate and remember argument location.
3301 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3306 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3307 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3308 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3309 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3310 MachineFunction &MF = DAG.getMachineFunction();
3312 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3313 // might overwrite each other in case of tail call optimization.
3314 SmallVector<SDValue, 8> MemOpChains2;
3315 // Do not flag preceding copytoreg stuff together with the following stuff.
3317 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3319 if (!MemOpChains2.empty())
3320 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3321 &MemOpChains2[0], MemOpChains2.size());
3323 // Store the return address to the appropriate stack slot.
3324 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3325 isPPC64, isDarwinABI, dl);
3327 // Emit callseq_end just before tailcall node.
3328 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3329 DAG.getIntPtrConstant(0, true), InFlag, dl);
3330 InFlag = Chain.getValue(1);
3334 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3335 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3336 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3337 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3338 const PPCSubtarget &PPCSubTarget) {
3340 bool isPPC64 = PPCSubTarget.isPPC64();
3341 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3343 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3344 NodeTys.push_back(MVT::Other); // Returns a chain
3345 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3347 unsigned CallOpc = PPCISD::CALL;
3349 bool needIndirectCall = true;
3350 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3351 // If this is an absolute destination address, use the munged value.
3352 Callee = SDValue(Dest, 0);
3353 needIndirectCall = false;
3356 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3357 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3358 // Use indirect calls for ALL functions calls in JIT mode, since the
3359 // far-call stubs may be outside relocation limits for a BL instruction.
3360 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3361 unsigned OpFlags = 0;
3362 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3363 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3364 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3365 (G->getGlobal()->isDeclaration() ||
3366 G->getGlobal()->isWeakForLinker())) {
3367 // PC-relative references to external symbols should go through $stub,
3368 // unless we're building with the leopard linker or later, which
3369 // automatically synthesizes these stubs.
3370 OpFlags = PPCII::MO_DARWIN_STUB;
3373 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3374 // every direct call is) turn it into a TargetGlobalAddress /
3375 // TargetExternalSymbol node so that legalize doesn't hack it.
3376 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3377 Callee.getValueType(),
3379 needIndirectCall = false;
3383 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3384 unsigned char OpFlags = 0;
3386 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3387 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3388 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3389 // PC-relative references to external symbols should go through $stub,
3390 // unless we're building with the leopard linker or later, which
3391 // automatically synthesizes these stubs.
3392 OpFlags = PPCII::MO_DARWIN_STUB;
3395 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3397 needIndirectCall = false;
3400 if (needIndirectCall) {
3401 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3402 // to do the call, we can't use PPCISD::CALL.
3403 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3405 if (isSVR4ABI && isPPC64) {
3406 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3407 // entry point, but to the function descriptor (the function entry point
3408 // address is part of the function descriptor though).
3409 // The function descriptor is a three doubleword structure with the
3410 // following fields: function entry point, TOC base address and
3411 // environment pointer.
3412 // Thus for a call through a function pointer, the following actions need
3414 // 1. Save the TOC of the caller in the TOC save area of its stack
3415 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3416 // 2. Load the address of the function entry point from the function
3418 // 3. Load the TOC of the callee from the function descriptor into r2.
3419 // 4. Load the environment pointer from the function descriptor into
3421 // 5. Branch to the function entry point address.
3422 // 6. On return of the callee, the TOC of the caller needs to be
3423 // restored (this is done in FinishCall()).
3425 // All those operations are flagged together to ensure that no other
3426 // operations can be scheduled in between. E.g. without flagging the
3427 // operations together, a TOC access in the caller could be scheduled
3428 // between the load of the callee TOC and the branch to the callee, which
3429 // results in the TOC access going through the TOC of the callee instead
3430 // of going through the TOC of the caller, which leads to incorrect code.
3432 // Load the address of the function entry point from the function
3434 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3435 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3436 InFlag.getNode() ? 3 : 2);
3437 Chain = LoadFuncPtr.getValue(1);
3438 InFlag = LoadFuncPtr.getValue(2);
3440 // Load environment pointer into r11.
3441 // Offset of the environment pointer within the function descriptor.
3442 SDValue PtrOff = DAG.getIntPtrConstant(16);
3444 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3445 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3447 Chain = LoadEnvPtr.getValue(1);
3448 InFlag = LoadEnvPtr.getValue(2);
3450 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3452 Chain = EnvVal.getValue(0);
3453 InFlag = EnvVal.getValue(1);
3455 // Load TOC of the callee into r2. We are using a target-specific load
3456 // with r2 hard coded, because the result of a target-independent load
3457 // would never go directly into r2, since r2 is a reserved register (which
3458 // prevents the register allocator from allocating it), resulting in an
3459 // additional register being allocated and an unnecessary move instruction
3461 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3462 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3464 Chain = LoadTOCPtr.getValue(0);
3465 InFlag = LoadTOCPtr.getValue(1);
3467 MTCTROps[0] = Chain;
3468 MTCTROps[1] = LoadFuncPtr;
3469 MTCTROps[2] = InFlag;
3472 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3473 2 + (InFlag.getNode() != 0));
3474 InFlag = Chain.getValue(1);
3477 NodeTys.push_back(MVT::Other);
3478 NodeTys.push_back(MVT::Glue);
3479 Ops.push_back(Chain);
3480 CallOpc = PPCISD::BCTRL;
3482 // Add use of X11 (holding environment pointer)
3483 if (isSVR4ABI && isPPC64)
3484 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3485 // Add CTR register as callee so a bctr can be emitted later.
3487 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3490 // If this is a direct call, pass the chain and the callee.
3491 if (Callee.getNode()) {
3492 Ops.push_back(Chain);
3493 Ops.push_back(Callee);
3495 // If this is a tail call add stack pointer delta.
3497 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3499 // Add argument registers to the end of the list so that they are known live
3501 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3502 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3503 RegsToPass[i].second.getValueType()));
3509 bool isLocalCall(const SDValue &Callee)
3511 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3512 return !G->getGlobal()->isDeclaration() &&
3513 !G->getGlobal()->isWeakForLinker();
3518 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3519 CallingConv::ID CallConv, bool isVarArg,
3520 const SmallVectorImpl<ISD::InputArg> &Ins,
3521 SDLoc dl, SelectionDAG &DAG,
3522 SmallVectorImpl<SDValue> &InVals) const {
3524 SmallVector<CCValAssign, 16> RVLocs;
3525 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3526 getTargetMachine(), RVLocs, *DAG.getContext());
3527 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3529 // Copy all of the result registers out of their specified physreg.
3530 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3531 CCValAssign &VA = RVLocs[i];
3532 assert(VA.isRegLoc() && "Can only return in registers!");
3534 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3535 VA.getLocReg(), VA.getLocVT(), InFlag);
3536 Chain = Val.getValue(1);
3537 InFlag = Val.getValue(2);
3539 switch (VA.getLocInfo()) {
3540 default: llvm_unreachable("Unknown loc info!");
3541 case CCValAssign::Full: break;
3542 case CCValAssign::AExt:
3543 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3545 case CCValAssign::ZExt:
3546 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3547 DAG.getValueType(VA.getValVT()));
3548 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3550 case CCValAssign::SExt:
3551 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3552 DAG.getValueType(VA.getValVT()));
3553 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3557 InVals.push_back(Val);
3564 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3565 bool isTailCall, bool isVarArg,
3567 SmallVector<std::pair<unsigned, SDValue>, 8>
3569 SDValue InFlag, SDValue Chain,
3571 int SPDiff, unsigned NumBytes,
3572 const SmallVectorImpl<ISD::InputArg> &Ins,
3573 SmallVectorImpl<SDValue> &InVals) const {
3574 std::vector<EVT> NodeTys;
3575 SmallVector<SDValue, 8> Ops;
3576 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3577 isTailCall, RegsToPass, Ops, NodeTys,
3580 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3581 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3582 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3584 // When performing tail call optimization the callee pops its arguments off
3585 // the stack. Account for this here so these bytes can be pushed back on in
3586 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3587 int BytesCalleePops =
3588 (CallConv == CallingConv::Fast &&
3589 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3591 // Add a register mask operand representing the call-preserved registers.
3592 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3593 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3594 assert(Mask && "Missing call preserved mask for calling convention");
3595 Ops.push_back(DAG.getRegisterMask(Mask));
3597 if (InFlag.getNode())
3598 Ops.push_back(InFlag);
3602 assert(((Callee.getOpcode() == ISD::Register &&
3603 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3604 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3605 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3606 isa<ConstantSDNode>(Callee)) &&
3607 "Expecting an global address, external symbol, absolute value or register");
3609 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3612 // Add a NOP immediately after the branch instruction when using the 64-bit
3613 // SVR4 ABI. At link time, if caller and callee are in a different module and
3614 // thus have a different TOC, the call will be replaced with a call to a stub
3615 // function which saves the current TOC, loads the TOC of the callee and
3616 // branches to the callee. The NOP will be replaced with a load instruction
3617 // which restores the TOC of the caller from the TOC save slot of the current
3618 // stack frame. If caller and callee belong to the same module (and have the
3619 // same TOC), the NOP will remain unchanged.
3621 bool needsTOCRestore = false;
3622 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3623 if (CallOpc == PPCISD::BCTRL) {
3624 // This is a call through a function pointer.
3625 // Restore the caller TOC from the save area into R2.
3626 // See PrepareCall() for more information about calls through function
3627 // pointers in the 64-bit SVR4 ABI.
3628 // We are using a target-specific load with r2 hard coded, because the
3629 // result of a target-independent load would never go directly into r2,
3630 // since r2 is a reserved register (which prevents the register allocator
3631 // from allocating it), resulting in an additional register being
3632 // allocated and an unnecessary move instruction being generated.
3633 needsTOCRestore = true;
3634 } else if ((CallOpc == PPCISD::CALL) &&
3635 (!isLocalCall(Callee) ||
3636 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3637 // Otherwise insert NOP for non-local calls.
3638 CallOpc = PPCISD::CALL_NOP;
3642 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3643 InFlag = Chain.getValue(1);
3645 if (needsTOCRestore) {
3646 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3647 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3648 InFlag = Chain.getValue(1);
3651 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3652 DAG.getIntPtrConstant(BytesCalleePops, true),
3655 InFlag = Chain.getValue(1);
3657 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3658 Ins, dl, DAG, InVals);
3662 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3663 SmallVectorImpl<SDValue> &InVals) const {
3664 SelectionDAG &DAG = CLI.DAG;
3666 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3667 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3668 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3669 SDValue Chain = CLI.Chain;
3670 SDValue Callee = CLI.Callee;
3671 bool &isTailCall = CLI.IsTailCall;
3672 CallingConv::ID CallConv = CLI.CallConv;
3673 bool isVarArg = CLI.IsVarArg;
3676 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3679 if (PPCSubTarget.isSVR4ABI()) {
3680 if (PPCSubTarget.isPPC64())
3681 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3682 isTailCall, Outs, OutVals, Ins,
3685 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3686 isTailCall, Outs, OutVals, Ins,
3690 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3691 isTailCall, Outs, OutVals, Ins,
3696 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3697 CallingConv::ID CallConv, bool isVarArg,
3699 const SmallVectorImpl<ISD::OutputArg> &Outs,
3700 const SmallVectorImpl<SDValue> &OutVals,
3701 const SmallVectorImpl<ISD::InputArg> &Ins,
3702 SDLoc dl, SelectionDAG &DAG,
3703 SmallVectorImpl<SDValue> &InVals) const {
3704 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3705 // of the 32-bit SVR4 ABI stack frame layout.
3707 assert((CallConv == CallingConv::C ||
3708 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3710 unsigned PtrByteSize = 4;
3712 MachineFunction &MF = DAG.getMachineFunction();
3714 // Mark this function as potentially containing a function that contains a
3715 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3716 // and restoring the callers stack pointer in this functions epilog. This is
3717 // done because by tail calling the called function might overwrite the value
3718 // in this function's (MF) stack pointer stack slot 0(SP).
3719 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3720 CallConv == CallingConv::Fast)
3721 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3723 // Count how many bytes are to be pushed on the stack, including the linkage
3724 // area, parameter list area and the part of the local variable space which
3725 // contains copies of aggregates which are passed by value.
3727 // Assign locations to all of the outgoing arguments.
3728 SmallVector<CCValAssign, 16> ArgLocs;
3729 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3730 getTargetMachine(), ArgLocs, *DAG.getContext());
3732 // Reserve space for the linkage area on the stack.
3733 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3736 // Handle fixed and variable vector arguments differently.
3737 // Fixed vector arguments go into registers as long as registers are
3738 // available. Variable vector arguments always go into memory.
3739 unsigned NumArgs = Outs.size();
3741 for (unsigned i = 0; i != NumArgs; ++i) {
3742 MVT ArgVT = Outs[i].VT;
3743 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3746 if (Outs[i].IsFixed) {
3747 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3750 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3756 errs() << "Call operand #" << i << " has unhandled type "
3757 << EVT(ArgVT).getEVTString() << "\n";
3759 llvm_unreachable(0);
3763 // All arguments are treated the same.
3764 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3767 // Assign locations to all of the outgoing aggregate by value arguments.
3768 SmallVector<CCValAssign, 16> ByValArgLocs;
3769 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3770 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3772 // Reserve stack space for the allocations in CCInfo.
3773 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3775 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3777 // Size of the linkage area, parameter list area and the part of the local
3778 // space variable where copies of aggregates which are passed by value are
3780 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3782 // Calculate by how many bytes the stack has to be adjusted in case of tail
3783 // call optimization.
3784 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3786 // Adjust the stack pointer for the new arguments...
3787 // These operations are automatically eliminated by the prolog/epilog pass
3788 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3790 SDValue CallSeqStart = Chain;
3792 // Load the return address and frame pointer so it can be moved somewhere else
3795 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3798 // Set up a copy of the stack pointer for use loading and storing any
3799 // arguments that may not fit in the registers available for argument
3801 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3803 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3804 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3805 SmallVector<SDValue, 8> MemOpChains;
3807 bool seenFloatArg = false;
3808 // Walk the register/memloc assignments, inserting copies/loads.
3809 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3812 CCValAssign &VA = ArgLocs[i];
3813 SDValue Arg = OutVals[i];
3814 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3816 if (Flags.isByVal()) {
3817 // Argument is an aggregate which is passed by value, thus we need to
3818 // create a copy of it in the local variable space of the current stack
3819 // frame (which is the stack frame of the caller) and pass the address of
3820 // this copy to the callee.
3821 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3822 CCValAssign &ByValVA = ByValArgLocs[j++];
3823 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3825 // Memory reserved in the local variable space of the callers stack frame.
3826 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3828 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3829 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3831 // Create a copy of the argument in the local area of the current
3833 SDValue MemcpyCall =
3834 CreateCopyOfByValArgument(Arg, PtrOff,
3835 CallSeqStart.getNode()->getOperand(0),
3838 // This must go outside the CALLSEQ_START..END.
3839 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3840 CallSeqStart.getNode()->getOperand(1),
3842 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3843 NewCallSeqStart.getNode());
3844 Chain = CallSeqStart = NewCallSeqStart;
3846 // Pass the address of the aggregate copy on the stack either in a
3847 // physical register or in the parameter list area of the current stack
3848 // frame to the callee.
3852 if (VA.isRegLoc()) {
3853 if (Arg.getValueType() == MVT::i1)
3854 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3856 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3857 // Put argument in a physical register.
3858 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3860 // Put argument in the parameter list area of the current stack frame.
3861 assert(VA.isMemLoc());
3862 unsigned LocMemOffset = VA.getLocMemOffset();
3865 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3866 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3868 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3869 MachinePointerInfo(),
3872 // Calculate and remember argument location.
3873 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3879 if (!MemOpChains.empty())
3880 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3881 &MemOpChains[0], MemOpChains.size());
3883 // Build a sequence of copy-to-reg nodes chained together with token chain
3884 // and flag operands which copy the outgoing args into the appropriate regs.
3886 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3887 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3888 RegsToPass[i].second, InFlag);
3889 InFlag = Chain.getValue(1);
3892 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3895 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3896 SDValue Ops[] = { Chain, InFlag };
3898 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3899 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3901 InFlag = Chain.getValue(1);
3905 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3906 false, TailCallArguments);
3908 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3909 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3913 // Copy an argument into memory, being careful to do this outside the
3914 // call sequence for the call to which the argument belongs.
3916 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3917 SDValue CallSeqStart,
3918 ISD::ArgFlagsTy Flags,
3921 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3922 CallSeqStart.getNode()->getOperand(0),
3924 // The MEMCPY must go outside the CALLSEQ_START..END.
3925 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3926 CallSeqStart.getNode()->getOperand(1),
3928 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3929 NewCallSeqStart.getNode());
3930 return NewCallSeqStart;
3934 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3935 CallingConv::ID CallConv, bool isVarArg,
3937 const SmallVectorImpl<ISD::OutputArg> &Outs,
3938 const SmallVectorImpl<SDValue> &OutVals,
3939 const SmallVectorImpl<ISD::InputArg> &Ins,
3940 SDLoc dl, SelectionDAG &DAG,
3941 SmallVectorImpl<SDValue> &InVals) const {
3943 unsigned NumOps = Outs.size();
3945 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3946 unsigned PtrByteSize = 8;
3948 MachineFunction &MF = DAG.getMachineFunction();
3950 // Mark this function as potentially containing a function that contains a
3951 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3952 // and restoring the callers stack pointer in this functions epilog. This is
3953 // done because by tail calling the called function might overwrite the value
3954 // in this function's (MF) stack pointer stack slot 0(SP).
3955 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3956 CallConv == CallingConv::Fast)
3957 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3959 unsigned nAltivecParamsAtEnd = 0;
3961 // Count how many bytes are to be pushed on the stack, including the linkage
3962 // area, and parameter passing area. We start with at least 48 bytes, which
3963 // is reserved space for [SP][CR][LR][3 x unused].
3964 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3967 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3968 Outs, OutVals, nAltivecParamsAtEnd);
3970 // Calculate by how many bytes the stack has to be adjusted in case of tail
3971 // call optimization.
3972 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3974 // To protect arguments on the stack from being clobbered in a tail call,
3975 // force all the loads to happen before doing any other lowering.
3977 Chain = DAG.getStackArgumentTokenFactor(Chain);
3979 // Adjust the stack pointer for the new arguments...
3980 // These operations are automatically eliminated by the prolog/epilog pass
3981 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3983 SDValue CallSeqStart = Chain;
3985 // Load the return address and frame pointer so it can be move somewhere else
3988 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3991 // Set up a copy of the stack pointer for use loading and storing any
3992 // arguments that may not fit in the registers available for argument
3994 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3996 // Figure out which arguments are going to go in registers, and which in
3997 // memory. Also, if this is a vararg function, floating point operations
3998 // must be stored to our stack, and loaded into integer regs as well, if
3999 // any integer regs are available for argument passing.
4000 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4001 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4003 static const uint16_t GPR[] = {
4004 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4005 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4007 static const uint16_t *FPR = GetFPR();
4009 static const uint16_t VR[] = {
4010 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4011 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4013 const unsigned NumGPRs = array_lengthof(GPR);
4014 const unsigned NumFPRs = 13;
4015 const unsigned NumVRs = array_lengthof(VR);
4017 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4018 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4020 SmallVector<SDValue, 8> MemOpChains;
4021 for (unsigned i = 0; i != NumOps; ++i) {
4022 SDValue Arg = OutVals[i];
4023 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4025 // PtrOff will be used to store the current argument to the stack if a
4026 // register cannot be found for it.
4029 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4031 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4033 // Promote integers to 64-bit values.
4034 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4035 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4036 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4037 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4040 // FIXME memcpy is used way more than necessary. Correctness first.
4041 // Note: "by value" is code for passing a structure by value, not
4043 if (Flags.isByVal()) {
4044 // Note: Size includes alignment padding, so
4045 // struct x { short a; char b; }
4046 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4047 // These are the proper values we need for right-justifying the
4048 // aggregate in a parameter register.
4049 unsigned Size = Flags.getByValSize();
4051 // An empty aggregate parameter takes up no storage and no
4056 unsigned BVAlign = Flags.getByValAlign();
4058 if (BVAlign % PtrByteSize != 0)
4060 "ByVal alignment is not a multiple of the pointer size");
4062 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4065 // All aggregates smaller than 8 bytes must be passed right-justified.
4066 if (Size==1 || Size==2 || Size==4) {
4067 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4068 if (GPR_idx != NumGPRs) {
4069 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4070 MachinePointerInfo(), VT,
4072 MemOpChains.push_back(Load.getValue(1));
4073 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4075 ArgOffset += PtrByteSize;
4080 if (GPR_idx == NumGPRs && Size < 8) {
4081 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4082 PtrOff.getValueType());
4083 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4084 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4087 ArgOffset += PtrByteSize;
4090 // Copy entire object into memory. There are cases where gcc-generated
4091 // code assumes it is there, even if it could be put entirely into
4092 // registers. (This is not what the doc says.)
4094 // FIXME: The above statement is likely due to a misunderstanding of the
4095 // documents. All arguments must be copied into the parameter area BY
4096 // THE CALLEE in the event that the callee takes the address of any
4097 // formal argument. That has not yet been implemented. However, it is
4098 // reasonable to use the stack area as a staging area for the register
4101 // Skip this for small aggregates, as we will use the same slot for a
4102 // right-justified copy, below.
4104 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4108 // When a register is available, pass a small aggregate right-justified.
4109 if (Size < 8 && GPR_idx != NumGPRs) {
4110 // The easiest way to get this right-justified in a register
4111 // is to copy the structure into the rightmost portion of a
4112 // local variable slot, then load the whole slot into the
4114 // FIXME: The memcpy seems to produce pretty awful code for
4115 // small aggregates, particularly for packed ones.
4116 // FIXME: It would be preferable to use the slot in the
4117 // parameter save area instead of a new local variable.
4118 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4119 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4120 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4124 // Load the slot into the register.
4125 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4126 MachinePointerInfo(),
4127 false, false, false, 0);
4128 MemOpChains.push_back(Load.getValue(1));
4129 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4131 // Done with this argument.
4132 ArgOffset += PtrByteSize;
4136 // For aggregates larger than PtrByteSize, copy the pieces of the
4137 // object that fit into registers from the parameter save area.
4138 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4139 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4140 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4141 if (GPR_idx != NumGPRs) {
4142 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4143 MachinePointerInfo(),
4144 false, false, false, 0);
4145 MemOpChains.push_back(Load.getValue(1));
4146 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4147 ArgOffset += PtrByteSize;
4149 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4156 switch (Arg.getSimpleValueType().SimpleTy) {
4157 default: llvm_unreachable("Unexpected ValueType for argument!");
4161 if (GPR_idx != NumGPRs) {
4162 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4164 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4165 true, isTailCall, false, MemOpChains,
4166 TailCallArguments, dl);
4168 ArgOffset += PtrByteSize;
4172 if (FPR_idx != NumFPRs) {
4173 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4176 // A single float or an aggregate containing only a single float
4177 // must be passed right-justified in the stack doubleword, and
4178 // in the GPR, if one is available.
4180 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4181 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4182 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4186 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4187 MachinePointerInfo(), false, false, 0);
4188 MemOpChains.push_back(Store);
4190 // Float varargs are always shadowed in available integer registers
4191 if (GPR_idx != NumGPRs) {
4192 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4193 MachinePointerInfo(), false, false,
4195 MemOpChains.push_back(Load.getValue(1));
4196 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4198 } else if (GPR_idx != NumGPRs)
4199 // If we have any FPRs remaining, we may also have GPRs remaining.
4202 // Single-precision floating-point values are mapped to the
4203 // second (rightmost) word of the stack doubleword.
4204 if (Arg.getValueType() == MVT::f32) {
4205 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4206 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4209 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4210 true, isTailCall, false, MemOpChains,
4211 TailCallArguments, dl);
4222 // These go aligned on the stack, or in the corresponding R registers
4223 // when within range. The Darwin PPC ABI doc claims they also go in
4224 // V registers; in fact gcc does this only for arguments that are
4225 // prototyped, not for those that match the ... We do it for all
4226 // arguments, seems to work.
4227 while (ArgOffset % 16 !=0) {
4228 ArgOffset += PtrByteSize;
4229 if (GPR_idx != NumGPRs)
4232 // We could elide this store in the case where the object fits
4233 // entirely in R registers. Maybe later.
4234 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4235 DAG.getConstant(ArgOffset, PtrVT));
4236 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4237 MachinePointerInfo(), false, false, 0);
4238 MemOpChains.push_back(Store);
4239 if (VR_idx != NumVRs) {
4240 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4241 MachinePointerInfo(),
4242 false, false, false, 0);
4243 MemOpChains.push_back(Load.getValue(1));
4244 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4247 for (unsigned i=0; i<16; i+=PtrByteSize) {
4248 if (GPR_idx == NumGPRs)
4250 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4251 DAG.getConstant(i, PtrVT));
4252 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4253 false, false, false, 0);
4254 MemOpChains.push_back(Load.getValue(1));
4255 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4260 // Non-varargs Altivec params generally go in registers, but have
4261 // stack space allocated at the end.
4262 if (VR_idx != NumVRs) {
4263 // Doesn't have GPR space allocated.
4264 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4266 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4267 true, isTailCall, true, MemOpChains,
4268 TailCallArguments, dl);
4275 if (!MemOpChains.empty())
4276 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4277 &MemOpChains[0], MemOpChains.size());
4279 // Check if this is an indirect call (MTCTR/BCTRL).
4280 // See PrepareCall() for more information about calls through function
4281 // pointers in the 64-bit SVR4 ABI.
4283 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4284 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4285 !isBLACompatibleAddress(Callee, DAG)) {
4286 // Load r2 into a virtual register and store it to the TOC save area.
4287 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4288 // TOC save area offset.
4289 SDValue PtrOff = DAG.getIntPtrConstant(40);
4290 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4291 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4293 // R12 must contain the address of an indirect callee. This does not
4294 // mean the MTCTR instruction must use R12; it's easier to model this
4295 // as an extra parameter, so do that.
4296 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4299 // Build a sequence of copy-to-reg nodes chained together with token chain
4300 // and flag operands which copy the outgoing args into the appropriate regs.
4302 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4303 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4304 RegsToPass[i].second, InFlag);
4305 InFlag = Chain.getValue(1);
4309 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4310 FPOp, true, TailCallArguments);
4312 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4313 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4318 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4319 CallingConv::ID CallConv, bool isVarArg,
4321 const SmallVectorImpl<ISD::OutputArg> &Outs,
4322 const SmallVectorImpl<SDValue> &OutVals,
4323 const SmallVectorImpl<ISD::InputArg> &Ins,
4324 SDLoc dl, SelectionDAG &DAG,
4325 SmallVectorImpl<SDValue> &InVals) const {
4327 unsigned NumOps = Outs.size();
4329 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4330 bool isPPC64 = PtrVT == MVT::i64;
4331 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4333 MachineFunction &MF = DAG.getMachineFunction();
4335 // Mark this function as potentially containing a function that contains a
4336 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4337 // and restoring the callers stack pointer in this functions epilog. This is
4338 // done because by tail calling the called function might overwrite the value
4339 // in this function's (MF) stack pointer stack slot 0(SP).
4340 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4341 CallConv == CallingConv::Fast)
4342 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4344 unsigned nAltivecParamsAtEnd = 0;
4346 // Count how many bytes are to be pushed on the stack, including the linkage
4347 // area, and parameter passing area. We start with 24/48 bytes, which is
4348 // prereserved space for [SP][CR][LR][3 x unused].
4350 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4352 nAltivecParamsAtEnd);
4354 // Calculate by how many bytes the stack has to be adjusted in case of tail
4355 // call optimization.
4356 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4358 // To protect arguments on the stack from being clobbered in a tail call,
4359 // force all the loads to happen before doing any other lowering.
4361 Chain = DAG.getStackArgumentTokenFactor(Chain);
4363 // Adjust the stack pointer for the new arguments...
4364 // These operations are automatically eliminated by the prolog/epilog pass
4365 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4367 SDValue CallSeqStart = Chain;
4369 // Load the return address and frame pointer so it can be move somewhere else
4372 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4375 // Set up a copy of the stack pointer for use loading and storing any
4376 // arguments that may not fit in the registers available for argument
4380 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4382 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4384 // Figure out which arguments are going to go in registers, and which in
4385 // memory. Also, if this is a vararg function, floating point operations
4386 // must be stored to our stack, and loaded into integer regs as well, if
4387 // any integer regs are available for argument passing.
4388 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4389 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4391 static const uint16_t GPR_32[] = { // 32-bit registers.
4392 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4393 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4395 static const uint16_t GPR_64[] = { // 64-bit registers.
4396 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4397 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4399 static const uint16_t *FPR = GetFPR();
4401 static const uint16_t VR[] = {
4402 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4403 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4405 const unsigned NumGPRs = array_lengthof(GPR_32);
4406 const unsigned NumFPRs = 13;
4407 const unsigned NumVRs = array_lengthof(VR);
4409 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4411 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4412 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4414 SmallVector<SDValue, 8> MemOpChains;
4415 for (unsigned i = 0; i != NumOps; ++i) {
4416 SDValue Arg = OutVals[i];
4417 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4419 // PtrOff will be used to store the current argument to the stack if a
4420 // register cannot be found for it.
4423 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4425 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4427 // On PPC64, promote integers to 64-bit values.
4428 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4429 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4430 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4431 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4434 // FIXME memcpy is used way more than necessary. Correctness first.
4435 // Note: "by value" is code for passing a structure by value, not
4437 if (Flags.isByVal()) {
4438 unsigned Size = Flags.getByValSize();
4439 // Very small objects are passed right-justified. Everything else is
4440 // passed left-justified.
4441 if (Size==1 || Size==2) {
4442 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4443 if (GPR_idx != NumGPRs) {
4444 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4445 MachinePointerInfo(), VT,
4447 MemOpChains.push_back(Load.getValue(1));
4448 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4450 ArgOffset += PtrByteSize;
4452 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4453 PtrOff.getValueType());
4454 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4455 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4458 ArgOffset += PtrByteSize;
4462 // Copy entire object into memory. There are cases where gcc-generated
4463 // code assumes it is there, even if it could be put entirely into
4464 // registers. (This is not what the doc says.)
4465 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4469 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4470 // copy the pieces of the object that fit into registers from the
4471 // parameter save area.
4472 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4473 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4474 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4475 if (GPR_idx != NumGPRs) {
4476 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4477 MachinePointerInfo(),
4478 false, false, false, 0);
4479 MemOpChains.push_back(Load.getValue(1));
4480 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4481 ArgOffset += PtrByteSize;
4483 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4490 switch (Arg.getSimpleValueType().SimpleTy) {
4491 default: llvm_unreachable("Unexpected ValueType for argument!");
4495 if (GPR_idx != NumGPRs) {
4496 if (Arg.getValueType() == MVT::i1)
4497 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4499 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4501 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4502 isPPC64, isTailCall, false, MemOpChains,
4503 TailCallArguments, dl);
4505 ArgOffset += PtrByteSize;
4509 if (FPR_idx != NumFPRs) {
4510 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4513 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4514 MachinePointerInfo(), false, false, 0);
4515 MemOpChains.push_back(Store);
4517 // Float varargs are always shadowed in available integer registers
4518 if (GPR_idx != NumGPRs) {
4519 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4520 MachinePointerInfo(), false, false,
4522 MemOpChains.push_back(Load.getValue(1));
4523 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4525 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4526 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4527 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4528 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4529 MachinePointerInfo(),
4530 false, false, false, 0);
4531 MemOpChains.push_back(Load.getValue(1));
4532 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4535 // If we have any FPRs remaining, we may also have GPRs remaining.
4536 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4538 if (GPR_idx != NumGPRs)
4540 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4541 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4545 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4546 isPPC64, isTailCall, false, MemOpChains,
4547 TailCallArguments, dl);
4551 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4558 // These go aligned on the stack, or in the corresponding R registers
4559 // when within range. The Darwin PPC ABI doc claims they also go in
4560 // V registers; in fact gcc does this only for arguments that are
4561 // prototyped, not for those that match the ... We do it for all
4562 // arguments, seems to work.
4563 while (ArgOffset % 16 !=0) {
4564 ArgOffset += PtrByteSize;
4565 if (GPR_idx != NumGPRs)
4568 // We could elide this store in the case where the object fits
4569 // entirely in R registers. Maybe later.
4570 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4571 DAG.getConstant(ArgOffset, PtrVT));
4572 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4573 MachinePointerInfo(), false, false, 0);
4574 MemOpChains.push_back(Store);
4575 if (VR_idx != NumVRs) {
4576 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4577 MachinePointerInfo(),
4578 false, false, false, 0);
4579 MemOpChains.push_back(Load.getValue(1));
4580 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4583 for (unsigned i=0; i<16; i+=PtrByteSize) {
4584 if (GPR_idx == NumGPRs)
4586 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4587 DAG.getConstant(i, PtrVT));
4588 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4589 false, false, false, 0);
4590 MemOpChains.push_back(Load.getValue(1));
4591 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4596 // Non-varargs Altivec params generally go in registers, but have
4597 // stack space allocated at the end.
4598 if (VR_idx != NumVRs) {
4599 // Doesn't have GPR space allocated.
4600 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4601 } else if (nAltivecParamsAtEnd==0) {
4602 // We are emitting Altivec params in order.
4603 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4604 isPPC64, isTailCall, true, MemOpChains,
4605 TailCallArguments, dl);
4611 // If all Altivec parameters fit in registers, as they usually do,
4612 // they get stack space following the non-Altivec parameters. We
4613 // don't track this here because nobody below needs it.
4614 // If there are more Altivec parameters than fit in registers emit
4616 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4618 // Offset is aligned; skip 1st 12 params which go in V registers.
4619 ArgOffset = ((ArgOffset+15)/16)*16;
4621 for (unsigned i = 0; i != NumOps; ++i) {
4622 SDValue Arg = OutVals[i];
4623 EVT ArgType = Outs[i].VT;
4624 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4625 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4628 // We are emitting Altivec params in order.
4629 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4630 isPPC64, isTailCall, true, MemOpChains,
4631 TailCallArguments, dl);
4638 if (!MemOpChains.empty())
4639 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4640 &MemOpChains[0], MemOpChains.size());
4642 // On Darwin, R12 must contain the address of an indirect callee. This does
4643 // not mean the MTCTR instruction must use R12; it's easier to model this as
4644 // an extra parameter, so do that.
4646 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4647 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4648 !isBLACompatibleAddress(Callee, DAG))
4649 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4650 PPC::R12), Callee));
4652 // Build a sequence of copy-to-reg nodes chained together with token chain
4653 // and flag operands which copy the outgoing args into the appropriate regs.
4655 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4656 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4657 RegsToPass[i].second, InFlag);
4658 InFlag = Chain.getValue(1);
4662 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4663 FPOp, true, TailCallArguments);
4665 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4666 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4671 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4672 MachineFunction &MF, bool isVarArg,
4673 const SmallVectorImpl<ISD::OutputArg> &Outs,
4674 LLVMContext &Context) const {
4675 SmallVector<CCValAssign, 16> RVLocs;
4676 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4678 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4682 PPCTargetLowering::LowerReturn(SDValue Chain,
4683 CallingConv::ID CallConv, bool isVarArg,
4684 const SmallVectorImpl<ISD::OutputArg> &Outs,
4685 const SmallVectorImpl<SDValue> &OutVals,
4686 SDLoc dl, SelectionDAG &DAG) const {
4688 SmallVector<CCValAssign, 16> RVLocs;
4689 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4690 getTargetMachine(), RVLocs, *DAG.getContext());
4691 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4694 SmallVector<SDValue, 4> RetOps(1, Chain);
4696 // Copy the result values into the output registers.
4697 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4698 CCValAssign &VA = RVLocs[i];
4699 assert(VA.isRegLoc() && "Can only return in registers!");
4701 SDValue Arg = OutVals[i];
4703 switch (VA.getLocInfo()) {
4704 default: llvm_unreachable("Unknown loc info!");
4705 case CCValAssign::Full: break;
4706 case CCValAssign::AExt:
4707 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4709 case CCValAssign::ZExt:
4710 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4712 case CCValAssign::SExt:
4713 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4717 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4718 Flag = Chain.getValue(1);
4719 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4722 RetOps[0] = Chain; // Update chain.
4724 // Add the flag if we have it.
4726 RetOps.push_back(Flag);
4728 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4729 &RetOps[0], RetOps.size());
4732 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4733 const PPCSubtarget &Subtarget) const {
4734 // When we pop the dynamic allocation we need to restore the SP link.
4737 // Get the corect type for pointers.
4738 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4740 // Construct the stack pointer operand.
4741 bool isPPC64 = Subtarget.isPPC64();
4742 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4743 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4745 // Get the operands for the STACKRESTORE.
4746 SDValue Chain = Op.getOperand(0);
4747 SDValue SaveSP = Op.getOperand(1);
4749 // Load the old link SP.
4750 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4751 MachinePointerInfo(),
4752 false, false, false, 0);
4754 // Restore the stack pointer.
4755 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4757 // Store the old link SP.
4758 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4765 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4766 MachineFunction &MF = DAG.getMachineFunction();
4767 bool isPPC64 = PPCSubTarget.isPPC64();
4768 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4769 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4771 // Get current frame pointer save index. The users of this index will be
4772 // primarily DYNALLOC instructions.
4773 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4774 int RASI = FI->getReturnAddrSaveIndex();
4776 // If the frame pointer save index hasn't been defined yet.
4778 // Find out what the fix offset of the frame pointer save area.
4779 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4780 // Allocate the frame index for frame pointer save area.
4781 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4783 FI->setReturnAddrSaveIndex(RASI);
4785 return DAG.getFrameIndex(RASI, PtrVT);
4789 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4790 MachineFunction &MF = DAG.getMachineFunction();
4791 bool isPPC64 = PPCSubTarget.isPPC64();
4792 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4793 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4795 // Get current frame pointer save index. The users of this index will be
4796 // primarily DYNALLOC instructions.
4797 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4798 int FPSI = FI->getFramePointerSaveIndex();
4800 // If the frame pointer save index hasn't been defined yet.
4802 // Find out what the fix offset of the frame pointer save area.
4803 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4806 // Allocate the frame index for frame pointer save area.
4807 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4809 FI->setFramePointerSaveIndex(FPSI);
4811 return DAG.getFrameIndex(FPSI, PtrVT);
4814 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4816 const PPCSubtarget &Subtarget) const {
4818 SDValue Chain = Op.getOperand(0);
4819 SDValue Size = Op.getOperand(1);
4822 // Get the corect type for pointers.
4823 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4825 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4826 DAG.getConstant(0, PtrVT), Size);
4827 // Construct a node for the frame pointer save index.
4828 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4829 // Build a DYNALLOC node.
4830 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4831 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4832 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4835 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4836 SelectionDAG &DAG) const {
4838 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4839 DAG.getVTList(MVT::i32, MVT::Other),
4840 Op.getOperand(0), Op.getOperand(1));
4843 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4844 SelectionDAG &DAG) const {
4846 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4847 Op.getOperand(0), Op.getOperand(1));
4850 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4851 assert(Op.getValueType() == MVT::i1 &&
4852 "Custom lowering only for i1 loads");
4854 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4857 LoadSDNode *LD = cast<LoadSDNode>(Op);
4859 SDValue Chain = LD->getChain();
4860 SDValue BasePtr = LD->getBasePtr();
4861 MachineMemOperand *MMO = LD->getMemOperand();
4863 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4864 BasePtr, MVT::i8, MMO);
4865 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4867 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4868 return DAG.getMergeValues(Ops, 2, dl);
4871 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4872 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4873 "Custom lowering only for i1 stores");
4875 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4878 StoreSDNode *ST = cast<StoreSDNode>(Op);
4880 SDValue Chain = ST->getChain();
4881 SDValue BasePtr = ST->getBasePtr();
4882 SDValue Value = ST->getValue();
4883 MachineMemOperand *MMO = ST->getMemOperand();
4885 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4886 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4889 // FIXME: Remove this once the ANDI glue bug is fixed:
4890 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4891 assert(Op.getValueType() == MVT::i1 &&
4892 "Custom lowering only for i1 results");
4895 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4899 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4901 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4902 // Not FP? Not a fsel.
4903 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4904 !Op.getOperand(2).getValueType().isFloatingPoint())
4907 // We might be able to do better than this under some circumstances, but in
4908 // general, fsel-based lowering of select is a finite-math-only optimization.
4909 // For more information, see section F.3 of the 2.06 ISA specification.
4910 if (!DAG.getTarget().Options.NoInfsFPMath ||
4911 !DAG.getTarget().Options.NoNaNsFPMath)
4914 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4916 EVT ResVT = Op.getValueType();
4917 EVT CmpVT = Op.getOperand(0).getValueType();
4918 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4919 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4922 // If the RHS of the comparison is a 0.0, we don't need to do the
4923 // subtraction at all.
4925 if (isFloatingPointZero(RHS))
4927 default: break; // SETUO etc aren't handled by fsel.
4931 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4932 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4933 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4934 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4935 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4936 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4937 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4940 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4943 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4944 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4945 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4948 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4951 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4952 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4953 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4954 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4959 default: break; // SETUO etc aren't handled by fsel.
4963 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4964 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4965 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4966 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4967 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4968 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4969 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4970 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4973 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4974 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4975 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4976 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4979 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4980 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4981 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4982 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4985 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4986 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4987 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4988 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4991 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4992 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4993 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4994 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4999 // FIXME: Split this code up when LegalizeDAGTypes lands.
5000 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5002 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5003 SDValue Src = Op.getOperand(0);
5004 if (Src.getValueType() == MVT::f32)
5005 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5008 switch (Op.getSimpleValueType().SimpleTy) {
5009 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5011 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5012 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5017 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5018 "i64 FP_TO_UINT is supported only with FPCVT");
5019 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5025 // Convert the FP value to an int value through memory.
5026 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5027 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5028 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5029 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5030 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5032 // Emit a store to the stack slot.
5035 MachineFunction &MF = DAG.getMachineFunction();
5036 MachineMemOperand *MMO =
5037 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5038 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5039 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5040 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
5043 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5044 MPI, false, false, 0);
5046 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5048 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5049 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5050 DAG.getConstant(4, FIPtr.getValueType()));
5051 MPI = MachinePointerInfo();
5054 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5055 false, false, false, 0);
5058 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5059 SelectionDAG &DAG) const {
5061 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5062 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5065 if (Op.getOperand(0).getValueType() == MVT::i1)
5066 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5067 DAG.getConstantFP(1.0, Op.getValueType()),
5068 DAG.getConstantFP(0.0, Op.getValueType()));
5070 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5071 "UINT_TO_FP is supported only with FPCVT");
5073 // If we have FCFIDS, then use it when converting to single-precision.
5074 // Otherwise, convert to double-precision and then round.
5075 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5076 (Op.getOpcode() == ISD::UINT_TO_FP ?
5077 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5078 (Op.getOpcode() == ISD::UINT_TO_FP ?
5079 PPCISD::FCFIDU : PPCISD::FCFID);
5080 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5081 MVT::f32 : MVT::f64;
5083 if (Op.getOperand(0).getValueType() == MVT::i64) {
5084 SDValue SINT = Op.getOperand(0);
5085 // When converting to single-precision, we actually need to convert
5086 // to double-precision first and then round to single-precision.
5087 // To avoid double-rounding effects during that operation, we have
5088 // to prepare the input operand. Bits that might be truncated when
5089 // converting to double-precision are replaced by a bit that won't
5090 // be lost at this stage, but is below the single-precision rounding
5093 // However, if -enable-unsafe-fp-math is in effect, accept double
5094 // rounding to avoid the extra overhead.
5095 if (Op.getValueType() == MVT::f32 &&
5096 !PPCSubTarget.hasFPCVT() &&
5097 !DAG.getTarget().Options.UnsafeFPMath) {
5099 // Twiddle input to make sure the low 11 bits are zero. (If this
5100 // is the case, we are guaranteed the value will fit into the 53 bit
5101 // mantissa of an IEEE double-precision value without rounding.)
5102 // If any of those low 11 bits were not zero originally, make sure
5103 // bit 12 (value 2048) is set instead, so that the final rounding
5104 // to single-precision gets the correct result.
5105 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5106 SINT, DAG.getConstant(2047, MVT::i64));
5107 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5108 Round, DAG.getConstant(2047, MVT::i64));
5109 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5110 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5111 Round, DAG.getConstant(-2048, MVT::i64));
5113 // However, we cannot use that value unconditionally: if the magnitude
5114 // of the input value is small, the bit-twiddling we did above might
5115 // end up visibly changing the output. Fortunately, in that case, we
5116 // don't need to twiddle bits since the original input will convert
5117 // exactly to double-precision floating-point already. Therefore,
5118 // construct a conditional to use the original value if the top 11
5119 // bits are all sign-bit copies, and use the rounded value computed
5121 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5122 SINT, DAG.getConstant(53, MVT::i32));
5123 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5124 Cond, DAG.getConstant(1, MVT::i64));
5125 Cond = DAG.getSetCC(dl, MVT::i32,
5126 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5128 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5131 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5132 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5134 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5135 FP = DAG.getNode(ISD::FP_ROUND, dl,
5136 MVT::f32, FP, DAG.getIntPtrConstant(0));
5140 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5141 "Unhandled INT_TO_FP type in custom expander!");
5142 // Since we only generate this in 64-bit mode, we can take advantage of
5143 // 64-bit registers. In particular, sign extend the input value into the
5144 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5145 // then lfd it and fcfid it.
5146 MachineFunction &MF = DAG.getMachineFunction();
5147 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5148 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5151 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5152 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5153 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5155 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5156 MachinePointerInfo::getFixedStack(FrameIdx),
5159 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5160 "Expected an i32 store");
5161 MachineMemOperand *MMO =
5162 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5163 MachineMemOperand::MOLoad, 4, 4);
5164 SDValue Ops[] = { Store, FIdx };
5165 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5166 PPCISD::LFIWZX : PPCISD::LFIWAX,
5167 dl, DAG.getVTList(MVT::f64, MVT::Other),
5168 Ops, 2, MVT::i32, MMO);
5170 assert(PPCSubTarget.isPPC64() &&
5171 "i32->FP without LFIWAX supported only on PPC64");
5173 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5174 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5176 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5179 // STD the extended value into the stack slot.
5180 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5181 MachinePointerInfo::getFixedStack(FrameIdx),
5184 // Load the value as a double.
5185 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5186 MachinePointerInfo::getFixedStack(FrameIdx),
5187 false, false, false, 0);
5190 // FCFID it and return it.
5191 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5192 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5193 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5197 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5198 SelectionDAG &DAG) const {
5201 The rounding mode is in bits 30:31 of FPSR, and has the following
5208 FLT_ROUNDS, on the other hand, expects the following:
5215 To perform the conversion, we do:
5216 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5219 MachineFunction &MF = DAG.getMachineFunction();
5220 EVT VT = Op.getValueType();
5221 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5222 SDValue MFFSreg, InFlag;
5224 // Save FP Control Word to register
5226 MVT::f64, // return register
5227 MVT::Glue // unused in this context
5229 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5231 // Save FP register to stack slot
5232 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5233 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5234 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5235 StackSlot, MachinePointerInfo(), false, false,0);
5237 // Load FP Control Word from low 32 bits of stack slot.
5238 SDValue Four = DAG.getConstant(4, PtrVT);
5239 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5240 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5241 false, false, false, 0);
5243 // Transform as necessary
5245 DAG.getNode(ISD::AND, dl, MVT::i32,
5246 CWD, DAG.getConstant(3, MVT::i32));
5248 DAG.getNode(ISD::SRL, dl, MVT::i32,
5249 DAG.getNode(ISD::AND, dl, MVT::i32,
5250 DAG.getNode(ISD::XOR, dl, MVT::i32,
5251 CWD, DAG.getConstant(3, MVT::i32)),
5252 DAG.getConstant(3, MVT::i32)),
5253 DAG.getConstant(1, MVT::i32));
5256 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5258 return DAG.getNode((VT.getSizeInBits() < 16 ?
5259 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5262 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5263 EVT VT = Op.getValueType();
5264 unsigned BitWidth = VT.getSizeInBits();
5266 assert(Op.getNumOperands() == 3 &&
5267 VT == Op.getOperand(1).getValueType() &&
5270 // Expand into a bunch of logical ops. Note that these ops
5271 // depend on the PPC behavior for oversized shift amounts.
5272 SDValue Lo = Op.getOperand(0);
5273 SDValue Hi = Op.getOperand(1);
5274 SDValue Amt = Op.getOperand(2);
5275 EVT AmtVT = Amt.getValueType();
5277 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5278 DAG.getConstant(BitWidth, AmtVT), Amt);
5279 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5280 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5281 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5282 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5283 DAG.getConstant(-BitWidth, AmtVT));
5284 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5285 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5286 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5287 SDValue OutOps[] = { OutLo, OutHi };
5288 return DAG.getMergeValues(OutOps, 2, dl);
5291 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5292 EVT VT = Op.getValueType();
5294 unsigned BitWidth = VT.getSizeInBits();
5295 assert(Op.getNumOperands() == 3 &&
5296 VT == Op.getOperand(1).getValueType() &&
5299 // Expand into a bunch of logical ops. Note that these ops
5300 // depend on the PPC behavior for oversized shift amounts.
5301 SDValue Lo = Op.getOperand(0);
5302 SDValue Hi = Op.getOperand(1);
5303 SDValue Amt = Op.getOperand(2);
5304 EVT AmtVT = Amt.getValueType();
5306 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5307 DAG.getConstant(BitWidth, AmtVT), Amt);
5308 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5309 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5310 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5311 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5312 DAG.getConstant(-BitWidth, AmtVT));
5313 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5314 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5315 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5316 SDValue OutOps[] = { OutLo, OutHi };
5317 return DAG.getMergeValues(OutOps, 2, dl);
5320 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5322 EVT VT = Op.getValueType();
5323 unsigned BitWidth = VT.getSizeInBits();
5324 assert(Op.getNumOperands() == 3 &&
5325 VT == Op.getOperand(1).getValueType() &&
5328 // Expand into a bunch of logical ops, followed by a select_cc.
5329 SDValue Lo = Op.getOperand(0);
5330 SDValue Hi = Op.getOperand(1);
5331 SDValue Amt = Op.getOperand(2);
5332 EVT AmtVT = Amt.getValueType();
5334 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5335 DAG.getConstant(BitWidth, AmtVT), Amt);
5336 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5337 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5338 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5339 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5340 DAG.getConstant(-BitWidth, AmtVT));
5341 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5342 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5343 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5344 Tmp4, Tmp6, ISD::SETLE);
5345 SDValue OutOps[] = { OutLo, OutHi };
5346 return DAG.getMergeValues(OutOps, 2, dl);
5349 //===----------------------------------------------------------------------===//
5350 // Vector related lowering.
5353 /// BuildSplatI - Build a canonical splati of Val with an element size of
5354 /// SplatSize. Cast the result to VT.
5355 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5356 SelectionDAG &DAG, SDLoc dl) {
5357 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5359 static const EVT VTys[] = { // canonical VT to use for each size.
5360 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5363 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5365 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5369 EVT CanonicalVT = VTys[SplatSize-1];
5371 // Build a canonical splat for this value.
5372 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5373 SmallVector<SDValue, 8> Ops;
5374 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5375 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5376 &Ops[0], Ops.size());
5377 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5380 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5381 /// specified intrinsic ID.
5382 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5383 SelectionDAG &DAG, SDLoc dl,
5384 EVT DestVT = MVT::Other) {
5385 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5386 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5387 DAG.getConstant(IID, MVT::i32), Op);
5390 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5391 /// specified intrinsic ID.
5392 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5393 SelectionDAG &DAG, SDLoc dl,
5394 EVT DestVT = MVT::Other) {
5395 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5396 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5397 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5400 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5401 /// specified intrinsic ID.
5402 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5403 SDValue Op2, SelectionDAG &DAG,
5404 SDLoc dl, EVT DestVT = MVT::Other) {
5405 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5406 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5407 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5411 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5412 /// amount. The result has the specified value type.
5413 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5414 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5415 // Force LHS/RHS to be the right type.
5416 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5417 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5420 for (unsigned i = 0; i != 16; ++i)
5422 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5423 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5426 // If this is a case we can't handle, return null and let the default
5427 // expansion code take care of it. If we CAN select this case, and if it
5428 // selects to a single instruction, return Op. Otherwise, if we can codegen
5429 // this case more efficiently than a constant pool load, lower it to the
5430 // sequence of ops that should be used.
5431 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5432 SelectionDAG &DAG) const {
5434 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5435 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5437 // Check if this is a splat of a constant value.
5438 APInt APSplatBits, APSplatUndef;
5439 unsigned SplatBitSize;
5441 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5442 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5445 unsigned SplatBits = APSplatBits.getZExtValue();
5446 unsigned SplatUndef = APSplatUndef.getZExtValue();
5447 unsigned SplatSize = SplatBitSize / 8;
5449 // First, handle single instruction cases.
5452 if (SplatBits == 0) {
5453 // Canonicalize all zero vectors to be v4i32.
5454 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5455 SDValue Z = DAG.getConstant(0, MVT::i32);
5456 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5457 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5462 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5463 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5465 if (SextVal >= -16 && SextVal <= 15)
5466 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5469 // Two instruction sequences.
5471 // If this value is in the range [-32,30] and is even, use:
5472 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5473 // If this value is in the range [17,31] and is odd, use:
5474 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5475 // If this value is in the range [-31,-17] and is odd, use:
5476 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5477 // Note the last two are three-instruction sequences.
5478 if (SextVal >= -32 && SextVal <= 31) {
5479 // To avoid having these optimizations undone by constant folding,
5480 // we convert to a pseudo that will be expanded later into one of
5482 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5483 EVT VT = Op.getValueType();
5484 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5485 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5486 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5489 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5490 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5492 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5493 // Make -1 and vspltisw -1:
5494 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5496 // Make the VSLW intrinsic, computing 0x8000_0000.
5497 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5500 // xor by OnesV to invert it.
5501 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5502 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5505 // Check to see if this is a wide variety of vsplti*, binop self cases.
5506 static const signed char SplatCsts[] = {
5507 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5508 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5511 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5512 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5513 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5514 int i = SplatCsts[idx];
5516 // Figure out what shift amount will be used by altivec if shifted by i in
5518 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5520 // vsplti + shl self.
5521 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5522 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5523 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5524 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5525 Intrinsic::ppc_altivec_vslw
5527 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5528 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5531 // vsplti + srl self.
5532 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5533 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5534 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5535 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5536 Intrinsic::ppc_altivec_vsrw
5538 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5539 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5542 // vsplti + sra self.
5543 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5544 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5545 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5546 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5547 Intrinsic::ppc_altivec_vsraw
5549 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5550 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5553 // vsplti + rol self.
5554 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5555 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5556 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5557 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5558 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5559 Intrinsic::ppc_altivec_vrlw
5561 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5562 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5565 // t = vsplti c, result = vsldoi t, t, 1
5566 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5567 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5568 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5570 // t = vsplti c, result = vsldoi t, t, 2
5571 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5572 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5573 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5575 // t = vsplti c, result = vsldoi t, t, 3
5576 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5577 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5578 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5585 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5586 /// the specified operations to build the shuffle.
5587 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5588 SDValue RHS, SelectionDAG &DAG,
5590 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5591 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5592 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5595 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5607 if (OpNum == OP_COPY) {
5608 if (LHSID == (1*9+2)*9+3) return LHS;
5609 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5613 SDValue OpLHS, OpRHS;
5614 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5615 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5619 default: llvm_unreachable("Unknown i32 permute!");
5621 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5622 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5623 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5624 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5627 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5628 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5629 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5630 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5633 for (unsigned i = 0; i != 16; ++i)
5634 ShufIdxs[i] = (i&3)+0;
5637 for (unsigned i = 0; i != 16; ++i)
5638 ShufIdxs[i] = (i&3)+4;
5641 for (unsigned i = 0; i != 16; ++i)
5642 ShufIdxs[i] = (i&3)+8;
5645 for (unsigned i = 0; i != 16; ++i)
5646 ShufIdxs[i] = (i&3)+12;
5649 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5651 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5653 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5655 EVT VT = OpLHS.getValueType();
5656 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5657 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5658 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5659 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5662 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5663 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5664 /// return the code it can be lowered into. Worst case, it can always be
5665 /// lowered into a vperm.
5666 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5667 SelectionDAG &DAG) const {
5669 SDValue V1 = Op.getOperand(0);
5670 SDValue V2 = Op.getOperand(1);
5671 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5672 EVT VT = Op.getValueType();
5674 // Cases that are handled by instructions that take permute immediates
5675 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5676 // selected by the instruction selector.
5677 if (V2.getOpcode() == ISD::UNDEF) {
5678 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5679 PPC::isSplatShuffleMask(SVOp, 2) ||
5680 PPC::isSplatShuffleMask(SVOp, 4) ||
5681 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5682 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5683 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5684 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5685 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5686 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5687 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5688 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5689 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5694 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5695 // and produce a fixed permutation. If any of these match, do not lower to
5697 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5698 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5699 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5700 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5701 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5702 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5703 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5704 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5705 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5708 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5709 // perfect shuffle table to emit an optimal matching sequence.
5710 ArrayRef<int> PermMask = SVOp->getMask();
5712 unsigned PFIndexes[4];
5713 bool isFourElementShuffle = true;
5714 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5715 unsigned EltNo = 8; // Start out undef.
5716 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5717 if (PermMask[i*4+j] < 0)
5718 continue; // Undef, ignore it.
5720 unsigned ByteSource = PermMask[i*4+j];
5721 if ((ByteSource & 3) != j) {
5722 isFourElementShuffle = false;
5727 EltNo = ByteSource/4;
5728 } else if (EltNo != ByteSource/4) {
5729 isFourElementShuffle = false;
5733 PFIndexes[i] = EltNo;
5736 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5737 // perfect shuffle vector to determine if it is cost effective to do this as
5738 // discrete instructions, or whether we should use a vperm.
5739 if (isFourElementShuffle) {
5740 // Compute the index in the perfect shuffle table.
5741 unsigned PFTableIndex =
5742 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5744 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5745 unsigned Cost = (PFEntry >> 30);
5747 // Determining when to avoid vperm is tricky. Many things affect the cost
5748 // of vperm, particularly how many times the perm mask needs to be computed.
5749 // For example, if the perm mask can be hoisted out of a loop or is already
5750 // used (perhaps because there are multiple permutes with the same shuffle
5751 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5752 // the loop requires an extra register.
5754 // As a compromise, we only emit discrete instructions if the shuffle can be
5755 // generated in 3 or fewer operations. When we have loop information
5756 // available, if this block is within a loop, we should avoid using vperm
5757 // for 3-operation perms and use a constant pool load instead.
5759 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5762 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5763 // vector that will get spilled to the constant pool.
5764 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5766 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5767 // that it is in input element units, not in bytes. Convert now.
5768 EVT EltVT = V1.getValueType().getVectorElementType();
5769 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5771 SmallVector<SDValue, 16> ResultMask;
5772 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5773 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5775 for (unsigned j = 0; j != BytesPerElement; ++j)
5776 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5780 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5781 &ResultMask[0], ResultMask.size());
5782 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5785 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5786 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5787 /// information about the intrinsic.
5788 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5790 unsigned IntrinsicID =
5791 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5794 switch (IntrinsicID) {
5795 default: return false;
5796 // Comparison predicates.
5797 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5798 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5799 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5800 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5801 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5802 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5803 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5804 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5805 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5806 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5807 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5808 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5809 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5811 // Normal Comparisons.
5812 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5813 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5814 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5815 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5816 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5817 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5818 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5819 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5820 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5821 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5822 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5823 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5824 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5829 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5830 /// lower, do it, otherwise return null.
5831 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5832 SelectionDAG &DAG) const {
5833 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5834 // opcode number of the comparison.
5838 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5839 return SDValue(); // Don't custom lower most intrinsics.
5841 // If this is a non-dot comparison, make the VCMP node and we are done.
5843 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5844 Op.getOperand(1), Op.getOperand(2),
5845 DAG.getConstant(CompareOpc, MVT::i32));
5846 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5849 // Create the PPCISD altivec 'dot' comparison node.
5851 Op.getOperand(2), // LHS
5852 Op.getOperand(3), // RHS
5853 DAG.getConstant(CompareOpc, MVT::i32)
5855 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5856 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5858 // Now that we have the comparison, emit a copy from the CR to a GPR.
5859 // This is flagged to the above dot comparison.
5860 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5861 DAG.getRegister(PPC::CR6, MVT::i32),
5862 CompNode.getValue(1));
5864 // Unpack the result based on how the target uses it.
5865 unsigned BitNo; // Bit # of CR6.
5866 bool InvertBit; // Invert result?
5867 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5868 default: // Can't happen, don't crash on invalid number though.
5869 case 0: // Return the value of the EQ bit of CR6.
5870 BitNo = 0; InvertBit = false;
5872 case 1: // Return the inverted value of the EQ bit of CR6.
5873 BitNo = 0; InvertBit = true;
5875 case 2: // Return the value of the LT bit of CR6.
5876 BitNo = 2; InvertBit = false;
5878 case 3: // Return the inverted value of the LT bit of CR6.
5879 BitNo = 2; InvertBit = true;
5883 // Shift the bit into the low position.
5884 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5885 DAG.getConstant(8-(3-BitNo), MVT::i32));
5887 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5888 DAG.getConstant(1, MVT::i32));
5890 // If we are supposed to, toggle the bit.
5892 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5893 DAG.getConstant(1, MVT::i32));
5897 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5898 SelectionDAG &DAG) const {
5900 // Create a stack slot that is 16-byte aligned.
5901 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5902 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5903 EVT PtrVT = getPointerTy();
5904 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5906 // Store the input value into Value#0 of the stack slot.
5907 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5908 Op.getOperand(0), FIdx, MachinePointerInfo(),
5911 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5912 false, false, false, 0);
5915 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5917 if (Op.getValueType() == MVT::v4i32) {
5918 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5920 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5921 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5923 SDValue RHSSwap = // = vrlw RHS, 16
5924 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5926 // Shrinkify inputs to v8i16.
5927 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5928 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5929 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5931 // Low parts multiplied together, generating 32-bit results (we ignore the
5933 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5934 LHS, RHS, DAG, dl, MVT::v4i32);
5936 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5937 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5938 // Shift the high parts up 16 bits.
5939 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5941 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5942 } else if (Op.getValueType() == MVT::v8i16) {
5943 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5945 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5947 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5948 LHS, RHS, Zero, DAG, dl);
5949 } else if (Op.getValueType() == MVT::v16i8) {
5950 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5952 // Multiply the even 8-bit parts, producing 16-bit sums.
5953 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5954 LHS, RHS, DAG, dl, MVT::v8i16);
5955 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5957 // Multiply the odd 8-bit parts, producing 16-bit sums.
5958 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5959 LHS, RHS, DAG, dl, MVT::v8i16);
5960 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5962 // Merge the results together.
5964 for (unsigned i = 0; i != 8; ++i) {
5966 Ops[i*2+1] = 2*i+1+16;
5968 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5970 llvm_unreachable("Unknown mul to lower!");
5974 /// LowerOperation - Provide custom lowering hooks for some operations.
5976 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5977 switch (Op.getOpcode()) {
5978 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5979 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5980 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5981 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5982 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5983 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5984 case ISD::SETCC: return LowerSETCC(Op, DAG);
5985 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5986 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5988 return LowerVASTART(Op, DAG, PPCSubTarget);
5991 return LowerVAARG(Op, DAG, PPCSubTarget);
5994 return LowerVACOPY(Op, DAG, PPCSubTarget);
5996 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5997 case ISD::DYNAMIC_STACKALLOC:
5998 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6000 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6001 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6003 case ISD::LOAD: return LowerLOAD(Op, DAG);
6004 case ISD::STORE: return LowerSTORE(Op, DAG);
6005 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6006 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6007 case ISD::FP_TO_UINT:
6008 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6010 case ISD::UINT_TO_FP:
6011 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6012 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6014 // Lower 64-bit shifts.
6015 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6016 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6017 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6019 // Vector-related lowering.
6020 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6021 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6022 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6023 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6024 case ISD::MUL: return LowerMUL(Op, DAG);
6026 // For counter-based loop handling.
6027 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6029 // Frame & Return address.
6030 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6031 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6035 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6036 SmallVectorImpl<SDValue>&Results,
6037 SelectionDAG &DAG) const {
6038 const TargetMachine &TM = getTargetMachine();
6040 switch (N->getOpcode()) {
6042 llvm_unreachable("Do not know how to custom type legalize this operation!");
6043 case ISD::INTRINSIC_W_CHAIN: {
6044 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6045 Intrinsic::ppc_is_decremented_ctr_nonzero)
6048 assert(N->getValueType(0) == MVT::i1 &&
6049 "Unexpected result type for CTR decrement intrinsic");
6050 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6051 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6052 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6055 Results.push_back(NewInt);
6056 Results.push_back(NewInt.getValue(1));
6060 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6061 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6064 EVT VT = N->getValueType(0);
6066 if (VT == MVT::i64) {
6067 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6069 Results.push_back(NewNode);
6070 Results.push_back(NewNode.getValue(1));
6074 case ISD::FP_ROUND_INREG: {
6075 assert(N->getValueType(0) == MVT::ppcf128);
6076 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6077 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6078 MVT::f64, N->getOperand(0),
6079 DAG.getIntPtrConstant(0));
6080 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6081 MVT::f64, N->getOperand(0),
6082 DAG.getIntPtrConstant(1));
6084 // Add the two halves of the long double in round-to-zero mode.
6085 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6087 // We know the low half is about to be thrown away, so just use something
6089 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6093 case ISD::FP_TO_SINT:
6094 // LowerFP_TO_INT() can only handle f32 and f64.
6095 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6097 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6103 //===----------------------------------------------------------------------===//
6104 // Other Lowering Code
6105 //===----------------------------------------------------------------------===//
6108 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6109 bool is64bit, unsigned BinOpcode) const {
6110 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6111 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6113 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6114 MachineFunction *F = BB->getParent();
6115 MachineFunction::iterator It = BB;
6118 unsigned dest = MI->getOperand(0).getReg();
6119 unsigned ptrA = MI->getOperand(1).getReg();
6120 unsigned ptrB = MI->getOperand(2).getReg();
6121 unsigned incr = MI->getOperand(3).getReg();
6122 DebugLoc dl = MI->getDebugLoc();
6124 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6125 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6126 F->insert(It, loopMBB);
6127 F->insert(It, exitMBB);
6128 exitMBB->splice(exitMBB->begin(), BB,
6129 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6130 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6132 MachineRegisterInfo &RegInfo = F->getRegInfo();
6133 unsigned TmpReg = (!BinOpcode) ? incr :
6134 RegInfo.createVirtualRegister(
6135 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6136 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6140 // fallthrough --> loopMBB
6141 BB->addSuccessor(loopMBB);
6144 // l[wd]arx dest, ptr
6145 // add r0, dest, incr
6146 // st[wd]cx. r0, ptr
6148 // fallthrough --> exitMBB
6150 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6151 .addReg(ptrA).addReg(ptrB);
6153 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6154 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6155 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6156 BuildMI(BB, dl, TII->get(PPC::BCC))
6157 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6158 BB->addSuccessor(loopMBB);
6159 BB->addSuccessor(exitMBB);
6168 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6169 MachineBasicBlock *BB,
6170 bool is8bit, // operation
6171 unsigned BinOpcode) const {
6172 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6173 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6174 // In 64 bit mode we have to use 64 bits for addresses, even though the
6175 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6176 // registers without caring whether they're 32 or 64, but here we're
6177 // doing actual arithmetic on the addresses.
6178 bool is64bit = PPCSubTarget.isPPC64();
6179 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6181 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6182 MachineFunction *F = BB->getParent();
6183 MachineFunction::iterator It = BB;
6186 unsigned dest = MI->getOperand(0).getReg();
6187 unsigned ptrA = MI->getOperand(1).getReg();
6188 unsigned ptrB = MI->getOperand(2).getReg();
6189 unsigned incr = MI->getOperand(3).getReg();
6190 DebugLoc dl = MI->getDebugLoc();
6192 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6193 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6194 F->insert(It, loopMBB);
6195 F->insert(It, exitMBB);
6196 exitMBB->splice(exitMBB->begin(), BB,
6197 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6198 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6200 MachineRegisterInfo &RegInfo = F->getRegInfo();
6201 const TargetRegisterClass *RC =
6202 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6203 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6204 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6205 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6206 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6207 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6208 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6209 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6210 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6211 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6212 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6213 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6214 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6216 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6220 // fallthrough --> loopMBB
6221 BB->addSuccessor(loopMBB);
6223 // The 4-byte load must be aligned, while a char or short may be
6224 // anywhere in the word. Hence all this nasty bookkeeping code.
6225 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6226 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6227 // xori shift, shift1, 24 [16]
6228 // rlwinm ptr, ptr1, 0, 0, 29
6229 // slw incr2, incr, shift
6230 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6231 // slw mask, mask2, shift
6233 // lwarx tmpDest, ptr
6234 // add tmp, tmpDest, incr2
6235 // andc tmp2, tmpDest, mask
6236 // and tmp3, tmp, mask
6237 // or tmp4, tmp3, tmp2
6240 // fallthrough --> exitMBB
6241 // srw dest, tmpDest, shift
6242 if (ptrA != ZeroReg) {
6243 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6244 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6245 .addReg(ptrA).addReg(ptrB);
6249 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6250 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6251 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6252 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6254 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6255 .addReg(Ptr1Reg).addImm(0).addImm(61);
6257 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6258 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6259 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6260 .addReg(incr).addReg(ShiftReg);
6262 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6264 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6265 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6267 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6268 .addReg(Mask2Reg).addReg(ShiftReg);
6271 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6272 .addReg(ZeroReg).addReg(PtrReg);
6274 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6275 .addReg(Incr2Reg).addReg(TmpDestReg);
6276 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6277 .addReg(TmpDestReg).addReg(MaskReg);
6278 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6279 .addReg(TmpReg).addReg(MaskReg);
6280 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6281 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6282 BuildMI(BB, dl, TII->get(PPC::STWCX))
6283 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6284 BuildMI(BB, dl, TII->get(PPC::BCC))
6285 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6286 BB->addSuccessor(loopMBB);
6287 BB->addSuccessor(exitMBB);
6292 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6297 llvm::MachineBasicBlock*
6298 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6299 MachineBasicBlock *MBB) const {
6300 DebugLoc DL = MI->getDebugLoc();
6301 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6303 MachineFunction *MF = MBB->getParent();
6304 MachineRegisterInfo &MRI = MF->getRegInfo();
6306 const BasicBlock *BB = MBB->getBasicBlock();
6307 MachineFunction::iterator I = MBB;
6311 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6312 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6314 unsigned DstReg = MI->getOperand(0).getReg();
6315 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6316 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6317 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6318 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6320 MVT PVT = getPointerTy();
6321 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6322 "Invalid Pointer Size!");
6323 // For v = setjmp(buf), we generate
6326 // SjLjSetup mainMBB
6332 // buf[LabelOffset] = LR
6336 // v = phi(main, restore)
6339 MachineBasicBlock *thisMBB = MBB;
6340 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6341 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6342 MF->insert(I, mainMBB);
6343 MF->insert(I, sinkMBB);
6345 MachineInstrBuilder MIB;
6347 // Transfer the remainder of BB and its successor edges to sinkMBB.
6348 sinkMBB->splice(sinkMBB->begin(), MBB,
6349 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6350 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6352 // Note that the structure of the jmp_buf used here is not compatible
6353 // with that used by libc, and is not designed to be. Specifically, it
6354 // stores only those 'reserved' registers that LLVM does not otherwise
6355 // understand how to spill. Also, by convention, by the time this
6356 // intrinsic is called, Clang has already stored the frame address in the
6357 // first slot of the buffer and stack address in the third. Following the
6358 // X86 target code, we'll store the jump address in the second slot. We also
6359 // need to save the TOC pointer (R2) to handle jumps between shared
6360 // libraries, and that will be stored in the fourth slot. The thread
6361 // identifier (R13) is not affected.
6364 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6365 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6366 const int64_t BPOffset = 4 * PVT.getStoreSize();
6368 // Prepare IP either in reg.
6369 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6370 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6371 unsigned BufReg = MI->getOperand(1).getReg();
6373 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6374 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6378 MIB.setMemRefs(MMOBegin, MMOEnd);
6381 // Naked functions never have a base pointer, and so we use r1. For all
6382 // other functions, this decision must be delayed until during PEI.
6384 if (MF->getFunction()->getAttributes().hasAttribute(
6385 AttributeSet::FunctionIndex, Attribute::Naked))
6386 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6388 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6390 MIB = BuildMI(*thisMBB, MI, DL,
6391 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6395 MIB.setMemRefs(MMOBegin, MMOEnd);
6398 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6399 const PPCRegisterInfo *TRI =
6400 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6401 MIB.addRegMask(TRI->getNoPreservedMask());
6403 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6405 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6407 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6409 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6410 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6414 MIB = BuildMI(mainMBB, DL,
6415 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6418 if (PPCSubTarget.isPPC64()) {
6419 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6421 .addImm(LabelOffset)
6424 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6426 .addImm(LabelOffset)
6430 MIB.setMemRefs(MMOBegin, MMOEnd);
6432 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6433 mainMBB->addSuccessor(sinkMBB);
6436 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6437 TII->get(PPC::PHI), DstReg)
6438 .addReg(mainDstReg).addMBB(mainMBB)
6439 .addReg(restoreDstReg).addMBB(thisMBB);
6441 MI->eraseFromParent();
6446 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6447 MachineBasicBlock *MBB) const {
6448 DebugLoc DL = MI->getDebugLoc();
6449 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6451 MachineFunction *MF = MBB->getParent();
6452 MachineRegisterInfo &MRI = MF->getRegInfo();
6455 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6456 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6458 MVT PVT = getPointerTy();
6459 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6460 "Invalid Pointer Size!");
6462 const TargetRegisterClass *RC =
6463 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6464 unsigned Tmp = MRI.createVirtualRegister(RC);
6465 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6466 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6467 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6468 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6470 MachineInstrBuilder MIB;
6472 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6473 const int64_t SPOffset = 2 * PVT.getStoreSize();
6474 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6475 const int64_t BPOffset = 4 * PVT.getStoreSize();
6477 unsigned BufReg = MI->getOperand(0).getReg();
6479 // Reload FP (the jumped-to function may not have had a
6480 // frame pointer, and if so, then its r31 will be restored
6482 if (PVT == MVT::i64) {
6483 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6487 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6491 MIB.setMemRefs(MMOBegin, MMOEnd);
6494 if (PVT == MVT::i64) {
6495 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6496 .addImm(LabelOffset)
6499 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6500 .addImm(LabelOffset)
6503 MIB.setMemRefs(MMOBegin, MMOEnd);
6506 if (PVT == MVT::i64) {
6507 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6511 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6515 MIB.setMemRefs(MMOBegin, MMOEnd);
6518 if (PVT == MVT::i64) {
6519 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6523 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6527 MIB.setMemRefs(MMOBegin, MMOEnd);
6530 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6531 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6535 MIB.setMemRefs(MMOBegin, MMOEnd);
6539 BuildMI(*MBB, MI, DL,
6540 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6541 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6543 MI->eraseFromParent();
6548 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6549 MachineBasicBlock *BB) const {
6550 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6551 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6552 return emitEHSjLjSetJmp(MI, BB);
6553 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6554 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6555 return emitEHSjLjLongJmp(MI, BB);
6558 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6560 // To "insert" these instructions we actually have to insert their
6561 // control-flow patterns.
6562 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6563 MachineFunction::iterator It = BB;
6566 MachineFunction *F = BB->getParent();
6568 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6569 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6570 MI->getOpcode() == PPC::SELECT_I4 ||
6571 MI->getOpcode() == PPC::SELECT_I8)) {
6572 SmallVector<MachineOperand, 2> Cond;
6573 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6574 MI->getOpcode() == PPC::SELECT_CC_I8)
6575 Cond.push_back(MI->getOperand(4));
6577 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6578 Cond.push_back(MI->getOperand(1));
6580 DebugLoc dl = MI->getDebugLoc();
6581 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6582 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6583 Cond, MI->getOperand(2).getReg(),
6584 MI->getOperand(3).getReg());
6585 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6586 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6587 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6588 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6589 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6590 MI->getOpcode() == PPC::SELECT_I4 ||
6591 MI->getOpcode() == PPC::SELECT_I8 ||
6592 MI->getOpcode() == PPC::SELECT_F4 ||
6593 MI->getOpcode() == PPC::SELECT_F8 ||
6594 MI->getOpcode() == PPC::SELECT_VRRC) {
6595 // The incoming instruction knows the destination vreg to set, the
6596 // condition code register to branch on, the true/false values to
6597 // select between, and a branch opcode to use.
6602 // cmpTY ccX, r1, r2
6604 // fallthrough --> copy0MBB
6605 MachineBasicBlock *thisMBB = BB;
6606 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6607 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6608 DebugLoc dl = MI->getDebugLoc();
6609 F->insert(It, copy0MBB);
6610 F->insert(It, sinkMBB);
6612 // Transfer the remainder of BB and its successor edges to sinkMBB.
6613 sinkMBB->splice(sinkMBB->begin(), BB,
6614 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6615 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6617 // Next, add the true and fallthrough blocks as its successors.
6618 BB->addSuccessor(copy0MBB);
6619 BB->addSuccessor(sinkMBB);
6621 if (MI->getOpcode() == PPC::SELECT_I4 ||
6622 MI->getOpcode() == PPC::SELECT_I8 ||
6623 MI->getOpcode() == PPC::SELECT_F4 ||
6624 MI->getOpcode() == PPC::SELECT_F8 ||
6625 MI->getOpcode() == PPC::SELECT_VRRC) {
6626 BuildMI(BB, dl, TII->get(PPC::BC))
6627 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6629 unsigned SelectPred = MI->getOperand(4).getImm();
6630 BuildMI(BB, dl, TII->get(PPC::BCC))
6631 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6635 // %FalseValue = ...
6636 // # fallthrough to sinkMBB
6639 // Update machine-CFG edges
6640 BB->addSuccessor(sinkMBB);
6643 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6646 BuildMI(*BB, BB->begin(), dl,
6647 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6648 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6649 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6651 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6652 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6653 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6654 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6655 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6656 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6657 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6658 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6660 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6661 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6662 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6663 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6664 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6665 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6666 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6667 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6669 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6670 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6671 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6672 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6673 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6674 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6675 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6676 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6678 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6679 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6680 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6681 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6682 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6683 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6684 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6685 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6687 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6688 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6689 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6690 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6691 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6692 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6693 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6694 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6696 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6697 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6698 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6699 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6700 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6701 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6702 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6703 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6705 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6706 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6707 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6708 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6709 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6710 BB = EmitAtomicBinary(MI, BB, false, 0);
6711 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6712 BB = EmitAtomicBinary(MI, BB, true, 0);
6714 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6715 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6716 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6718 unsigned dest = MI->getOperand(0).getReg();
6719 unsigned ptrA = MI->getOperand(1).getReg();
6720 unsigned ptrB = MI->getOperand(2).getReg();
6721 unsigned oldval = MI->getOperand(3).getReg();
6722 unsigned newval = MI->getOperand(4).getReg();
6723 DebugLoc dl = MI->getDebugLoc();
6725 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6726 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6727 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6728 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6729 F->insert(It, loop1MBB);
6730 F->insert(It, loop2MBB);
6731 F->insert(It, midMBB);
6732 F->insert(It, exitMBB);
6733 exitMBB->splice(exitMBB->begin(), BB,
6734 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6735 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6739 // fallthrough --> loopMBB
6740 BB->addSuccessor(loop1MBB);
6743 // l[wd]arx dest, ptr
6744 // cmp[wd] dest, oldval
6747 // st[wd]cx. newval, ptr
6751 // st[wd]cx. dest, ptr
6754 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6755 .addReg(ptrA).addReg(ptrB);
6756 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6757 .addReg(oldval).addReg(dest);
6758 BuildMI(BB, dl, TII->get(PPC::BCC))
6759 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6760 BB->addSuccessor(loop2MBB);
6761 BB->addSuccessor(midMBB);
6764 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6765 .addReg(newval).addReg(ptrA).addReg(ptrB);
6766 BuildMI(BB, dl, TII->get(PPC::BCC))
6767 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6768 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6769 BB->addSuccessor(loop1MBB);
6770 BB->addSuccessor(exitMBB);
6773 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6774 .addReg(dest).addReg(ptrA).addReg(ptrB);
6775 BB->addSuccessor(exitMBB);
6780 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6781 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6782 // We must use 64-bit registers for addresses when targeting 64-bit,
6783 // since we're actually doing arithmetic on them. Other registers
6785 bool is64bit = PPCSubTarget.isPPC64();
6786 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6788 unsigned dest = MI->getOperand(0).getReg();
6789 unsigned ptrA = MI->getOperand(1).getReg();
6790 unsigned ptrB = MI->getOperand(2).getReg();
6791 unsigned oldval = MI->getOperand(3).getReg();
6792 unsigned newval = MI->getOperand(4).getReg();
6793 DebugLoc dl = MI->getDebugLoc();
6795 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6796 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6797 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6798 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6799 F->insert(It, loop1MBB);
6800 F->insert(It, loop2MBB);
6801 F->insert(It, midMBB);
6802 F->insert(It, exitMBB);
6803 exitMBB->splice(exitMBB->begin(), BB,
6804 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6805 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6807 MachineRegisterInfo &RegInfo = F->getRegInfo();
6808 const TargetRegisterClass *RC =
6809 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6810 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6811 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6812 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6813 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6814 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6815 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6816 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6817 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6818 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6819 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6820 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6821 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6822 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6823 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6825 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6826 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6829 // fallthrough --> loopMBB
6830 BB->addSuccessor(loop1MBB);
6832 // The 4-byte load must be aligned, while a char or short may be
6833 // anywhere in the word. Hence all this nasty bookkeeping code.
6834 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6835 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6836 // xori shift, shift1, 24 [16]
6837 // rlwinm ptr, ptr1, 0, 0, 29
6838 // slw newval2, newval, shift
6839 // slw oldval2, oldval,shift
6840 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6841 // slw mask, mask2, shift
6842 // and newval3, newval2, mask
6843 // and oldval3, oldval2, mask
6845 // lwarx tmpDest, ptr
6846 // and tmp, tmpDest, mask
6847 // cmpw tmp, oldval3
6850 // andc tmp2, tmpDest, mask
6851 // or tmp4, tmp2, newval3
6856 // stwcx. tmpDest, ptr
6858 // srw dest, tmpDest, shift
6859 if (ptrA != ZeroReg) {
6860 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6861 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6862 .addReg(ptrA).addReg(ptrB);
6866 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6867 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6868 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6869 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6871 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6872 .addReg(Ptr1Reg).addImm(0).addImm(61);
6874 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6875 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6876 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6877 .addReg(newval).addReg(ShiftReg);
6878 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6879 .addReg(oldval).addReg(ShiftReg);
6881 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6883 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6884 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6885 .addReg(Mask3Reg).addImm(65535);
6887 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6888 .addReg(Mask2Reg).addReg(ShiftReg);
6889 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6890 .addReg(NewVal2Reg).addReg(MaskReg);
6891 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6892 .addReg(OldVal2Reg).addReg(MaskReg);
6895 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6896 .addReg(ZeroReg).addReg(PtrReg);
6897 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6898 .addReg(TmpDestReg).addReg(MaskReg);
6899 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6900 .addReg(TmpReg).addReg(OldVal3Reg);
6901 BuildMI(BB, dl, TII->get(PPC::BCC))
6902 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6903 BB->addSuccessor(loop2MBB);
6904 BB->addSuccessor(midMBB);
6907 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6908 .addReg(TmpDestReg).addReg(MaskReg);
6909 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6910 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6911 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6912 .addReg(ZeroReg).addReg(PtrReg);
6913 BuildMI(BB, dl, TII->get(PPC::BCC))
6914 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6915 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6916 BB->addSuccessor(loop1MBB);
6917 BB->addSuccessor(exitMBB);
6920 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6921 .addReg(ZeroReg).addReg(PtrReg);
6922 BB->addSuccessor(exitMBB);
6927 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6929 } else if (MI->getOpcode() == PPC::FADDrtz) {
6930 // This pseudo performs an FADD with rounding mode temporarily forced
6931 // to round-to-zero. We emit this via custom inserter since the FPSCR
6932 // is not modeled at the SelectionDAG level.
6933 unsigned Dest = MI->getOperand(0).getReg();
6934 unsigned Src1 = MI->getOperand(1).getReg();
6935 unsigned Src2 = MI->getOperand(2).getReg();
6936 DebugLoc dl = MI->getDebugLoc();
6938 MachineRegisterInfo &RegInfo = F->getRegInfo();
6939 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6941 // Save FPSCR value.
6942 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6944 // Set rounding mode to round-to-zero.
6945 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6946 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6948 // Perform addition.
6949 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6951 // Restore FPSCR value.
6952 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6953 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6954 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6955 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6956 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6957 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6958 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6959 PPC::ANDIo8 : PPC::ANDIo;
6960 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6961 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6963 MachineRegisterInfo &RegInfo = F->getRegInfo();
6964 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6965 &PPC::GPRCRegClass :
6966 &PPC::G8RCRegClass);
6968 DebugLoc dl = MI->getDebugLoc();
6969 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6970 .addReg(MI->getOperand(1).getReg()).addImm(1);
6971 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6972 MI->getOperand(0).getReg())
6973 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6975 llvm_unreachable("Unexpected instr type to insert");
6978 MI->eraseFromParent(); // The pseudo instruction is gone now.
6982 //===----------------------------------------------------------------------===//
6983 // Target Optimization Hooks
6984 //===----------------------------------------------------------------------===//
6986 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6987 DAGCombinerInfo &DCI) const {
6988 if (DCI.isAfterLegalizeVectorOps())
6991 EVT VT = Op.getValueType();
6993 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6994 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6995 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
6996 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
6998 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6999 // For the reciprocal, we need to find the zero of the function:
7000 // F(X) = A X - 1 [which has a zero at X = 1/A]
7002 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7003 // does not require additional intermediate precision]
7005 // Convergence is quadratic, so we essentially double the number of digits
7006 // correct after every iteration. The minimum architected relative
7007 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7008 // 23 digits and double has 52 digits.
7009 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7010 if (VT.getScalarType() == MVT::f64)
7013 SelectionDAG &DAG = DCI.DAG;
7017 DAG.getConstantFP(1.0, VT.getScalarType());
7018 if (VT.isVector()) {
7019 assert(VT.getVectorNumElements() == 4 &&
7020 "Unknown vector type");
7021 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7022 FPOne, FPOne, FPOne, FPOne);
7025 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7026 DCI.AddToWorklist(Est.getNode());
7028 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7029 for (int i = 0; i < Iterations; ++i) {
7030 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7031 DCI.AddToWorklist(NewEst.getNode());
7033 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7034 DCI.AddToWorklist(NewEst.getNode());
7036 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7037 DCI.AddToWorklist(NewEst.getNode());
7039 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7040 DCI.AddToWorklist(Est.getNode());
7049 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7050 DAGCombinerInfo &DCI) const {
7051 if (DCI.isAfterLegalizeVectorOps())
7054 EVT VT = Op.getValueType();
7056 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7057 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7058 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7059 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7061 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7062 // For the reciprocal sqrt, we need to find the zero of the function:
7063 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7065 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7066 // As a result, we precompute A/2 prior to the iteration loop.
7068 // Convergence is quadratic, so we essentially double the number of digits
7069 // correct after every iteration. The minimum architected relative
7070 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7071 // 23 digits and double has 52 digits.
7072 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7073 if (VT.getScalarType() == MVT::f64)
7076 SelectionDAG &DAG = DCI.DAG;
7079 SDValue FPThreeHalves =
7080 DAG.getConstantFP(1.5, VT.getScalarType());
7081 if (VT.isVector()) {
7082 assert(VT.getVectorNumElements() == 4 &&
7083 "Unknown vector type");
7084 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7085 FPThreeHalves, FPThreeHalves,
7086 FPThreeHalves, FPThreeHalves);
7089 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7090 DCI.AddToWorklist(Est.getNode());
7092 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7093 // this entire sequence requires only one FP constant.
7094 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7095 DCI.AddToWorklist(HalfArg.getNode());
7097 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7098 DCI.AddToWorklist(HalfArg.getNode());
7100 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7101 for (int i = 0; i < Iterations; ++i) {
7102 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7103 DCI.AddToWorklist(NewEst.getNode());
7105 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7106 DCI.AddToWorklist(NewEst.getNode());
7108 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7109 DCI.AddToWorklist(NewEst.getNode());
7111 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7112 DCI.AddToWorklist(Est.getNode());
7121 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7122 // not enforce equality of the chain operands.
7123 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7124 unsigned Bytes, int Dist,
7125 SelectionDAG &DAG) {
7126 EVT VT = LS->getMemoryVT();
7127 if (VT.getSizeInBits() / 8 != Bytes)
7130 SDValue Loc = LS->getBasePtr();
7131 SDValue BaseLoc = Base->getBasePtr();
7132 if (Loc.getOpcode() == ISD::FrameIndex) {
7133 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7135 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7136 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7137 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7138 int FS = MFI->getObjectSize(FI);
7139 int BFS = MFI->getObjectSize(BFI);
7140 if (FS != BFS || FS != (int)Bytes) return false;
7141 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7145 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7146 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7150 const GlobalValue *GV1 = NULL;
7151 const GlobalValue *GV2 = NULL;
7152 int64_t Offset1 = 0;
7153 int64_t Offset2 = 0;
7154 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7155 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7156 if (isGA1 && isGA2 && GV1 == GV2)
7157 return Offset1 == (Offset2 + Dist*Bytes);
7161 // Return true is there is a nearyby consecutive load to the one provided
7162 // (regardless of alignment). We search up and down the chain, looking though
7163 // token factors and other loads (but nothing else). As a result, a true
7164 // results indicates that it is safe to create a new consecutive load adjacent
7165 // to the load provided.
7166 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7167 SDValue Chain = LD->getChain();
7168 EVT VT = LD->getMemoryVT();
7170 SmallSet<SDNode *, 16> LoadRoots;
7171 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7172 SmallSet<SDNode *, 16> Visited;
7174 // First, search up the chain, branching to follow all token-factor operands.
7175 // If we find a consecutive load, then we're done, otherwise, record all
7176 // nodes just above the top-level loads and token factors.
7177 while (!Queue.empty()) {
7178 SDNode *ChainNext = Queue.pop_back_val();
7179 if (!Visited.insert(ChainNext))
7182 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7183 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7186 if (!Visited.count(ChainLD->getChain().getNode()))
7187 Queue.push_back(ChainLD->getChain().getNode());
7188 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7189 for (SDNode::op_iterator O = ChainNext->op_begin(),
7190 OE = ChainNext->op_end(); O != OE; ++O)
7191 if (!Visited.count(O->getNode()))
7192 Queue.push_back(O->getNode());
7194 LoadRoots.insert(ChainNext);
7197 // Second, search down the chain, starting from the top-level nodes recorded
7198 // in the first phase. These top-level nodes are the nodes just above all
7199 // loads and token factors. Starting with their uses, recursively look though
7200 // all loads (just the chain uses) and token factors to find a consecutive
7205 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7206 IE = LoadRoots.end(); I != IE; ++I) {
7207 Queue.push_back(*I);
7209 while (!Queue.empty()) {
7210 SDNode *LoadRoot = Queue.pop_back_val();
7211 if (!Visited.insert(LoadRoot))
7214 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7215 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7218 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7219 UE = LoadRoot->use_end(); UI != UE; ++UI)
7220 if (((isa<LoadSDNode>(*UI) &&
7221 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7222 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7223 Queue.push_back(*UI);
7230 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7231 DAGCombinerInfo &DCI) const {
7232 SelectionDAG &DAG = DCI.DAG;
7235 assert(PPCSubTarget.useCRBits() &&
7236 "Expecting to be tracking CR bits");
7237 // If we're tracking CR bits, we need to be careful that we don't have:
7238 // trunc(binary-ops(zext(x), zext(y)))
7240 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7241 // such that we're unnecessarily moving things into GPRs when it would be
7242 // better to keep them in CR bits.
7244 // Note that trunc here can be an actual i1 trunc, or can be the effective
7245 // truncation that comes from a setcc or select_cc.
7246 if (N->getOpcode() == ISD::TRUNCATE &&
7247 N->getValueType(0) != MVT::i1)
7250 if (N->getOperand(0).getValueType() != MVT::i32 &&
7251 N->getOperand(0).getValueType() != MVT::i64)
7254 if (N->getOpcode() == ISD::SETCC ||
7255 N->getOpcode() == ISD::SELECT_CC) {
7256 // If we're looking at a comparison, then we need to make sure that the
7257 // high bits (all except for the first) don't matter the result.
7259 cast<CondCodeSDNode>(N->getOperand(
7260 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7261 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7263 if (ISD::isSignedIntSetCC(CC)) {
7264 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7265 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7267 } else if (ISD::isUnsignedIntSetCC(CC)) {
7268 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7269 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7270 !DAG.MaskedValueIsZero(N->getOperand(1),
7271 APInt::getHighBitsSet(OpBits, OpBits-1)))
7274 // This is neither a signed nor an unsigned comparison, just make sure
7275 // that the high bits are equal.
7276 APInt Op1Zero, Op1One;
7277 APInt Op2Zero, Op2One;
7278 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7279 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7281 // We don't really care about what is known about the first bit (if
7282 // anything), so clear it in all masks prior to comparing them.
7283 Op1Zero.clearBit(0); Op1One.clearBit(0);
7284 Op2Zero.clearBit(0); Op2One.clearBit(0);
7286 if (Op1Zero != Op2Zero || Op1One != Op2One)
7291 // We now know that the higher-order bits are irrelevant, we just need to
7292 // make sure that all of the intermediate operations are bit operations, and
7293 // all inputs are extensions.
7294 if (N->getOperand(0).getOpcode() != ISD::AND &&
7295 N->getOperand(0).getOpcode() != ISD::OR &&
7296 N->getOperand(0).getOpcode() != ISD::XOR &&
7297 N->getOperand(0).getOpcode() != ISD::SELECT &&
7298 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7299 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7300 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7301 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7302 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7305 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7306 N->getOperand(1).getOpcode() != ISD::AND &&
7307 N->getOperand(1).getOpcode() != ISD::OR &&
7308 N->getOperand(1).getOpcode() != ISD::XOR &&
7309 N->getOperand(1).getOpcode() != ISD::SELECT &&
7310 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7311 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7312 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7313 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7314 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7317 SmallVector<SDValue, 4> Inputs;
7318 SmallVector<SDValue, 8> BinOps, PromOps;
7319 SmallPtrSet<SDNode *, 16> Visited;
7321 for (unsigned i = 0; i < 2; ++i) {
7322 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7323 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7324 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7325 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7326 isa<ConstantSDNode>(N->getOperand(i)))
7327 Inputs.push_back(N->getOperand(i));
7329 BinOps.push_back(N->getOperand(i));
7331 if (N->getOpcode() == ISD::TRUNCATE)
7335 // Visit all inputs, collect all binary operations (and, or, xor and
7336 // select) that are all fed by extensions.
7337 while (!BinOps.empty()) {
7338 SDValue BinOp = BinOps.back();
7341 if (!Visited.insert(BinOp.getNode()))
7344 PromOps.push_back(BinOp);
7346 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7347 // The condition of the select is not promoted.
7348 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7350 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7353 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7354 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7355 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7356 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7357 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7358 Inputs.push_back(BinOp.getOperand(i));
7359 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7360 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7361 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7362 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7363 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7364 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7365 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7366 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7367 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7368 BinOps.push_back(BinOp.getOperand(i));
7370 // We have an input that is not an extension or another binary
7371 // operation; we'll abort this transformation.
7377 // Make sure that this is a self-contained cluster of operations (which
7378 // is not quite the same thing as saying that everything has only one
7380 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7381 if (isa<ConstantSDNode>(Inputs[i]))
7384 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7385 UE = Inputs[i].getNode()->use_end();
7388 if (User != N && !Visited.count(User))
7391 // Make sure that we're not going to promote the non-output-value
7392 // operand(s) or SELECT or SELECT_CC.
7393 // FIXME: Although we could sometimes handle this, and it does occur in
7394 // practice that one of the condition inputs to the select is also one of
7395 // the outputs, we currently can't deal with this.
7396 if (User->getOpcode() == ISD::SELECT) {
7397 if (User->getOperand(0) == Inputs[i])
7399 } else if (User->getOpcode() == ISD::SELECT_CC) {
7400 if (User->getOperand(0) == Inputs[i] ||
7401 User->getOperand(1) == Inputs[i])
7407 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7408 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7409 UE = PromOps[i].getNode()->use_end();
7412 if (User != N && !Visited.count(User))
7415 // Make sure that we're not going to promote the non-output-value
7416 // operand(s) or SELECT or SELECT_CC.
7417 // FIXME: Although we could sometimes handle this, and it does occur in
7418 // practice that one of the condition inputs to the select is also one of
7419 // the outputs, we currently can't deal with this.
7420 if (User->getOpcode() == ISD::SELECT) {
7421 if (User->getOperand(0) == PromOps[i])
7423 } else if (User->getOpcode() == ISD::SELECT_CC) {
7424 if (User->getOperand(0) == PromOps[i] ||
7425 User->getOperand(1) == PromOps[i])
7431 // Replace all inputs with the extension operand.
7432 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7433 // Constants may have users outside the cluster of to-be-promoted nodes,
7434 // and so we need to replace those as we do the promotions.
7435 if (isa<ConstantSDNode>(Inputs[i]))
7438 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7441 // Replace all operations (these are all the same, but have a different
7442 // (i1) return type). DAG.getNode will validate that the types of
7443 // a binary operator match, so go through the list in reverse so that
7444 // we've likely promoted both operands first. Any intermediate truncations or
7445 // extensions disappear.
7446 while (!PromOps.empty()) {
7447 SDValue PromOp = PromOps.back();
7450 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7451 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7452 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7453 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7454 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7455 PromOp.getOperand(0).getValueType() != MVT::i1) {
7456 // The operand is not yet ready (see comment below).
7457 PromOps.insert(PromOps.begin(), PromOp);
7461 SDValue RepValue = PromOp.getOperand(0);
7462 if (isa<ConstantSDNode>(RepValue))
7463 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7465 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7470 switch (PromOp.getOpcode()) {
7471 default: C = 0; break;
7472 case ISD::SELECT: C = 1; break;
7473 case ISD::SELECT_CC: C = 2; break;
7476 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7477 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7478 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7479 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7480 // The to-be-promoted operands of this node have not yet been
7481 // promoted (this should be rare because we're going through the
7482 // list backward, but if one of the operands has several users in
7483 // this cluster of to-be-promoted nodes, it is possible).
7484 PromOps.insert(PromOps.begin(), PromOp);
7488 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7489 PromOp.getNode()->op_end());
7491 // If there are any constant inputs, make sure they're replaced now.
7492 for (unsigned i = 0; i < 2; ++i)
7493 if (isa<ConstantSDNode>(Ops[C+i]))
7494 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7496 DAG.ReplaceAllUsesOfValueWith(PromOp,
7497 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7498 Ops.data(), Ops.size()));
7501 // Now we're left with the initial truncation itself.
7502 if (N->getOpcode() == ISD::TRUNCATE)
7503 return N->getOperand(0);
7505 // Otherwise, this is a comparison. The operands to be compared have just
7506 // changed type (to i1), but everything else is the same.
7507 return SDValue(N, 0);
7510 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7511 DAGCombinerInfo &DCI) const {
7512 SelectionDAG &DAG = DCI.DAG;
7515 // If we're tracking CR bits, we need to be careful that we don't have:
7516 // zext(binary-ops(trunc(x), trunc(y)))
7518 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7519 // such that we're unnecessarily moving things into CR bits that can more
7520 // efficiently stay in GPRs. Note that if we're not certain that the high
7521 // bits are set as required by the final extension, we still may need to do
7522 // some masking to get the proper behavior.
7524 // This same functionality is important on PPC64 when dealing with
7525 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7526 // the return values of functions. Because it is so similar, it is handled
7529 if (N->getValueType(0) != MVT::i32 &&
7530 N->getValueType(0) != MVT::i64)
7533 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7534 PPCSubTarget.useCRBits()) ||
7535 (N->getOperand(0).getValueType() == MVT::i32 &&
7536 PPCSubTarget.isPPC64())))
7539 if (N->getOperand(0).getOpcode() != ISD::AND &&
7540 N->getOperand(0).getOpcode() != ISD::OR &&
7541 N->getOperand(0).getOpcode() != ISD::XOR &&
7542 N->getOperand(0).getOpcode() != ISD::SELECT &&
7543 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7546 SmallVector<SDValue, 4> Inputs;
7547 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7548 SmallPtrSet<SDNode *, 16> Visited;
7550 // Visit all inputs, collect all binary operations (and, or, xor and
7551 // select) that are all fed by truncations.
7552 while (!BinOps.empty()) {
7553 SDValue BinOp = BinOps.back();
7556 if (!Visited.insert(BinOp.getNode()))
7559 PromOps.push_back(BinOp);
7561 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7562 // The condition of the select is not promoted.
7563 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7565 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7568 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7569 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7570 Inputs.push_back(BinOp.getOperand(i));
7571 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7572 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7573 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7574 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7575 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7576 BinOps.push_back(BinOp.getOperand(i));
7578 // We have an input that is not a truncation or another binary
7579 // operation; we'll abort this transformation.
7585 // Make sure that this is a self-contained cluster of operations (which
7586 // is not quite the same thing as saying that everything has only one
7588 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7589 if (isa<ConstantSDNode>(Inputs[i]))
7592 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7593 UE = Inputs[i].getNode()->use_end();
7596 if (User != N && !Visited.count(User))
7599 // Make sure that we're not going to promote the non-output-value
7600 // operand(s) or SELECT or SELECT_CC.
7601 // FIXME: Although we could sometimes handle this, and it does occur in
7602 // practice that one of the condition inputs to the select is also one of
7603 // the outputs, we currently can't deal with this.
7604 if (User->getOpcode() == ISD::SELECT) {
7605 if (User->getOperand(0) == Inputs[i])
7607 } else if (User->getOpcode() == ISD::SELECT_CC) {
7608 if (User->getOperand(0) == Inputs[i] ||
7609 User->getOperand(1) == Inputs[i])
7615 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7616 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7617 UE = PromOps[i].getNode()->use_end();
7620 if (User != N && !Visited.count(User))
7623 // Make sure that we're not going to promote the non-output-value
7624 // operand(s) or SELECT or SELECT_CC.
7625 // FIXME: Although we could sometimes handle this, and it does occur in
7626 // practice that one of the condition inputs to the select is also one of
7627 // the outputs, we currently can't deal with this.
7628 if (User->getOpcode() == ISD::SELECT) {
7629 if (User->getOperand(0) == PromOps[i])
7631 } else if (User->getOpcode() == ISD::SELECT_CC) {
7632 if (User->getOperand(0) == PromOps[i] ||
7633 User->getOperand(1) == PromOps[i])
7639 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7640 bool ReallyNeedsExt = false;
7641 if (N->getOpcode() != ISD::ANY_EXTEND) {
7642 // If all of the inputs are not already sign/zero extended, then
7643 // we'll still need to do that at the end.
7644 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7645 if (isa<ConstantSDNode>(Inputs[i]))
7649 Inputs[i].getOperand(0).getValueSizeInBits();
7650 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7652 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7653 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7654 APInt::getHighBitsSet(OpBits,
7655 OpBits-PromBits))) ||
7656 (N->getOpcode() == ISD::SIGN_EXTEND &&
7657 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7658 (OpBits-(PromBits-1)))) {
7659 ReallyNeedsExt = true;
7665 // Replace all inputs, either with the truncation operand, or a
7666 // truncation or extension to the final output type.
7667 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7668 // Constant inputs need to be replaced with the to-be-promoted nodes that
7669 // use them because they might have users outside of the cluster of
7671 if (isa<ConstantSDNode>(Inputs[i]))
7674 SDValue InSrc = Inputs[i].getOperand(0);
7675 if (Inputs[i].getValueType() == N->getValueType(0))
7676 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7677 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7678 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7679 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7680 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7681 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7682 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7684 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7685 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7688 // Replace all operations (these are all the same, but have a different
7689 // (promoted) return type). DAG.getNode will validate that the types of
7690 // a binary operator match, so go through the list in reverse so that
7691 // we've likely promoted both operands first.
7692 while (!PromOps.empty()) {
7693 SDValue PromOp = PromOps.back();
7697 switch (PromOp.getOpcode()) {
7698 default: C = 0; break;
7699 case ISD::SELECT: C = 1; break;
7700 case ISD::SELECT_CC: C = 2; break;
7703 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7704 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7705 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7706 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7707 // The to-be-promoted operands of this node have not yet been
7708 // promoted (this should be rare because we're going through the
7709 // list backward, but if one of the operands has several users in
7710 // this cluster of to-be-promoted nodes, it is possible).
7711 PromOps.insert(PromOps.begin(), PromOp);
7715 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7716 PromOp.getNode()->op_end());
7718 // If this node has constant inputs, then they'll need to be promoted here.
7719 for (unsigned i = 0; i < 2; ++i) {
7720 if (!isa<ConstantSDNode>(Ops[C+i]))
7722 if (Ops[C+i].getValueType() == N->getValueType(0))
7725 if (N->getOpcode() == ISD::SIGN_EXTEND)
7726 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7727 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7728 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7730 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7733 DAG.ReplaceAllUsesOfValueWith(PromOp,
7734 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7735 Ops.data(), Ops.size()));
7738 // Now we're left with the initial extension itself.
7739 if (!ReallyNeedsExt)
7740 return N->getOperand(0);
7742 // To zero extend, just mask off everything except for the first bit (in the
7744 if (N->getOpcode() == ISD::ZERO_EXTEND)
7745 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7746 DAG.getConstant(APInt::getLowBitsSet(
7747 N->getValueSizeInBits(0), PromBits),
7748 N->getValueType(0)));
7750 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7751 "Invalid extension type");
7752 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7754 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7755 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7756 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7757 N->getOperand(0), ShiftCst), ShiftCst);
7760 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7761 DAGCombinerInfo &DCI) const {
7762 const TargetMachine &TM = getTargetMachine();
7763 SelectionDAG &DAG = DCI.DAG;
7765 switch (N->getOpcode()) {
7768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7769 if (C->isNullValue()) // 0 << V -> 0.
7770 return N->getOperand(0);
7774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7775 if (C->isNullValue()) // 0 >>u V -> 0.
7776 return N->getOperand(0);
7780 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7781 if (C->isNullValue() || // 0 >>s V -> 0.
7782 C->isAllOnesValue()) // -1 >>s V -> -1.
7783 return N->getOperand(0);
7786 case ISD::SIGN_EXTEND:
7787 case ISD::ZERO_EXTEND:
7788 case ISD::ANY_EXTEND:
7789 return DAGCombineExtBoolTrunc(N, DCI);
7792 case ISD::SELECT_CC:
7793 return DAGCombineTruncBoolExt(N, DCI);
7795 assert(TM.Options.UnsafeFPMath &&
7796 "Reciprocal estimates require UnsafeFPMath");
7798 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7800 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7801 if (RV.getNode() != 0) {
7802 DCI.AddToWorklist(RV.getNode());
7803 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7804 N->getOperand(0), RV);
7806 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7807 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7809 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7811 if (RV.getNode() != 0) {
7812 DCI.AddToWorklist(RV.getNode());
7813 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7814 N->getValueType(0), RV);
7815 DCI.AddToWorklist(RV.getNode());
7816 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7817 N->getOperand(0), RV);
7819 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7820 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7822 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7824 if (RV.getNode() != 0) {
7825 DCI.AddToWorklist(RV.getNode());
7826 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7827 N->getValueType(0), RV,
7828 N->getOperand(1).getOperand(1));
7829 DCI.AddToWorklist(RV.getNode());
7830 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7831 N->getOperand(0), RV);
7835 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7836 if (RV.getNode() != 0) {
7837 DCI.AddToWorklist(RV.getNode());
7838 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7839 N->getOperand(0), RV);
7845 assert(TM.Options.UnsafeFPMath &&
7846 "Reciprocal estimates require UnsafeFPMath");
7848 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7850 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7851 if (RV.getNode() != 0) {
7852 DCI.AddToWorklist(RV.getNode());
7853 RV = DAGCombineFastRecip(RV, DCI);
7854 if (RV.getNode() != 0) {
7855 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7856 // this case and force the answer to 0.
7858 EVT VT = RV.getValueType();
7860 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7861 if (VT.isVector()) {
7862 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7863 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7867 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7868 N->getOperand(0), Zero, ISD::SETEQ);
7869 DCI.AddToWorklist(ZeroCmp.getNode());
7870 DCI.AddToWorklist(RV.getNode());
7872 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7880 case ISD::SINT_TO_FP:
7881 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7882 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7883 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7884 // We allow the src/dst to be either f32/f64, but the intermediate
7885 // type must be i64.
7886 if (N->getOperand(0).getValueType() == MVT::i64 &&
7887 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7888 SDValue Val = N->getOperand(0).getOperand(0);
7889 if (Val.getValueType() == MVT::f32) {
7890 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7891 DCI.AddToWorklist(Val.getNode());
7894 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7895 DCI.AddToWorklist(Val.getNode());
7896 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7897 DCI.AddToWorklist(Val.getNode());
7898 if (N->getValueType(0) == MVT::f32) {
7899 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7900 DAG.getIntPtrConstant(0));
7901 DCI.AddToWorklist(Val.getNode());
7904 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7905 // If the intermediate type is i32, we can avoid the load/store here
7912 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7913 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7914 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7915 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7916 N->getOperand(1).getValueType() == MVT::i32 &&
7917 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7918 SDValue Val = N->getOperand(1).getOperand(0);
7919 if (Val.getValueType() == MVT::f32) {
7920 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7921 DCI.AddToWorklist(Val.getNode());
7923 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7924 DCI.AddToWorklist(Val.getNode());
7927 N->getOperand(0), Val, N->getOperand(2),
7928 DAG.getValueType(N->getOperand(1).getValueType())
7931 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7932 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7933 cast<StoreSDNode>(N)->getMemoryVT(),
7934 cast<StoreSDNode>(N)->getMemOperand());
7935 DCI.AddToWorklist(Val.getNode());
7939 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7940 if (cast<StoreSDNode>(N)->isUnindexed() &&
7941 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7942 N->getOperand(1).getNode()->hasOneUse() &&
7943 (N->getOperand(1).getValueType() == MVT::i32 ||
7944 N->getOperand(1).getValueType() == MVT::i16 ||
7945 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7946 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7947 N->getOperand(1).getValueType() == MVT::i64))) {
7948 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7949 // Do an any-extend to 32-bits if this is a half-word input.
7950 if (BSwapOp.getValueType() == MVT::i16)
7951 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7954 N->getOperand(0), BSwapOp, N->getOperand(2),
7955 DAG.getValueType(N->getOperand(1).getValueType())
7958 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7959 Ops, array_lengthof(Ops),
7960 cast<StoreSDNode>(N)->getMemoryVT(),
7961 cast<StoreSDNode>(N)->getMemOperand());
7965 LoadSDNode *LD = cast<LoadSDNode>(N);
7966 EVT VT = LD->getValueType(0);
7967 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7968 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7969 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7970 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7971 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7972 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7973 LD->getAlignment() < ABIAlignment) {
7974 // This is a type-legal unaligned Altivec load.
7975 SDValue Chain = LD->getChain();
7976 SDValue Ptr = LD->getBasePtr();
7978 // This implements the loading of unaligned vectors as described in
7979 // the venerable Apple Velocity Engine overview. Specifically:
7980 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7981 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7983 // The general idea is to expand a sequence of one or more unaligned
7984 // loads into a alignment-based permutation-control instruction (lvsl),
7985 // a series of regular vector loads (which always truncate their
7986 // input address to an aligned address), and a series of permutations.
7987 // The results of these permutations are the requested loaded values.
7988 // The trick is that the last "extra" load is not taken from the address
7989 // you might suspect (sizeof(vector) bytes after the last requested
7990 // load), but rather sizeof(vector) - 1 bytes after the last
7991 // requested vector. The point of this is to avoid a page fault if the
7992 // base address happened to be aligned. This works because if the base
7993 // address is aligned, then adding less than a full vector length will
7994 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7995 // the next vector will be fetched as you might suspect was necessary.
7997 // We might be able to reuse the permutation generation from
7998 // a different base address offset from this one by an aligned amount.
7999 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8000 // optimization later.
8001 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8002 DAG, dl, MVT::v16i8);
8004 // Refine the alignment of the original load (a "new" load created here
8005 // which was identical to the first except for the alignment would be
8006 // merged with the existing node regardless).
8007 MachineFunction &MF = DAG.getMachineFunction();
8008 MachineMemOperand *MMO =
8009 MF.getMachineMemOperand(LD->getPointerInfo(),
8010 LD->getMemOperand()->getFlags(),
8011 LD->getMemoryVT().getStoreSize(),
8013 LD->refineAlignment(MMO);
8014 SDValue BaseLoad = SDValue(LD, 0);
8016 // Note that the value of IncOffset (which is provided to the next
8017 // load's pointer info offset value, and thus used to calculate the
8018 // alignment), and the value of IncValue (which is actually used to
8019 // increment the pointer value) are different! This is because we
8020 // require the next load to appear to be aligned, even though it
8021 // is actually offset from the base pointer by a lesser amount.
8022 int IncOffset = VT.getSizeInBits() / 8;
8023 int IncValue = IncOffset;
8025 // Walk (both up and down) the chain looking for another load at the real
8026 // (aligned) offset (the alignment of the other load does not matter in
8027 // this case). If found, then do not use the offset reduction trick, as
8028 // that will prevent the loads from being later combined (as they would
8029 // otherwise be duplicates).
8030 if (!findConsecutiveLoad(LD, DAG))
8033 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8034 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8037 DAG.getLoad(VT, dl, Chain, Ptr,
8038 LD->getPointerInfo().getWithOffset(IncOffset),
8039 LD->isVolatile(), LD->isNonTemporal(),
8040 LD->isInvariant(), ABIAlignment);
8042 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8043 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8045 if (BaseLoad.getValueType() != MVT::v4i32)
8046 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8048 if (ExtraLoad.getValueType() != MVT::v4i32)
8049 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8051 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8052 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8054 if (VT != MVT::v4i32)
8055 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8057 // Now we need to be really careful about how we update the users of the
8058 // original load. We cannot just call DCI.CombineTo (or
8059 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8060 // uses created here (the permutation for example) that need to stay.
8061 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8063 SDUse &Use = UI.getUse();
8065 // Note: BaseLoad is checked here because it might not be N, but a
8067 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8068 User == TF.getNode() || Use.getResNo() > 1) {
8073 SDValue To = Use.getResNo() ? TF : Perm;
8076 SmallVector<SDValue, 8> Ops;
8077 for (SDNode::op_iterator O = User->op_begin(),
8078 OE = User->op_end(); O != OE; ++O) {
8085 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
8088 return SDValue(N, 0);
8092 case ISD::INTRINSIC_WO_CHAIN:
8093 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8094 Intrinsic::ppc_altivec_lvsl &&
8095 N->getOperand(1)->getOpcode() == ISD::ADD) {
8096 SDValue Add = N->getOperand(1);
8098 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8099 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8100 Add.getValueType().getScalarType().getSizeInBits()))) {
8101 SDNode *BasePtr = Add->getOperand(0).getNode();
8102 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8103 UE = BasePtr->use_end(); UI != UE; ++UI) {
8104 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8105 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8106 Intrinsic::ppc_altivec_lvsl) {
8107 // We've found another LVSL, and this address if an aligned
8108 // multiple of that one. The results will be the same, so use the
8109 // one we've just found instead.
8111 return SDValue(*UI, 0);
8119 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8120 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8121 N->getOperand(0).hasOneUse() &&
8122 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8123 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8124 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8125 N->getValueType(0) == MVT::i64))) {
8126 SDValue Load = N->getOperand(0);
8127 LoadSDNode *LD = cast<LoadSDNode>(Load);
8128 // Create the byte-swapping load.
8130 LD->getChain(), // Chain
8131 LD->getBasePtr(), // Ptr
8132 DAG.getValueType(N->getValueType(0)) // VT
8135 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8136 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8137 MVT::i64 : MVT::i32, MVT::Other),
8138 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8140 // If this is an i16 load, insert the truncate.
8141 SDValue ResVal = BSLoad;
8142 if (N->getValueType(0) == MVT::i16)
8143 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8145 // First, combine the bswap away. This makes the value produced by the
8147 DCI.CombineTo(N, ResVal);
8149 // Next, combine the load away, we give it a bogus result value but a real
8150 // chain result. The result value is dead because the bswap is dead.
8151 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8153 // Return N so it doesn't get rechecked!
8154 return SDValue(N, 0);
8158 case PPCISD::VCMP: {
8159 // If a VCMPo node already exists with exactly the same operands as this
8160 // node, use its result instead of this node (VCMPo computes both a CR6 and
8161 // a normal output).
8163 if (!N->getOperand(0).hasOneUse() &&
8164 !N->getOperand(1).hasOneUse() &&
8165 !N->getOperand(2).hasOneUse()) {
8167 // Scan all of the users of the LHS, looking for VCMPo's that match.
8168 SDNode *VCMPoNode = 0;
8170 SDNode *LHSN = N->getOperand(0).getNode();
8171 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8173 if (UI->getOpcode() == PPCISD::VCMPo &&
8174 UI->getOperand(1) == N->getOperand(1) &&
8175 UI->getOperand(2) == N->getOperand(2) &&
8176 UI->getOperand(0) == N->getOperand(0)) {
8181 // If there is no VCMPo node, or if the flag value has a single use, don't
8183 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8186 // Look at the (necessarily single) use of the flag value. If it has a
8187 // chain, this transformation is more complex. Note that multiple things
8188 // could use the value result, which we should ignore.
8189 SDNode *FlagUser = 0;
8190 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8191 FlagUser == 0; ++UI) {
8192 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8194 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8195 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8202 // If the user is a MFOCRF instruction, we know this is safe.
8203 // Otherwise we give up for right now.
8204 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8205 return SDValue(VCMPoNode, 0);
8210 SDValue Cond = N->getOperand(1);
8211 SDValue Target = N->getOperand(2);
8213 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8214 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8215 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8217 // We now need to make the intrinsic dead (it cannot be instruction
8219 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8220 assert(Cond.getNode()->hasOneUse() &&
8221 "Counter decrement has more than one use");
8223 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8224 N->getOperand(0), Target);
8229 // If this is a branch on an altivec predicate comparison, lower this so
8230 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8231 // lowering is done pre-legalize, because the legalizer lowers the predicate
8232 // compare down to code that is difficult to reassemble.
8233 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8234 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8236 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8237 // value. If so, pass-through the AND to get to the intrinsic.
8238 if (LHS.getOpcode() == ISD::AND &&
8239 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8240 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8241 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8242 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8243 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8245 LHS = LHS.getOperand(0);
8247 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8248 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8249 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8250 isa<ConstantSDNode>(RHS)) {
8251 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8252 "Counter decrement comparison is not EQ or NE");
8254 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8255 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8256 (CC == ISD::SETNE && !Val);
8258 // We now need to make the intrinsic dead (it cannot be instruction
8260 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8261 assert(LHS.getNode()->hasOneUse() &&
8262 "Counter decrement has more than one use");
8264 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8265 N->getOperand(0), N->getOperand(4));
8271 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8272 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8273 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8274 assert(isDot && "Can't compare against a vector result!");
8276 // If this is a comparison against something other than 0/1, then we know
8277 // that the condition is never/always true.
8278 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8279 if (Val != 0 && Val != 1) {
8280 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8281 return N->getOperand(0);
8282 // Always !=, turn it into an unconditional branch.
8283 return DAG.getNode(ISD::BR, dl, MVT::Other,
8284 N->getOperand(0), N->getOperand(4));
8287 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8289 // Create the PPCISD altivec 'dot' comparison node.
8291 LHS.getOperand(2), // LHS of compare
8292 LHS.getOperand(3), // RHS of compare
8293 DAG.getConstant(CompareOpc, MVT::i32)
8295 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8296 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8298 // Unpack the result based on how the target uses it.
8299 PPC::Predicate CompOpc;
8300 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8301 default: // Can't happen, don't crash on invalid number though.
8302 case 0: // Branch on the value of the EQ bit of CR6.
8303 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8305 case 1: // Branch on the inverted value of the EQ bit of CR6.
8306 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8308 case 2: // Branch on the value of the LT bit of CR6.
8309 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8311 case 3: // Branch on the inverted value of the LT bit of CR6.
8312 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8316 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8317 DAG.getConstant(CompOpc, MVT::i32),
8318 DAG.getRegister(PPC::CR6, MVT::i32),
8319 N->getOperand(4), CompNode.getValue(1));
8328 //===----------------------------------------------------------------------===//
8329 // Inline Assembly Support
8330 //===----------------------------------------------------------------------===//
8332 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8335 const SelectionDAG &DAG,
8336 unsigned Depth) const {
8337 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8338 switch (Op.getOpcode()) {
8340 case PPCISD::LBRX: {
8341 // lhbrx is known to have the top bits cleared out.
8342 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8343 KnownZero = 0xFFFF0000;
8346 case ISD::INTRINSIC_WO_CHAIN: {
8347 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8349 case Intrinsic::ppc_altivec_vcmpbfp_p:
8350 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8351 case Intrinsic::ppc_altivec_vcmpequb_p:
8352 case Intrinsic::ppc_altivec_vcmpequh_p:
8353 case Intrinsic::ppc_altivec_vcmpequw_p:
8354 case Intrinsic::ppc_altivec_vcmpgefp_p:
8355 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8356 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8357 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8358 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8359 case Intrinsic::ppc_altivec_vcmpgtub_p:
8360 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8361 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8362 KnownZero = ~1U; // All bits but the low one are known to be zero.
8370 /// getConstraintType - Given a constraint, return the type of
8371 /// constraint it is for this target.
8372 PPCTargetLowering::ConstraintType
8373 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8374 if (Constraint.size() == 1) {
8375 switch (Constraint[0]) {
8382 return C_RegisterClass;
8384 // FIXME: While Z does indicate a memory constraint, it specifically
8385 // indicates an r+r address (used in conjunction with the 'y' modifier
8386 // in the replacement string). Currently, we're forcing the base
8387 // register to be r0 in the asm printer (which is interpreted as zero)
8388 // and forming the complete address in the second register. This is
8392 } else if (Constraint == "wc") { // individual CR bits.
8393 return C_RegisterClass;
8394 } else if (Constraint == "wa" || Constraint == "wd" ||
8395 Constraint == "wf" || Constraint == "ws") {
8396 return C_RegisterClass; // VSX registers.
8398 return TargetLowering::getConstraintType(Constraint);
8401 /// Examine constraint type and operand type and determine a weight value.
8402 /// This object must already have been set up with the operand type
8403 /// and the current alternative constraint selected.
8404 TargetLowering::ConstraintWeight
8405 PPCTargetLowering::getSingleConstraintMatchWeight(
8406 AsmOperandInfo &info, const char *constraint) const {
8407 ConstraintWeight weight = CW_Invalid;
8408 Value *CallOperandVal = info.CallOperandVal;
8409 // If we don't have a value, we can't do a match,
8410 // but allow it at the lowest weight.
8411 if (CallOperandVal == NULL)
8413 Type *type = CallOperandVal->getType();
8415 // Look at the constraint type.
8416 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8417 return CW_Register; // an individual CR bit.
8418 else if ((StringRef(constraint) == "wa" ||
8419 StringRef(constraint) == "wd" ||
8420 StringRef(constraint) == "wf") &&
8423 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8426 switch (*constraint) {
8428 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8431 if (type->isIntegerTy())
8432 weight = CW_Register;
8435 if (type->isFloatTy())
8436 weight = CW_Register;
8439 if (type->isDoubleTy())
8440 weight = CW_Register;
8443 if (type->isVectorTy())
8444 weight = CW_Register;
8447 weight = CW_Register;
8456 std::pair<unsigned, const TargetRegisterClass*>
8457 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8459 if (Constraint.size() == 1) {
8460 // GCC RS6000 Constraint Letters
8461 switch (Constraint[0]) {
8463 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8464 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8465 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8467 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8468 return std::make_pair(0U, &PPC::G8RCRegClass);
8469 return std::make_pair(0U, &PPC::GPRCRegClass);
8471 if (VT == MVT::f32 || VT == MVT::i32)
8472 return std::make_pair(0U, &PPC::F4RCRegClass);
8473 if (VT == MVT::f64 || VT == MVT::i64)
8474 return std::make_pair(0U, &PPC::F8RCRegClass);
8477 return std::make_pair(0U, &PPC::VRRCRegClass);
8479 return std::make_pair(0U, &PPC::CRRCRegClass);
8481 } else if (Constraint == "wc") { // an individual CR bit.
8482 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8483 } else if (Constraint == "wa" || Constraint == "wd" ||
8484 Constraint == "wf" || Constraint == "ws") {
8485 return std::make_pair(0U, &PPC::VSRCRegClass);
8488 std::pair<unsigned, const TargetRegisterClass*> R =
8489 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8491 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8492 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8493 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8495 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8496 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8497 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8498 PPC::GPRCRegClass.contains(R.first)) {
8499 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8500 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8501 PPC::sub_32, &PPC::G8RCRegClass),
8502 &PPC::G8RCRegClass);
8509 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8510 /// vector. If it is invalid, don't add anything to Ops.
8511 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8512 std::string &Constraint,
8513 std::vector<SDValue>&Ops,
8514 SelectionDAG &DAG) const {
8515 SDValue Result(0,0);
8517 // Only support length 1 constraints.
8518 if (Constraint.length() > 1) return;
8520 char Letter = Constraint[0];
8531 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8532 if (!CST) return; // Must be an immediate to match.
8533 unsigned Value = CST->getZExtValue();
8535 default: llvm_unreachable("Unknown constraint letter!");
8536 case 'I': // "I" is a signed 16-bit constant.
8537 if ((short)Value == (int)Value)
8538 Result = DAG.getTargetConstant(Value, Op.getValueType());
8540 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8541 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8542 if ((short)Value == 0)
8543 Result = DAG.getTargetConstant(Value, Op.getValueType());
8545 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8546 if ((Value >> 16) == 0)
8547 Result = DAG.getTargetConstant(Value, Op.getValueType());
8549 case 'M': // "M" is a constant that is greater than 31.
8551 Result = DAG.getTargetConstant(Value, Op.getValueType());
8553 case 'N': // "N" is a positive constant that is an exact power of two.
8554 if ((int)Value > 0 && isPowerOf2_32(Value))
8555 Result = DAG.getTargetConstant(Value, Op.getValueType());
8557 case 'O': // "O" is the constant zero.
8559 Result = DAG.getTargetConstant(Value, Op.getValueType());
8561 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8562 if ((short)-Value == (int)-Value)
8563 Result = DAG.getTargetConstant(Value, Op.getValueType());
8570 if (Result.getNode()) {
8571 Ops.push_back(Result);
8575 // Handle standard constraint letters.
8576 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8579 // isLegalAddressingMode - Return true if the addressing mode represented
8580 // by AM is legal for this target, for a load/store of the specified type.
8581 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8583 // FIXME: PPC does not allow r+i addressing modes for vectors!
8585 // PPC allows a sign-extended 16-bit immediate field.
8586 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8589 // No global is ever allowed as a base.
8593 // PPC only support r+r,
8595 case 0: // "r+i" or just "i", depending on HasBaseReg.
8598 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8600 // Otherwise we have r+r or r+i.
8603 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8605 // Allow 2*r as r+r.
8608 // No other scales are supported.
8615 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8616 SelectionDAG &DAG) const {
8617 MachineFunction &MF = DAG.getMachineFunction();
8618 MachineFrameInfo *MFI = MF.getFrameInfo();
8619 MFI->setReturnAddressIsTaken(true);
8621 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8625 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8627 // Make sure the function does not optimize away the store of the RA to
8629 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8630 FuncInfo->setLRStoreRequired();
8631 bool isPPC64 = PPCSubTarget.isPPC64();
8632 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8635 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8638 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8639 isPPC64? MVT::i64 : MVT::i32);
8640 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8641 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8643 MachinePointerInfo(), false, false, false, 0);
8646 // Just load the return address off the stack.
8647 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8648 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8649 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8652 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8653 SelectionDAG &DAG) const {
8655 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8657 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8658 bool isPPC64 = PtrVT == MVT::i64;
8660 MachineFunction &MF = DAG.getMachineFunction();
8661 MachineFrameInfo *MFI = MF.getFrameInfo();
8662 MFI->setFrameAddressIsTaken(true);
8664 // Naked functions never have a frame pointer, and so we use r1. For all
8665 // other functions, this decision must be delayed until during PEI.
8667 if (MF.getFunction()->getAttributes().hasAttribute(
8668 AttributeSet::FunctionIndex, Attribute::Naked))
8669 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8671 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8673 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8676 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8677 FrameAddr, MachinePointerInfo(), false, false,
8683 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8684 // The PowerPC target isn't yet aware of offsets.
8688 /// getOptimalMemOpType - Returns the target specific optimal type for load
8689 /// and store operations as a result of memset, memcpy, and memmove
8690 /// lowering. If DstAlign is zero that means it's safe to destination
8691 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8692 /// means there isn't a need to check it against alignment requirement,
8693 /// probably because the source does not need to be loaded. If 'IsMemset' is
8694 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8695 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8696 /// source is constant so it does not need to be loaded.
8697 /// It returns EVT::Other if the type should be determined using generic
8698 /// target-independent logic.
8699 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8700 unsigned DstAlign, unsigned SrcAlign,
8701 bool IsMemset, bool ZeroMemset,
8703 MachineFunction &MF) const {
8704 if (this->PPCSubTarget.isPPC64()) {
8711 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8714 if (DisablePPCUnaligned)
8717 // PowerPC supports unaligned memory access for simple non-vector types.
8718 // Although accessing unaligned addresses is not as efficient as accessing
8719 // aligned addresses, it is generally more efficient than manual expansion,
8720 // and generally only traps for software emulation when crossing page
8726 if (VT.getSimpleVT().isVector()) {
8727 if (PPCSubTarget.hasVSX()) {
8728 if (VT != MVT::v2f64 && VT != MVT::v2i64)
8735 if (VT == MVT::ppcf128)
8744 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8745 VT = VT.getScalarType();
8750 switch (VT.getSimpleVT().SimpleTy) {
8761 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8762 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8763 return TargetLowering::getSchedulingPreference(N);
8768 // Create a fast isel object.
8770 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8771 const TargetLibraryInfo *LibInfo) const {
8772 return PPC::createFastISel(FuncInfo, LibInfo);