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 "PPCMachineFunctionInfo.h"
16 #include "PPCPredicates.h"
17 #include "PPCTargetMachine.h"
18 #include "PPCPerfectShuffle.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/VectorExtras.h"
21 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/Constants.h"
30 #include "llvm/Function.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/CommandLine.h"
37 static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc",
38 cl::desc("enable preincrement load/store generation on PPC (experimental)"),
41 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
42 : TargetLowering(TM), PPCSubTarget(*TM.getSubtargetImpl()),
43 PPCAtomicLabelIndex(0) {
47 // Use _setjmp/_longjmp instead of setjmp/longjmp.
48 setUseUnderscoreSetJmp(true);
49 setUseUnderscoreLongJmp(true);
51 // Set up the register classes.
52 addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
53 addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
54 addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
56 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
57 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
58 setLoadXAction(ISD::SEXTLOAD, MVT::i8, Expand);
60 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
62 // PowerPC has pre-inc load and store's.
63 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
64 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
65 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
66 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
67 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
68 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
69 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
70 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
71 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
72 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
74 // Shortening conversions involving ppcf128 get expanded (2 regs -> 1 reg)
75 setConvertAction(MVT::ppcf128, MVT::f64, Expand);
76 setConvertAction(MVT::ppcf128, MVT::f32, Expand);
77 // This is used in the ppcf128->int sequence. Note it has different semantics
78 // from FP_ROUND: that rounds to nearest, this rounds to zero.
79 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
81 // PowerPC has no intrinsics for these particular operations
82 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
84 // PowerPC has no SREM/UREM instructions
85 setOperationAction(ISD::SREM, MVT::i32, Expand);
86 setOperationAction(ISD::UREM, MVT::i32, Expand);
87 setOperationAction(ISD::SREM, MVT::i64, Expand);
88 setOperationAction(ISD::UREM, MVT::i64, Expand);
90 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
91 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
92 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
93 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
94 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
95 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
96 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
97 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
98 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
100 // We don't support sin/cos/sqrt/fmod/pow
101 setOperationAction(ISD::FSIN , MVT::f64, Expand);
102 setOperationAction(ISD::FCOS , MVT::f64, Expand);
103 setOperationAction(ISD::FREM , MVT::f64, Expand);
104 setOperationAction(ISD::FPOW , MVT::f64, Expand);
105 setOperationAction(ISD::FSIN , MVT::f32, Expand);
106 setOperationAction(ISD::FCOS , MVT::f32, Expand);
107 setOperationAction(ISD::FREM , MVT::f32, Expand);
108 setOperationAction(ISD::FPOW , MVT::f32, Expand);
110 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
112 // If we're enabling GP optimizations, use hardware square root
113 if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
114 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
115 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
118 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
119 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
121 // PowerPC does not have BSWAP, CTPOP or CTTZ
122 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
123 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
124 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
125 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
126 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
127 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
129 // PowerPC does not have ROTR
130 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
132 // PowerPC does not have Select
133 setOperationAction(ISD::SELECT, MVT::i32, Expand);
134 setOperationAction(ISD::SELECT, MVT::i64, Expand);
135 setOperationAction(ISD::SELECT, MVT::f32, Expand);
136 setOperationAction(ISD::SELECT, MVT::f64, Expand);
138 // PowerPC wants to turn select_cc of FP into fsel when possible.
139 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
140 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
142 // PowerPC wants to optimize integer setcc a bit
143 setOperationAction(ISD::SETCC, MVT::i32, Custom);
145 // PowerPC does not have BRCOND which requires SetCC
146 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
148 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
150 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
151 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
153 // PowerPC does not have [U|S]INT_TO_FP
154 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
155 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
157 setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
158 setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
159 setOperationAction(ISD::BIT_CONVERT, MVT::i64, Expand);
160 setOperationAction(ISD::BIT_CONVERT, MVT::f64, Expand);
162 // We cannot sextinreg(i1). Expand to shifts.
163 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
165 // Support label based line numbers.
166 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
167 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
169 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
170 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
171 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
172 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
175 // We want to legalize GlobalAddress and ConstantPool nodes into the
176 // appropriate instructions to materialize the address.
177 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
178 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
179 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
180 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
181 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
182 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
183 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
184 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
186 // RET must be custom lowered, to meet ABI requirements
187 setOperationAction(ISD::RET , MVT::Other, Custom);
189 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
190 setOperationAction(ISD::VASTART , MVT::Other, Custom);
192 // VAARG is custom lowered with ELF 32 ABI
193 if (TM.getSubtarget<PPCSubtarget>().isELF32_ABI())
194 setOperationAction(ISD::VAARG, MVT::Other, Custom);
196 setOperationAction(ISD::VAARG, MVT::Other, Expand);
198 // Use the default implementation.
199 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
200 setOperationAction(ISD::VAEND , MVT::Other, Expand);
201 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
202 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
203 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
204 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
206 setOperationAction(ISD::ATOMIC_LAS , MVT::i32 , Custom);
207 setOperationAction(ISD::ATOMIC_LCS , MVT::i32 , Custom);
208 setOperationAction(ISD::ATOMIC_SWAP , MVT::i32 , Custom);
209 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
210 setOperationAction(ISD::ATOMIC_LAS , MVT::i64 , Custom);
211 setOperationAction(ISD::ATOMIC_LCS , MVT::i64 , Custom);
212 setOperationAction(ISD::ATOMIC_SWAP , MVT::i64 , Custom);
215 // We want to custom lower some of our intrinsics.
216 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
218 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
219 // They also have instructions for converting between i64 and fp.
220 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
221 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
222 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
223 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
224 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
226 // FIXME: disable this lowered code. This generates 64-bit register values,
227 // and we don't model the fact that the top part is clobbered by calls. We
228 // need to flag these together so that the value isn't live across a call.
229 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
231 // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
232 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
234 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
235 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
238 if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
239 // 64-bit PowerPC implementations can support i64 types directly
240 addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
241 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
242 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
243 // 64-bit PowerPC wants to expand i128 shifts itself.
244 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
245 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
246 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
248 // 32-bit PowerPC wants to expand i64 shifts itself.
249 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
250 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
251 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
254 if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
255 // First set operation action for all vector types to expand. Then we
256 // will selectively turn on ones that can be effectively codegen'd.
257 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
258 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
259 // add/sub are legal for all supported vector VT's.
260 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Legal);
261 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Legal);
263 // We promote all shuffles to v16i8.
264 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Promote);
265 AddPromotedToType (ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, MVT::v16i8);
267 // We promote all non-typed operations to v4i32.
268 setOperationAction(ISD::AND , (MVT::ValueType)VT, Promote);
269 AddPromotedToType (ISD::AND , (MVT::ValueType)VT, MVT::v4i32);
270 setOperationAction(ISD::OR , (MVT::ValueType)VT, Promote);
271 AddPromotedToType (ISD::OR , (MVT::ValueType)VT, MVT::v4i32);
272 setOperationAction(ISD::XOR , (MVT::ValueType)VT, Promote);
273 AddPromotedToType (ISD::XOR , (MVT::ValueType)VT, MVT::v4i32);
274 setOperationAction(ISD::LOAD , (MVT::ValueType)VT, Promote);
275 AddPromotedToType (ISD::LOAD , (MVT::ValueType)VT, MVT::v4i32);
276 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
277 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v4i32);
278 setOperationAction(ISD::STORE, (MVT::ValueType)VT, Promote);
279 AddPromotedToType (ISD::STORE, (MVT::ValueType)VT, MVT::v4i32);
281 // No other operations are legal.
282 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
283 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
284 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
285 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
286 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
287 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
288 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
289 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
290 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
291 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Expand);
292 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
293 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
294 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
295 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
296 setOperationAction(ISD::SCALAR_TO_VECTOR, (MVT::ValueType)VT, Expand);
297 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
298 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
299 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
300 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
303 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
304 // with merges, splats, etc.
305 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
307 setOperationAction(ISD::AND , MVT::v4i32, Legal);
308 setOperationAction(ISD::OR , MVT::v4i32, Legal);
309 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
310 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
311 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
312 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
314 addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
315 addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
316 addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
317 addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
319 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
320 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
321 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
322 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
324 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
325 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
327 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
328 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
329 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
330 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
333 setShiftAmountType(MVT::i32);
334 setSetCCResultContents(ZeroOrOneSetCCResult);
336 if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
337 setStackPointerRegisterToSaveRestore(PPC::X1);
338 setExceptionPointerRegister(PPC::X3);
339 setExceptionSelectorRegister(PPC::X4);
341 setStackPointerRegisterToSaveRestore(PPC::R1);
342 setExceptionPointerRegister(PPC::R3);
343 setExceptionSelectorRegister(PPC::R4);
346 // We have target-specific dag combine patterns for the following nodes:
347 setTargetDAGCombine(ISD::SINT_TO_FP);
348 setTargetDAGCombine(ISD::STORE);
349 setTargetDAGCombine(ISD::BR_CC);
350 setTargetDAGCombine(ISD::BSWAP);
352 // Darwin long double math library functions have $LDBL128 appended.
353 if (TM.getSubtarget<PPCSubtarget>().isDarwin()) {
354 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
355 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
356 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
357 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
358 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
361 computeRegisterProperties();
364 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
365 /// function arguments in the caller parameter area.
366 unsigned PPCTargetLowering::getByValTypeAlignment(const Type *Ty) const {
367 TargetMachine &TM = getTargetMachine();
368 // Darwin passes everything on 4 byte boundary.
369 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
375 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
378 case PPCISD::FSEL: return "PPCISD::FSEL";
379 case PPCISD::FCFID: return "PPCISD::FCFID";
380 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
381 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
382 case PPCISD::STFIWX: return "PPCISD::STFIWX";
383 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
384 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
385 case PPCISD::VPERM: return "PPCISD::VPERM";
386 case PPCISD::Hi: return "PPCISD::Hi";
387 case PPCISD::Lo: return "PPCISD::Lo";
388 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
389 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
390 case PPCISD::SRL: return "PPCISD::SRL";
391 case PPCISD::SRA: return "PPCISD::SRA";
392 case PPCISD::SHL: return "PPCISD::SHL";
393 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
394 case PPCISD::STD_32: return "PPCISD::STD_32";
395 case PPCISD::CALL_ELF: return "PPCISD::CALL_ELF";
396 case PPCISD::CALL_Macho: return "PPCISD::CALL_Macho";
397 case PPCISD::MTCTR: return "PPCISD::MTCTR";
398 case PPCISD::BCTRL_Macho: return "PPCISD::BCTRL_Macho";
399 case PPCISD::BCTRL_ELF: return "PPCISD::BCTRL_ELF";
400 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
401 case PPCISD::MFCR: return "PPCISD::MFCR";
402 case PPCISD::VCMP: return "PPCISD::VCMP";
403 case PPCISD::VCMPo: return "PPCISD::VCMPo";
404 case PPCISD::LBRX: return "PPCISD::LBRX";
405 case PPCISD::STBRX: return "PPCISD::STBRX";
406 case PPCISD::LARX: return "PPCISD::LARX";
407 case PPCISD::STCX: return "PPCISD::STCX";
408 case PPCISD::CMP_UNRESERVE: return "PPCISD::CMP_UNRESERVE";
409 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
410 case PPCISD::MFFS: return "PPCISD::MFFS";
411 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
412 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
413 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
414 case PPCISD::MTFSF: return "PPCISD::MTFSF";
420 PPCTargetLowering::getSetCCResultType(const SDOperand &) const {
425 //===----------------------------------------------------------------------===//
426 // Node matching predicates, for use by the tblgen matching code.
427 //===----------------------------------------------------------------------===//
429 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
430 static bool isFloatingPointZero(SDOperand Op) {
431 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
432 return CFP->getValueAPF().isZero();
433 else if (ISD::isEXTLoad(Op.Val) || ISD::isNON_EXTLoad(Op.Val)) {
434 // Maybe this has already been legalized into the constant pool?
435 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
436 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
437 return CFP->getValueAPF().isZero();
442 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
443 /// true if Op is undef or if it matches the specified value.
444 static bool isConstantOrUndef(SDOperand Op, unsigned Val) {
445 return Op.getOpcode() == ISD::UNDEF ||
446 cast<ConstantSDNode>(Op)->getValue() == Val;
449 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
450 /// VPKUHUM instruction.
451 bool PPC::isVPKUHUMShuffleMask(SDNode *N, bool isUnary) {
453 for (unsigned i = 0; i != 16; ++i)
454 if (!isConstantOrUndef(N->getOperand(i), i*2+1))
457 for (unsigned i = 0; i != 8; ++i)
458 if (!isConstantOrUndef(N->getOperand(i), i*2+1) ||
459 !isConstantOrUndef(N->getOperand(i+8), i*2+1))
465 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
466 /// VPKUWUM instruction.
467 bool PPC::isVPKUWUMShuffleMask(SDNode *N, bool isUnary) {
469 for (unsigned i = 0; i != 16; i += 2)
470 if (!isConstantOrUndef(N->getOperand(i ), i*2+2) ||
471 !isConstantOrUndef(N->getOperand(i+1), i*2+3))
474 for (unsigned i = 0; i != 8; i += 2)
475 if (!isConstantOrUndef(N->getOperand(i ), i*2+2) ||
476 !isConstantOrUndef(N->getOperand(i+1), i*2+3) ||
477 !isConstantOrUndef(N->getOperand(i+8), i*2+2) ||
478 !isConstantOrUndef(N->getOperand(i+9), i*2+3))
484 /// isVMerge - Common function, used to match vmrg* shuffles.
486 static bool isVMerge(SDNode *N, unsigned UnitSize,
487 unsigned LHSStart, unsigned RHSStart) {
488 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
489 N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
490 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
491 "Unsupported merge size!");
493 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
494 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
495 if (!isConstantOrUndef(N->getOperand(i*UnitSize*2+j),
496 LHSStart+j+i*UnitSize) ||
497 !isConstantOrUndef(N->getOperand(i*UnitSize*2+UnitSize+j),
498 RHSStart+j+i*UnitSize))
504 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
505 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
506 bool PPC::isVMRGLShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
508 return isVMerge(N, UnitSize, 8, 24);
509 return isVMerge(N, UnitSize, 8, 8);
512 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
513 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
514 bool PPC::isVMRGHShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
516 return isVMerge(N, UnitSize, 0, 16);
517 return isVMerge(N, UnitSize, 0, 0);
521 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
522 /// amount, otherwise return -1.
523 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
524 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
525 N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
526 // Find the first non-undef value in the shuffle mask.
528 for (i = 0; i != 16 && N->getOperand(i).getOpcode() == ISD::UNDEF; ++i)
531 if (i == 16) return -1; // all undef.
533 // Otherwise, check to see if the rest of the elements are consequtively
534 // numbered from this value.
535 unsigned ShiftAmt = cast<ConstantSDNode>(N->getOperand(i))->getValue();
536 if (ShiftAmt < i) return -1;
540 // Check the rest of the elements to see if they are consequtive.
541 for (++i; i != 16; ++i)
542 if (!isConstantOrUndef(N->getOperand(i), ShiftAmt+i))
545 // Check the rest of the elements to see if they are consequtive.
546 for (++i; i != 16; ++i)
547 if (!isConstantOrUndef(N->getOperand(i), (ShiftAmt+i) & 15))
554 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
555 /// specifies a splat of a single element that is suitable for input to
556 /// VSPLTB/VSPLTH/VSPLTW.
557 bool PPC::isSplatShuffleMask(SDNode *N, unsigned EltSize) {
558 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
559 N->getNumOperands() == 16 &&
560 (EltSize == 1 || EltSize == 2 || EltSize == 4));
562 // This is a splat operation if each element of the permute is the same, and
563 // if the value doesn't reference the second vector.
564 unsigned ElementBase = 0;
565 SDOperand Elt = N->getOperand(0);
566 if (ConstantSDNode *EltV = dyn_cast<ConstantSDNode>(Elt))
567 ElementBase = EltV->getValue();
569 return false; // FIXME: Handle UNDEF elements too!
571 if (cast<ConstantSDNode>(Elt)->getValue() >= 16)
574 // Check that they are consequtive.
575 for (unsigned i = 1; i != EltSize; ++i) {
576 if (!isa<ConstantSDNode>(N->getOperand(i)) ||
577 cast<ConstantSDNode>(N->getOperand(i))->getValue() != i+ElementBase)
581 assert(isa<ConstantSDNode>(Elt) && "Invalid VECTOR_SHUFFLE mask!");
582 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
583 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
584 assert(isa<ConstantSDNode>(N->getOperand(i)) &&
585 "Invalid VECTOR_SHUFFLE mask!");
586 for (unsigned j = 0; j != EltSize; ++j)
587 if (N->getOperand(i+j) != N->getOperand(j))
594 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
596 bool PPC::isAllNegativeZeroVector(SDNode *N) {
597 assert(N->getOpcode() == ISD::BUILD_VECTOR);
598 if (PPC::isSplatShuffleMask(N, N->getNumOperands()))
599 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N))
600 return CFP->getValueAPF().isNegZero();
604 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
605 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
606 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
607 assert(isSplatShuffleMask(N, EltSize));
608 return cast<ConstantSDNode>(N->getOperand(0))->getValue() / EltSize;
611 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
612 /// by using a vspltis[bhw] instruction of the specified element size, return
613 /// the constant being splatted. The ByteSize field indicates the number of
614 /// bytes of each element [124] -> [bhw].
615 SDOperand PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
616 SDOperand OpVal(0, 0);
618 // If ByteSize of the splat is bigger than the element size of the
619 // build_vector, then we have a case where we are checking for a splat where
620 // multiple elements of the buildvector are folded together into a single
621 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
622 unsigned EltSize = 16/N->getNumOperands();
623 if (EltSize < ByteSize) {
624 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
625 SDOperand UniquedVals[4];
626 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
628 // See if all of the elements in the buildvector agree across.
629 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
630 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
631 // If the element isn't a constant, bail fully out.
632 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDOperand();
635 if (UniquedVals[i&(Multiple-1)].Val == 0)
636 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
637 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
638 return SDOperand(); // no match.
641 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
642 // either constant or undef values that are identical for each chunk. See
643 // if these chunks can form into a larger vspltis*.
645 // Check to see if all of the leading entries are either 0 or -1. If
646 // neither, then this won't fit into the immediate field.
647 bool LeadingZero = true;
648 bool LeadingOnes = true;
649 for (unsigned i = 0; i != Multiple-1; ++i) {
650 if (UniquedVals[i].Val == 0) continue; // Must have been undefs.
652 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
653 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
655 // Finally, check the least significant entry.
657 if (UniquedVals[Multiple-1].Val == 0)
658 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
659 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getValue();
661 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
664 if (UniquedVals[Multiple-1].Val == 0)
665 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
666 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSignExtended();
667 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
668 return DAG.getTargetConstant(Val, MVT::i32);
674 // Check to see if this buildvec has a single non-undef value in its elements.
675 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
676 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
678 OpVal = N->getOperand(i);
679 else if (OpVal != N->getOperand(i))
683 if (OpVal.Val == 0) return SDOperand(); // All UNDEF: use implicit def.
685 unsigned ValSizeInBytes = 0;
687 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
688 Value = CN->getValue();
689 ValSizeInBytes = MVT::getSizeInBits(CN->getValueType(0))/8;
690 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
691 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
692 Value = FloatToBits(CN->getValueAPF().convertToFloat());
696 // If the splat value is larger than the element value, then we can never do
697 // this splat. The only case that we could fit the replicated bits into our
698 // immediate field for would be zero, and we prefer to use vxor for it.
699 if (ValSizeInBytes < ByteSize) return SDOperand();
701 // If the element value is larger than the splat value, cut it in half and
702 // check to see if the two halves are equal. Continue doing this until we
703 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
704 while (ValSizeInBytes > ByteSize) {
705 ValSizeInBytes >>= 1;
707 // If the top half equals the bottom half, we're still ok.
708 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
709 (Value & ((1 << (8*ValSizeInBytes))-1)))
713 // Properly sign extend the value.
714 int ShAmt = (4-ByteSize)*8;
715 int MaskVal = ((int)Value << ShAmt) >> ShAmt;
717 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
718 if (MaskVal == 0) return SDOperand();
720 // Finally, if this value fits in a 5 bit sext field, return it
721 if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
722 return DAG.getTargetConstant(MaskVal, MVT::i32);
726 //===----------------------------------------------------------------------===//
727 // Addressing Mode Selection
728 //===----------------------------------------------------------------------===//
730 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
731 /// or 64-bit immediate, and if the value can be accurately represented as a
732 /// sign extension from a 16-bit value. If so, this returns true and the
734 static bool isIntS16Immediate(SDNode *N, short &Imm) {
735 if (N->getOpcode() != ISD::Constant)
738 Imm = (short)cast<ConstantSDNode>(N)->getValue();
739 if (N->getValueType(0) == MVT::i32)
740 return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
742 return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
744 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
745 return isIntS16Immediate(Op.Val, Imm);
749 /// SelectAddressRegReg - Given the specified addressed, check to see if it
750 /// can be represented as an indexed [r+r] operation. Returns false if it
751 /// can be more efficiently represented with [r+imm].
752 bool PPCTargetLowering::SelectAddressRegReg(SDOperand N, SDOperand &Base,
756 if (N.getOpcode() == ISD::ADD) {
757 if (isIntS16Immediate(N.getOperand(1), imm))
759 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
762 Base = N.getOperand(0);
763 Index = N.getOperand(1);
765 } else if (N.getOpcode() == ISD::OR) {
766 if (isIntS16Immediate(N.getOperand(1), imm))
767 return false; // r+i can fold it if we can.
769 // If this is an or of disjoint bitfields, we can codegen this as an add
770 // (for better address arithmetic) if the LHS and RHS of the OR are provably
772 APInt LHSKnownZero, LHSKnownOne;
773 APInt RHSKnownZero, RHSKnownOne;
774 DAG.ComputeMaskedBits(N.getOperand(0),
775 APInt::getAllOnesValue(N.getOperand(0)
776 .getValueSizeInBits()),
777 LHSKnownZero, LHSKnownOne);
779 if (LHSKnownZero.getBoolValue()) {
780 DAG.ComputeMaskedBits(N.getOperand(1),
781 APInt::getAllOnesValue(N.getOperand(1)
782 .getValueSizeInBits()),
783 RHSKnownZero, RHSKnownOne);
784 // If all of the bits are known zero on the LHS or RHS, the add won't
786 if (~(LHSKnownZero | RHSKnownZero) == 0) {
787 Base = N.getOperand(0);
788 Index = N.getOperand(1);
797 /// Returns true if the address N can be represented by a base register plus
798 /// a signed 16-bit displacement [r+imm], and if it is not better
799 /// represented as reg+reg.
800 bool PPCTargetLowering::SelectAddressRegImm(SDOperand N, SDOperand &Disp,
801 SDOperand &Base, SelectionDAG &DAG){
802 // If this can be more profitably realized as r+r, fail.
803 if (SelectAddressRegReg(N, Disp, Base, DAG))
806 if (N.getOpcode() == ISD::ADD) {
808 if (isIntS16Immediate(N.getOperand(1), imm)) {
809 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
810 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
811 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
813 Base = N.getOperand(0);
815 return true; // [r+i]
816 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
817 // Match LOAD (ADD (X, Lo(G))).
818 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
819 && "Cannot handle constant offsets yet!");
820 Disp = N.getOperand(1).getOperand(0); // The global address.
821 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
822 Disp.getOpcode() == ISD::TargetConstantPool ||
823 Disp.getOpcode() == ISD::TargetJumpTable);
824 Base = N.getOperand(0);
825 return true; // [&g+r]
827 } else if (N.getOpcode() == ISD::OR) {
829 if (isIntS16Immediate(N.getOperand(1), imm)) {
830 // If this is an or of disjoint bitfields, we can codegen this as an add
831 // (for better address arithmetic) if the LHS and RHS of the OR are
832 // provably disjoint.
833 APInt LHSKnownZero, LHSKnownOne;
834 DAG.ComputeMaskedBits(N.getOperand(0),
835 APInt::getAllOnesValue(N.getOperand(0)
836 .getValueSizeInBits()),
837 LHSKnownZero, LHSKnownOne);
839 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
840 // If all of the bits are known zero on the LHS or RHS, the add won't
842 Base = N.getOperand(0);
843 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
847 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
848 // Loading from a constant address.
850 // If this address fits entirely in a 16-bit sext immediate field, codegen
853 if (isIntS16Immediate(CN, Imm)) {
854 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
855 Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
859 // Handle 32-bit sext immediates with LIS + addr mode.
860 if (CN->getValueType(0) == MVT::i32 ||
861 (int64_t)CN->getValue() == (int)CN->getValue()) {
862 int Addr = (int)CN->getValue();
864 // Otherwise, break this down into an LIS + disp.
865 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
867 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
868 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
869 Base = SDOperand(DAG.getTargetNode(Opc, CN->getValueType(0), Base), 0);
874 Disp = DAG.getTargetConstant(0, getPointerTy());
875 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
876 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
879 return true; // [r+0]
882 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
883 /// represented as an indexed [r+r] operation.
884 bool PPCTargetLowering::SelectAddressRegRegOnly(SDOperand N, SDOperand &Base,
887 // Check to see if we can easily represent this as an [r+r] address. This
888 // will fail if it thinks that the address is more profitably represented as
889 // reg+imm, e.g. where imm = 0.
890 if (SelectAddressRegReg(N, Base, Index, DAG))
893 // If the operand is an addition, always emit this as [r+r], since this is
894 // better (for code size, and execution, as the memop does the add for free)
895 // than emitting an explicit add.
896 if (N.getOpcode() == ISD::ADD) {
897 Base = N.getOperand(0);
898 Index = N.getOperand(1);
902 // Otherwise, do it the hard way, using R0 as the base register.
903 Base = DAG.getRegister(PPC::R0, N.getValueType());
908 /// SelectAddressRegImmShift - Returns true if the address N can be
909 /// represented by a base register plus a signed 14-bit displacement
910 /// [r+imm*4]. Suitable for use by STD and friends.
911 bool PPCTargetLowering::SelectAddressRegImmShift(SDOperand N, SDOperand &Disp,
914 // If this can be more profitably realized as r+r, fail.
915 if (SelectAddressRegReg(N, Disp, Base, DAG))
918 if (N.getOpcode() == ISD::ADD) {
920 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
921 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
922 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
923 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
925 Base = N.getOperand(0);
927 return true; // [r+i]
928 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
929 // Match LOAD (ADD (X, Lo(G))).
930 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
931 && "Cannot handle constant offsets yet!");
932 Disp = N.getOperand(1).getOperand(0); // The global address.
933 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
934 Disp.getOpcode() == ISD::TargetConstantPool ||
935 Disp.getOpcode() == ISD::TargetJumpTable);
936 Base = N.getOperand(0);
937 return true; // [&g+r]
939 } else if (N.getOpcode() == ISD::OR) {
941 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
942 // If this is an or of disjoint bitfields, we can codegen this as an add
943 // (for better address arithmetic) if the LHS and RHS of the OR are
944 // provably disjoint.
945 APInt LHSKnownZero, LHSKnownOne;
946 DAG.ComputeMaskedBits(N.getOperand(0),
947 APInt::getAllOnesValue(N.getOperand(0)
948 .getValueSizeInBits()),
949 LHSKnownZero, LHSKnownOne);
950 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
951 // If all of the bits are known zero on the LHS or RHS, the add won't
953 Base = N.getOperand(0);
954 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
958 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
959 // Loading from a constant address. Verify low two bits are clear.
960 if ((CN->getValue() & 3) == 0) {
961 // If this address fits entirely in a 14-bit sext immediate field, codegen
964 if (isIntS16Immediate(CN, Imm)) {
965 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
966 Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
970 // Fold the low-part of 32-bit absolute addresses into addr mode.
971 if (CN->getValueType(0) == MVT::i32 ||
972 (int64_t)CN->getValue() == (int)CN->getValue()) {
973 int Addr = (int)CN->getValue();
975 // Otherwise, break this down into an LIS + disp.
976 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
978 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
979 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
980 Base = SDOperand(DAG.getTargetNode(Opc, CN->getValueType(0), Base), 0);
986 Disp = DAG.getTargetConstant(0, getPointerTy());
987 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
988 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
991 return true; // [r+0]
995 /// getPreIndexedAddressParts - returns true by value, base pointer and
996 /// offset pointer and addressing mode by reference if the node's address
997 /// can be legally represented as pre-indexed load / store address.
998 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
1000 ISD::MemIndexedMode &AM,
1001 SelectionDAG &DAG) {
1002 // Disabled by default for now.
1003 if (!EnablePPCPreinc) return false;
1007 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1008 Ptr = LD->getBasePtr();
1009 VT = LD->getMemoryVT();
1011 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1013 Ptr = ST->getBasePtr();
1014 VT = ST->getMemoryVT();
1018 // PowerPC doesn't have preinc load/store instructions for vectors.
1019 if (MVT::isVector(VT))
1022 // TODO: Check reg+reg first.
1024 // LDU/STU use reg+imm*4, others use reg+imm.
1025 if (VT != MVT::i64) {
1027 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1031 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1035 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1036 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1037 // sext i32 to i64 when addr mode is r+i.
1038 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1039 LD->getExtensionType() == ISD::SEXTLOAD &&
1040 isa<ConstantSDNode>(Offset))
1048 //===----------------------------------------------------------------------===//
1049 // LowerOperation implementation
1050 //===----------------------------------------------------------------------===//
1052 SDOperand PPCTargetLowering::LowerConstantPool(SDOperand Op,
1053 SelectionDAG &DAG) {
1054 MVT::ValueType PtrVT = Op.getValueType();
1055 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1056 Constant *C = CP->getConstVal();
1057 SDOperand CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
1058 SDOperand Zero = DAG.getConstant(0, PtrVT);
1060 const TargetMachine &TM = DAG.getTarget();
1062 SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, CPI, Zero);
1063 SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, CPI, Zero);
1065 // If this is a non-darwin platform, we don't support non-static relo models
1067 if (TM.getRelocationModel() == Reloc::Static ||
1068 !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1069 // Generate non-pic code that has direct accesses to the constant pool.
1070 // The address of the global is just (hi(&g)+lo(&g)).
1071 return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1074 if (TM.getRelocationModel() == Reloc::PIC_) {
1075 // With PIC, the first instruction is actually "GR+hi(&G)".
1076 Hi = DAG.getNode(ISD::ADD, PtrVT,
1077 DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
1080 Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1084 SDOperand PPCTargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
1085 MVT::ValueType PtrVT = Op.getValueType();
1086 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1087 SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1088 SDOperand Zero = DAG.getConstant(0, PtrVT);
1090 const TargetMachine &TM = DAG.getTarget();
1092 SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, JTI, Zero);
1093 SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, JTI, Zero);
1095 // If this is a non-darwin platform, we don't support non-static relo models
1097 if (TM.getRelocationModel() == Reloc::Static ||
1098 !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1099 // Generate non-pic code that has direct accesses to the constant pool.
1100 // The address of the global is just (hi(&g)+lo(&g)).
1101 return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1104 if (TM.getRelocationModel() == Reloc::PIC_) {
1105 // With PIC, the first instruction is actually "GR+hi(&G)".
1106 Hi = DAG.getNode(ISD::ADD, PtrVT,
1107 DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
1110 Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1114 SDOperand PPCTargetLowering::LowerGlobalTLSAddress(SDOperand Op,
1115 SelectionDAG &DAG) {
1116 assert(0 && "TLS not implemented for PPC.");
1117 return SDOperand(); // Not reached
1120 SDOperand PPCTargetLowering::LowerGlobalAddress(SDOperand Op,
1121 SelectionDAG &DAG) {
1122 MVT::ValueType PtrVT = Op.getValueType();
1123 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1124 GlobalValue *GV = GSDN->getGlobal();
1125 SDOperand GA = DAG.getTargetGlobalAddress(GV, PtrVT, GSDN->getOffset());
1126 // If it's a debug information descriptor, don't mess with it.
1127 if (DAG.isVerifiedDebugInfoDesc(Op))
1129 SDOperand Zero = DAG.getConstant(0, PtrVT);
1131 const TargetMachine &TM = DAG.getTarget();
1133 SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, GA, Zero);
1134 SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, GA, Zero);
1136 // If this is a non-darwin platform, we don't support non-static relo models
1138 if (TM.getRelocationModel() == Reloc::Static ||
1139 !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1140 // Generate non-pic code that has direct accesses to globals.
1141 // The address of the global is just (hi(&g)+lo(&g)).
1142 return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1145 if (TM.getRelocationModel() == Reloc::PIC_) {
1146 // With PIC, the first instruction is actually "GR+hi(&G)".
1147 Hi = DAG.getNode(ISD::ADD, PtrVT,
1148 DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
1151 Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
1153 if (!TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV))
1156 // If the global is weak or external, we have to go through the lazy
1158 return DAG.getLoad(PtrVT, DAG.getEntryNode(), Lo, NULL, 0);
1161 SDOperand PPCTargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
1162 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1164 // If we're comparing for equality to zero, expose the fact that this is
1165 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1166 // fold the new nodes.
1167 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1168 if (C->isNullValue() && CC == ISD::SETEQ) {
1169 MVT::ValueType VT = Op.getOperand(0).getValueType();
1170 SDOperand Zext = Op.getOperand(0);
1171 if (VT < MVT::i32) {
1173 Zext = DAG.getNode(ISD::ZERO_EXTEND, VT, Op.getOperand(0));
1175 unsigned Log2b = Log2_32(MVT::getSizeInBits(VT));
1176 SDOperand Clz = DAG.getNode(ISD::CTLZ, VT, Zext);
1177 SDOperand Scc = DAG.getNode(ISD::SRL, VT, Clz,
1178 DAG.getConstant(Log2b, MVT::i32));
1179 return DAG.getNode(ISD::TRUNCATE, MVT::i32, Scc);
1181 // Leave comparisons against 0 and -1 alone for now, since they're usually
1182 // optimized. FIXME: revisit this when we can custom lower all setcc
1184 if (C->isAllOnesValue() || C->isNullValue())
1188 // If we have an integer seteq/setne, turn it into a compare against zero
1189 // by xor'ing the rhs with the lhs, which is faster than setting a
1190 // condition register, reading it back out, and masking the correct bit. The
1191 // normal approach here uses sub to do this instead of xor. Using xor exposes
1192 // the result to other bit-twiddling opportunities.
1193 MVT::ValueType LHSVT = Op.getOperand(0).getValueType();
1194 if (MVT::isInteger(LHSVT) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1195 MVT::ValueType VT = Op.getValueType();
1196 SDOperand Sub = DAG.getNode(ISD::XOR, LHSVT, Op.getOperand(0),
1198 return DAG.getSetCC(VT, Sub, DAG.getConstant(0, LHSVT), CC);
1203 SDOperand PPCTargetLowering::LowerVAARG(SDOperand Op, SelectionDAG &DAG,
1204 int VarArgsFrameIndex,
1205 int VarArgsStackOffset,
1206 unsigned VarArgsNumGPR,
1207 unsigned VarArgsNumFPR,
1208 const PPCSubtarget &Subtarget) {
1210 assert(0 && "VAARG in ELF32 ABI not implemented yet!");
1211 return SDOperand(); // Not reached
1214 SDOperand PPCTargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG,
1215 int VarArgsFrameIndex,
1216 int VarArgsStackOffset,
1217 unsigned VarArgsNumGPR,
1218 unsigned VarArgsNumFPR,
1219 const PPCSubtarget &Subtarget) {
1221 if (Subtarget.isMachoABI()) {
1222 // vastart just stores the address of the VarArgsFrameIndex slot into the
1223 // memory location argument.
1224 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1225 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1226 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1227 return DAG.getStore(Op.getOperand(0), FR, Op.getOperand(1), SV, 0);
1230 // For ELF 32 ABI we follow the layout of the va_list struct.
1231 // We suppose the given va_list is already allocated.
1234 // char gpr; /* index into the array of 8 GPRs
1235 // * stored in the register save area
1236 // * gpr=0 corresponds to r3,
1237 // * gpr=1 to r4, etc.
1239 // char fpr; /* index into the array of 8 FPRs
1240 // * stored in the register save area
1241 // * fpr=0 corresponds to f1,
1242 // * fpr=1 to f2, etc.
1244 // char *overflow_arg_area;
1245 // /* location on stack that holds
1246 // * the next overflow argument
1248 // char *reg_save_area;
1249 // /* where r3:r10 and f1:f8 (if saved)
1255 SDOperand ArgGPR = DAG.getConstant(VarArgsNumGPR, MVT::i8);
1256 SDOperand ArgFPR = DAG.getConstant(VarArgsNumFPR, MVT::i8);
1259 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1261 SDOperand StackOffsetFI = DAG.getFrameIndex(VarArgsStackOffset, PtrVT);
1262 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1264 uint64_t FrameOffset = MVT::getSizeInBits(PtrVT)/8;
1265 SDOperand ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1267 uint64_t StackOffset = MVT::getSizeInBits(PtrVT)/8 - 1;
1268 SDOperand ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1270 uint64_t FPROffset = 1;
1271 SDOperand ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1273 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1275 // Store first byte : number of int regs
1276 SDOperand firstStore = DAG.getStore(Op.getOperand(0), ArgGPR,
1277 Op.getOperand(1), SV, 0);
1278 uint64_t nextOffset = FPROffset;
1279 SDOperand nextPtr = DAG.getNode(ISD::ADD, PtrVT, Op.getOperand(1),
1282 // Store second byte : number of float regs
1283 SDOperand secondStore =
1284 DAG.getStore(firstStore, ArgFPR, nextPtr, SV, nextOffset);
1285 nextOffset += StackOffset;
1286 nextPtr = DAG.getNode(ISD::ADD, PtrVT, nextPtr, ConstStackOffset);
1288 // Store second word : arguments given on stack
1289 SDOperand thirdStore =
1290 DAG.getStore(secondStore, StackOffsetFI, nextPtr, SV, nextOffset);
1291 nextOffset += FrameOffset;
1292 nextPtr = DAG.getNode(ISD::ADD, PtrVT, nextPtr, ConstFrameOffset);
1294 // Store third word : arguments given in registers
1295 return DAG.getStore(thirdStore, FR, nextPtr, SV, nextOffset);
1299 #include "PPCGenCallingConv.inc"
1301 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1302 /// depending on which subtarget is selected.
1303 static const unsigned *GetFPR(const PPCSubtarget &Subtarget) {
1304 if (Subtarget.isMachoABI()) {
1305 static const unsigned FPR[] = {
1306 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1307 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1313 static const unsigned FPR[] = {
1314 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1321 PPCTargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op,
1323 int &VarArgsFrameIndex,
1324 int &VarArgsStackOffset,
1325 unsigned &VarArgsNumGPR,
1326 unsigned &VarArgsNumFPR,
1327 const PPCSubtarget &Subtarget) {
1328 // TODO: add description of PPC stack frame format, or at least some docs.
1330 MachineFunction &MF = DAG.getMachineFunction();
1331 MachineFrameInfo *MFI = MF.getFrameInfo();
1332 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1333 SmallVector<SDOperand, 8> ArgValues;
1334 SDOperand Root = Op.getOperand(0);
1335 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1337 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1338 bool isPPC64 = PtrVT == MVT::i64;
1339 bool isMachoABI = Subtarget.isMachoABI();
1340 bool isELF32_ABI = Subtarget.isELF32_ABI();
1341 unsigned PtrByteSize = isPPC64 ? 8 : 4;
1343 unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1345 static const unsigned GPR_32[] = { // 32-bit registers.
1346 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1347 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1349 static const unsigned GPR_64[] = { // 64-bit registers.
1350 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1351 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1354 static const unsigned *FPR = GetFPR(Subtarget);
1356 static const unsigned VR[] = {
1357 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1358 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1361 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
1362 const unsigned Num_FPR_Regs = isMachoABI ? 13 : 8;
1363 const unsigned Num_VR_Regs = array_lengthof( VR);
1365 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1367 const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1369 // In 32-bit non-varargs functions, the stack space for vectors is after the
1370 // stack space for non-vectors. We do not use this space unless we have
1371 // too many vectors to fit in registers, something that only occurs in
1372 // constructed examples:), but we have to walk the arglist to figure
1373 // that out...for the pathological case, compute VecArgOffset as the
1374 // start of the vector parameter area. Computing VecArgOffset is the
1375 // entire point of the following loop.
1376 // Altivec is not mentioned in the ppc32 Elf Supplement, so I'm not trying
1377 // to handle Elf here.
1378 unsigned VecArgOffset = ArgOffset;
1379 if (!isVarArg && !isPPC64) {
1380 for (unsigned ArgNo = 0, e = Op.Val->getNumValues()-1; ArgNo != e;
1382 MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
1383 unsigned ObjSize = MVT::getSizeInBits(ObjectVT)/8;
1384 ISD::ArgFlagsTy Flags =
1385 cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1387 if (Flags.isByVal()) {
1388 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
1389 ObjSize = Flags.getByValSize();
1391 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1392 VecArgOffset += ArgSize;
1397 default: assert(0 && "Unhandled argument type!");
1400 VecArgOffset += isPPC64 ? 8 : 4;
1402 case MVT::i64: // PPC64
1410 // Nothing to do, we're only looking at Nonvector args here.
1415 // We've found where the vector parameter area in memory is. Skip the
1416 // first 12 parameters; these don't use that memory.
1417 VecArgOffset = ((VecArgOffset+15)/16)*16;
1418 VecArgOffset += 12*16;
1420 // Add DAG nodes to load the arguments or copy them out of registers. On
1421 // entry to a function on PPC, the arguments start after the linkage area,
1422 // although the first ones are often in registers.
1424 // In the ELF 32 ABI, GPRs and stack are double word align: an argument
1425 // represented with two words (long long or double) must be copied to an
1426 // even GPR_idx value or to an even ArgOffset value.
1428 SmallVector<SDOperand, 8> MemOps;
1430 for (unsigned ArgNo = 0, e = Op.Val->getNumValues()-1; ArgNo != e; ++ArgNo) {
1432 bool needsLoad = false;
1433 MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
1434 unsigned ObjSize = MVT::getSizeInBits(ObjectVT)/8;
1435 unsigned ArgSize = ObjSize;
1436 ISD::ArgFlagsTy Flags =
1437 cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1438 // See if next argument requires stack alignment in ELF
1439 bool Align = Flags.isSplit();
1441 unsigned CurArgOffset = ArgOffset;
1443 // FIXME alignment for ELF may not be right
1444 // FIXME the codegen can be much improved in some cases.
1445 // We do not have to keep everything in memory.
1446 if (Flags.isByVal()) {
1447 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
1448 ObjSize = Flags.getByValSize();
1449 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1450 // Double word align in ELF
1451 if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1452 // Objects of size 1 and 2 are right justified, everything else is
1453 // left justified. This means the memory address is adjusted forwards.
1454 if (ObjSize==1 || ObjSize==2) {
1455 CurArgOffset = CurArgOffset + (4 - ObjSize);
1457 // The value of the object is its address.
1458 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset);
1459 SDOperand FIN = DAG.getFrameIndex(FI, PtrVT);
1460 ArgValues.push_back(FIN);
1461 if (ObjSize==1 || ObjSize==2) {
1462 if (GPR_idx != Num_GPR_Regs) {
1463 unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1464 RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1465 SDOperand Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
1466 SDOperand Store = DAG.getTruncStore(Val.getValue(1), Val, FIN,
1467 NULL, 0, ObjSize==1 ? MVT::i8 : MVT::i16 );
1468 MemOps.push_back(Store);
1470 if (isMachoABI) ArgOffset += PtrByteSize;
1472 ArgOffset += PtrByteSize;
1476 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
1477 // Store whatever pieces of the object are in registers
1478 // to memory. ArgVal will be address of the beginning of
1480 if (GPR_idx != Num_GPR_Regs) {
1481 unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1482 RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1483 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset);
1484 SDOperand FIN = DAG.getFrameIndex(FI, PtrVT);
1485 SDOperand Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
1486 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1487 MemOps.push_back(Store);
1489 if (isMachoABI) ArgOffset += PtrByteSize;
1491 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
1499 default: assert(0 && "Unhandled argument type!");
1502 // Double word align in ELF
1503 if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1505 if (GPR_idx != Num_GPR_Regs) {
1506 unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1507 RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1508 ArgVal = DAG.getCopyFromReg(Root, VReg, MVT::i32);
1512 ArgSize = PtrByteSize;
1514 // Stack align in ELF
1515 if (needsLoad && Align && isELF32_ABI)
1516 ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1517 // All int arguments reserve stack space in Macho ABI.
1518 if (isMachoABI || needsLoad) ArgOffset += PtrByteSize;
1522 case MVT::i64: // PPC64
1523 if (GPR_idx != Num_GPR_Regs) {
1524 unsigned VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
1525 RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1526 ArgVal = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1528 if (ObjectVT == MVT::i32) {
1529 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
1530 // value to MVT::i64 and then truncate to the correct register size.
1532 ArgVal = DAG.getNode(ISD::AssertSext, MVT::i64, ArgVal,
1533 DAG.getValueType(ObjectVT));
1534 else if (Flags.isZExt())
1535 ArgVal = DAG.getNode(ISD::AssertZext, MVT::i64, ArgVal,
1536 DAG.getValueType(ObjectVT));
1538 ArgVal = DAG.getNode(ISD::TRUNCATE, MVT::i32, ArgVal);
1545 // All int arguments reserve stack space in Macho ABI.
1546 if (isMachoABI || needsLoad) ArgOffset += 8;
1551 // Every 4 bytes of argument space consumes one of the GPRs available for
1552 // argument passing.
1553 if (GPR_idx != Num_GPR_Regs && isMachoABI) {
1555 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
1558 if (FPR_idx != Num_FPR_Regs) {
1560 if (ObjectVT == MVT::f32)
1561 VReg = RegInfo.createVirtualRegister(&PPC::F4RCRegClass);
1563 VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
1564 RegInfo.addLiveIn(FPR[FPR_idx], VReg);
1565 ArgVal = DAG.getCopyFromReg(Root, VReg, ObjectVT);
1571 // Stack align in ELF
1572 if (needsLoad && Align && isELF32_ABI)
1573 ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1574 // All FP arguments reserve stack space in Macho ABI.
1575 if (isMachoABI || needsLoad) ArgOffset += isPPC64 ? 8 : ObjSize;
1581 // Note that vector arguments in registers don't reserve stack space,
1582 // except in varargs functions.
1583 if (VR_idx != Num_VR_Regs) {
1584 unsigned VReg = RegInfo.createVirtualRegister(&PPC::VRRCRegClass);
1585 RegInfo.addLiveIn(VR[VR_idx], VReg);
1586 ArgVal = DAG.getCopyFromReg(Root, VReg, ObjectVT);
1588 while ((ArgOffset % 16) != 0) {
1589 ArgOffset += PtrByteSize;
1590 if (GPR_idx != Num_GPR_Regs)
1594 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs);
1598 if (!isVarArg && !isPPC64) {
1599 // Vectors go after all the nonvectors.
1600 CurArgOffset = VecArgOffset;
1603 // Vectors are aligned.
1604 ArgOffset = ((ArgOffset+15)/16)*16;
1605 CurArgOffset = ArgOffset;
1613 // We need to load the argument to a virtual register if we determined above
1614 // that we ran out of physical registers of the appropriate type.
1616 int FI = MFI->CreateFixedObject(ObjSize,
1617 CurArgOffset + (ArgSize - ObjSize));
1618 SDOperand FIN = DAG.getFrameIndex(FI, PtrVT);
1619 ArgVal = DAG.getLoad(ObjectVT, Root, FIN, NULL, 0);
1622 ArgValues.push_back(ArgVal);
1625 // If the function takes variable number of arguments, make a frame index for
1626 // the start of the first vararg value... for expansion of llvm.va_start.
1631 VarArgsNumGPR = GPR_idx;
1632 VarArgsNumFPR = FPR_idx;
1634 // Make room for Num_GPR_Regs, Num_FPR_Regs and for a possible frame
1636 depth = -(Num_GPR_Regs * MVT::getSizeInBits(PtrVT)/8 +
1637 Num_FPR_Regs * MVT::getSizeInBits(MVT::f64)/8 +
1638 MVT::getSizeInBits(PtrVT)/8);
1640 VarArgsStackOffset = MFI->CreateFixedObject(MVT::getSizeInBits(PtrVT)/8,
1647 VarArgsFrameIndex = MFI->CreateFixedObject(MVT::getSizeInBits(PtrVT)/8,
1649 SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1651 // In ELF 32 ABI, the fixed integer arguments of a variadic function are
1652 // stored to the VarArgsFrameIndex on the stack.
1654 for (GPR_idx = 0; GPR_idx != VarArgsNumGPR; ++GPR_idx) {
1655 SDOperand Val = DAG.getRegister(GPR[GPR_idx], PtrVT);
1656 SDOperand Store = DAG.getStore(Root, Val, FIN, NULL, 0);
1657 MemOps.push_back(Store);
1658 // Increment the address by four for the next argument to store
1659 SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(PtrVT)/8, PtrVT);
1660 FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1664 // If this function is vararg, store any remaining integer argument regs
1665 // to their spots on the stack so that they may be loaded by deferencing the
1666 // result of va_next.
1667 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
1670 VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
1672 VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1674 RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1675 SDOperand Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
1676 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1677 MemOps.push_back(Store);
1678 // Increment the address by four for the next argument to store
1679 SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(PtrVT)/8, PtrVT);
1680 FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1683 // In ELF 32 ABI, the double arguments are stored to the VarArgsFrameIndex
1686 for (FPR_idx = 0; FPR_idx != VarArgsNumFPR; ++FPR_idx) {
1687 SDOperand Val = DAG.getRegister(FPR[FPR_idx], MVT::f64);
1688 SDOperand Store = DAG.getStore(Root, Val, FIN, NULL, 0);
1689 MemOps.push_back(Store);
1690 // Increment the address by eight for the next argument to store
1691 SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(MVT::f64)/8,
1693 FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1696 for (; FPR_idx != Num_FPR_Regs; ++FPR_idx) {
1698 VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
1700 RegInfo.addLiveIn(FPR[FPR_idx], VReg);
1701 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::f64);
1702 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1703 MemOps.push_back(Store);
1704 // Increment the address by eight for the next argument to store
1705 SDOperand PtrOff = DAG.getConstant(MVT::getSizeInBits(MVT::f64)/8,
1707 FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
1712 if (!MemOps.empty())
1713 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,&MemOps[0],MemOps.size());
1715 ArgValues.push_back(Root);
1717 // Return the new list of results.
1718 std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
1719 Op.Val->value_end());
1720 return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
1723 /// isCallCompatibleAddress - Return the immediate to use if the specified
1724 /// 32-bit value is representable in the immediate field of a BxA instruction.
1725 static SDNode *isBLACompatibleAddress(SDOperand Op, SelectionDAG &DAG) {
1726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1729 int Addr = C->getValue();
1730 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
1731 (Addr << 6 >> 6) != Addr)
1732 return 0; // Top 6 bits have to be sext of immediate.
1734 return DAG.getConstant((int)C->getValue() >> 2,
1735 DAG.getTargetLoweringInfo().getPointerTy()).Val;
1738 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1739 /// by "Src" to address "Dst" of size "Size". Alignment information is
1740 /// specified by the specific parameter attribute. The copy will be passed as
1741 /// a byval function parameter.
1742 /// Sometimes what we are copying is the end of a larger object, the part that
1743 /// does not fit in registers.
1745 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1746 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1748 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1749 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(), false,
1753 SDOperand PPCTargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG,
1754 const PPCSubtarget &Subtarget,
1755 TargetMachine &TM) {
1756 SDOperand Chain = Op.getOperand(0);
1757 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1758 SDOperand Callee = Op.getOperand(4);
1759 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1761 bool isMachoABI = Subtarget.isMachoABI();
1762 bool isELF32_ABI = Subtarget.isELF32_ABI();
1764 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1765 bool isPPC64 = PtrVT == MVT::i64;
1766 unsigned PtrByteSize = isPPC64 ? 8 : 4;
1768 // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
1769 // SelectExpr to use to put the arguments in the appropriate registers.
1770 std::vector<SDOperand> args_to_use;
1772 // Count how many bytes are to be pushed on the stack, including the linkage
1773 // area, and parameter passing area. We start with 24/48 bytes, which is
1774 // prereserved space for [SP][CR][LR][3 x unused].
1775 unsigned NumBytes = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1777 // Add up all the space actually used.
1778 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
1779 // they all go in registers, but we must reserve stack space for them for
1780 // possible use by the caller. In varargs or 64-bit calls, parameters are
1781 // assigned stack space in order, with padding so Altivec parameters are
1783 unsigned nAltivecParamsAtEnd = 0;
1784 for (unsigned i = 0; i != NumOps; ++i) {
1785 SDOperand Arg = Op.getOperand(5+2*i);
1786 MVT::ValueType ArgVT = Arg.getValueType();
1787 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
1788 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
1789 if (!isVarArg && !isPPC64) {
1790 // Non-varargs Altivec parameters go after all the non-Altivec parameters;
1791 // do those last so we know how much padding we need.
1792 nAltivecParamsAtEnd++;
1795 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
1796 NumBytes = ((NumBytes+15)/16)*16;
1799 ISD::ArgFlagsTy Flags =
1800 cast<ARG_FLAGSSDNode>(Op.getOperand(5+2*i+1))->getArgFlags();
1801 unsigned ArgSize =MVT::getSizeInBits(Op.getOperand(5+2*i).getValueType())/8;
1802 if (Flags.isByVal())
1803 ArgSize = Flags.getByValSize();
1804 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1805 NumBytes += ArgSize;
1807 // Allow for Altivec parameters at the end, if needed.
1808 if (nAltivecParamsAtEnd) {
1809 NumBytes = ((NumBytes+15)/16)*16;
1810 NumBytes += 16*nAltivecParamsAtEnd;
1813 // The prolog code of the callee may store up to 8 GPR argument registers to
1814 // the stack, allowing va_start to index over them in memory if its varargs.
1815 // Because we cannot tell if this is needed on the caller side, we have to
1816 // conservatively assume that it is needed. As such, make sure we have at
1817 // least enough stack space for the caller to store the 8 GPRs.
1818 NumBytes = std::max(NumBytes,
1819 PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
1821 // Adjust the stack pointer for the new arguments...
1822 // These operations are automatically eliminated by the prolog/epilog pass
1823 Chain = DAG.getCALLSEQ_START(Chain,
1824 DAG.getConstant(NumBytes, PtrVT));
1825 SDOperand CallSeqStart = Chain;
1827 // Set up a copy of the stack pointer for use loading and storing any
1828 // arguments that may not fit in the registers available for argument
1832 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
1834 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
1836 // Figure out which arguments are going to go in registers, and which in
1837 // memory. Also, if this is a vararg function, floating point operations
1838 // must be stored to our stack, and loaded into integer regs as well, if
1839 // any integer regs are available for argument passing.
1840 unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1841 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1843 static const unsigned GPR_32[] = { // 32-bit registers.
1844 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1845 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1847 static const unsigned GPR_64[] = { // 64-bit registers.
1848 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1849 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1851 static const unsigned *FPR = GetFPR(Subtarget);
1853 static const unsigned VR[] = {
1854 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1855 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1857 const unsigned NumGPRs = array_lengthof(GPR_32);
1858 const unsigned NumFPRs = isMachoABI ? 13 : 8;
1859 const unsigned NumVRs = array_lengthof( VR);
1861 const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1863 std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
1864 SmallVector<SDOperand, 8> MemOpChains;
1865 for (unsigned i = 0; i != NumOps; ++i) {
1867 SDOperand Arg = Op.getOperand(5+2*i);
1868 ISD::ArgFlagsTy Flags =
1869 cast<ARG_FLAGSSDNode>(Op.getOperand(5+2*i+1))->getArgFlags();
1870 // See if next argument requires stack alignment in ELF
1871 bool Align = Flags.isSplit();
1873 // PtrOff will be used to store the current argument to the stack if a
1874 // register cannot be found for it.
1877 // Stack align in ELF 32
1878 if (isELF32_ABI && Align)
1879 PtrOff = DAG.getConstant(ArgOffset + ((ArgOffset/4) % 2) * PtrByteSize,
1880 StackPtr.getValueType());
1882 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
1884 PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr, PtrOff);
1886 // On PPC64, promote integers to 64-bit values.
1887 if (isPPC64 && Arg.getValueType() == MVT::i32) {
1888 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
1889 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1890 Arg = DAG.getNode(ExtOp, MVT::i64, Arg);
1893 // FIXME Elf untested, what are alignment rules?
1894 // FIXME memcpy is used way more than necessary. Correctness first.
1895 if (Flags.isByVal()) {
1896 unsigned Size = Flags.getByValSize();
1897 if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
1898 if (Size==1 || Size==2) {
1899 // Very small objects are passed right-justified.
1900 // Everything else is passed left-justified.
1901 MVT::ValueType VT = (Size==1) ? MVT::i8 : MVT::i16;
1902 if (GPR_idx != NumGPRs) {
1903 SDOperand Load = DAG.getExtLoad(ISD::EXTLOAD, PtrVT, Chain, Arg,
1905 MemOpChains.push_back(Load.getValue(1));
1906 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
1908 ArgOffset += PtrByteSize;
1910 SDOperand Const = DAG.getConstant(4 - Size, PtrOff.getValueType());
1911 SDOperand AddPtr = DAG.getNode(ISD::ADD, PtrVT, PtrOff, Const);
1912 SDOperand MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr,
1913 CallSeqStart.Val->getOperand(0),
1915 // This must go outside the CALLSEQ_START..END.
1916 SDOperand NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
1917 CallSeqStart.Val->getOperand(1));
1918 DAG.ReplaceAllUsesWith(CallSeqStart.Val, NewCallSeqStart.Val);
1919 Chain = CallSeqStart = NewCallSeqStart;
1920 ArgOffset += PtrByteSize;
1924 // Copy entire object into memory. There are cases where gcc-generated
1925 // code assumes it is there, even if it could be put entirely into
1926 // registers. (This is not what the doc says.)
1927 SDOperand MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
1928 CallSeqStart.Val->getOperand(0),
1930 // This must go outside the CALLSEQ_START..END.
1931 SDOperand NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
1932 CallSeqStart.Val->getOperand(1));
1933 DAG.ReplaceAllUsesWith(CallSeqStart.Val, NewCallSeqStart.Val);
1934 Chain = CallSeqStart = NewCallSeqStart;
1935 // And copy the pieces of it that fit into registers.
1936 for (unsigned j=0; j<Size; j+=PtrByteSize) {
1937 SDOperand Const = DAG.getConstant(j, PtrOff.getValueType());
1938 SDOperand AddArg = DAG.getNode(ISD::ADD, PtrVT, Arg, Const);
1939 if (GPR_idx != NumGPRs) {
1940 SDOperand Load = DAG.getLoad(PtrVT, Chain, AddArg, NULL, 0);
1941 MemOpChains.push_back(Load.getValue(1));
1942 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
1944 ArgOffset += PtrByteSize;
1946 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
1953 switch (Arg.getValueType()) {
1954 default: assert(0 && "Unexpected ValueType for argument!");
1957 // Double word align in ELF
1958 if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
1959 if (GPR_idx != NumGPRs) {
1960 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
1962 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1965 if (inMem || isMachoABI) {
1966 // Stack align in ELF
1967 if (isELF32_ABI && Align)
1968 ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1970 ArgOffset += PtrByteSize;
1975 if (FPR_idx != NumFPRs) {
1976 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
1979 SDOperand Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1980 MemOpChains.push_back(Store);
1982 // Float varargs are always shadowed in available integer registers
1983 if (GPR_idx != NumGPRs) {
1984 SDOperand Load = DAG.getLoad(PtrVT, Store, PtrOff, NULL, 0);
1985 MemOpChains.push_back(Load.getValue(1));
1986 if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
1989 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
1990 SDOperand ConstFour = DAG.getConstant(4, PtrOff.getValueType());
1991 PtrOff = DAG.getNode(ISD::ADD, PtrVT, PtrOff, ConstFour);
1992 SDOperand Load = DAG.getLoad(PtrVT, Store, PtrOff, NULL, 0);
1993 MemOpChains.push_back(Load.getValue(1));
1994 if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
1998 // If we have any FPRs remaining, we may also have GPRs remaining.
1999 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
2002 if (GPR_idx != NumGPRs)
2004 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
2005 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
2010 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
2013 if (inMem || isMachoABI) {
2014 // Stack align in ELF
2015 if (isELF32_ABI && Align)
2016 ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
2020 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
2028 // These go aligned on the stack, or in the corresponding R registers
2029 // when within range. The Darwin PPC ABI doc claims they also go in
2030 // V registers; in fact gcc does this only for arguments that are
2031 // prototyped, not for those that match the ... We do it for all
2032 // arguments, seems to work.
2033 while (ArgOffset % 16 !=0) {
2034 ArgOffset += PtrByteSize;
2035 if (GPR_idx != NumGPRs)
2038 // We could elide this store in the case where the object fits
2039 // entirely in R registers. Maybe later.
2040 PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr,
2041 DAG.getConstant(ArgOffset, PtrVT));
2042 SDOperand Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
2043 MemOpChains.push_back(Store);
2044 if (VR_idx != NumVRs) {
2045 SDOperand Load = DAG.getLoad(MVT::v4f32, Store, PtrOff, NULL, 0);
2046 MemOpChains.push_back(Load.getValue(1));
2047 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
2050 for (unsigned i=0; i<16; i+=PtrByteSize) {
2051 if (GPR_idx == NumGPRs)
2053 SDOperand Ix = DAG.getNode(ISD::ADD, PtrVT, PtrOff,
2054 DAG.getConstant(i, PtrVT));
2055 SDOperand Load = DAG.getLoad(PtrVT, Store, Ix, NULL, 0);
2056 MemOpChains.push_back(Load.getValue(1));
2057 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2061 // Non-varargs Altivec params generally go in registers, but have
2062 // stack space allocated at the end.
2063 if (VR_idx != NumVRs) {
2064 // Doesn't have GPR space allocated.
2065 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
2066 } else if (nAltivecParamsAtEnd==0) {
2067 // We are emitting Altivec params in order.
2068 PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr,
2069 DAG.getConstant(ArgOffset, PtrVT));
2070 SDOperand Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
2071 MemOpChains.push_back(Store);
2077 // If all Altivec parameters fit in registers, as they usually do,
2078 // they get stack space following the non-Altivec parameters. We
2079 // don't track this here because nobody below needs it.
2080 // If there are more Altivec parameters than fit in registers emit
2082 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
2084 // Offset is aligned; skip 1st 12 params which go in V registers.
2085 ArgOffset = ((ArgOffset+15)/16)*16;
2087 for (unsigned i = 0; i != NumOps; ++i) {
2088 SDOperand Arg = Op.getOperand(5+2*i);
2089 MVT::ValueType ArgType = Arg.getValueType();
2090 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
2091 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
2093 SDOperand PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr,
2094 DAG.getConstant(ArgOffset, PtrVT));
2095 SDOperand Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
2096 MemOpChains.push_back(Store);
2103 if (!MemOpChains.empty())
2104 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2105 &MemOpChains[0], MemOpChains.size());
2107 // Build a sequence of copy-to-reg nodes chained together with token chain
2108 // and flag operands which copy the outgoing args into the appropriate regs.
2110 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2111 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
2113 InFlag = Chain.getValue(1);
2116 // With the ELF 32 ABI, set CR6 to true if this is a vararg call.
2117 if (isVarArg && isELF32_ABI) {
2118 SDOperand SetCR(DAG.getTargetNode(PPC::CRSET, MVT::i32), 0);
2119 Chain = DAG.getCopyToReg(Chain, PPC::CR1EQ, SetCR, InFlag);
2120 InFlag = Chain.getValue(1);
2123 std::vector<MVT::ValueType> NodeTys;
2124 NodeTys.push_back(MVT::Other); // Returns a chain
2125 NodeTys.push_back(MVT::Flag); // Returns a flag for retval copy to use.
2127 SmallVector<SDOperand, 8> Ops;
2128 unsigned CallOpc = isMachoABI? PPCISD::CALL_Macho : PPCISD::CALL_ELF;
2130 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2131 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2132 // node so that legalize doesn't hack it.
2133 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2134 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
2135 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
2136 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
2137 else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
2138 // If this is an absolute destination address, use the munged value.
2139 Callee = SDOperand(Dest, 0);
2141 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
2142 // to do the call, we can't use PPCISD::CALL.
2143 SDOperand MTCTROps[] = {Chain, Callee, InFlag};
2144 Chain = DAG.getNode(PPCISD::MTCTR, NodeTys, MTCTROps, 2+(InFlag.Val!=0));
2145 InFlag = Chain.getValue(1);
2147 // Copy the callee address into R12/X12 on darwin.
2149 unsigned Reg = Callee.getValueType() == MVT::i32 ? PPC::R12 : PPC::X12;
2150 Chain = DAG.getCopyToReg(Chain, Reg, Callee, InFlag);
2151 InFlag = Chain.getValue(1);
2155 NodeTys.push_back(MVT::Other);
2156 NodeTys.push_back(MVT::Flag);
2157 Ops.push_back(Chain);
2158 CallOpc = isMachoABI ? PPCISD::BCTRL_Macho : PPCISD::BCTRL_ELF;
2162 // If this is a direct call, pass the chain and the callee.
2164 Ops.push_back(Chain);
2165 Ops.push_back(Callee);
2168 // Add argument registers to the end of the list so that they are known live
2170 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2171 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2172 RegsToPass[i].second.getValueType()));
2175 Ops.push_back(InFlag);
2176 Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
2177 InFlag = Chain.getValue(1);
2179 Chain = DAG.getCALLSEQ_END(Chain,
2180 DAG.getConstant(NumBytes, PtrVT),
2181 DAG.getConstant(0, PtrVT),
2183 if (Op.Val->getValueType(0) != MVT::Other)
2184 InFlag = Chain.getValue(1);
2186 SmallVector<SDOperand, 16> ResultVals;
2187 SmallVector<CCValAssign, 16> RVLocs;
2188 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
2189 CCState CCInfo(CC, isVarArg, TM, RVLocs);
2190 CCInfo.AnalyzeCallResult(Op.Val, RetCC_PPC);
2192 // Copy all of the result registers out of their specified physreg.
2193 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2194 CCValAssign &VA = RVLocs[i];
2195 MVT::ValueType VT = VA.getValVT();
2196 assert(VA.isRegLoc() && "Can only return in registers!");
2197 Chain = DAG.getCopyFromReg(Chain, VA.getLocReg(), VT, InFlag).getValue(1);
2198 ResultVals.push_back(Chain.getValue(0));
2199 InFlag = Chain.getValue(2);
2202 // If the function returns void, just return the chain.
2206 // Otherwise, merge everything together with a MERGE_VALUES node.
2207 ResultVals.push_back(Chain);
2208 SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
2209 &ResultVals[0], ResultVals.size());
2210 return Res.getValue(Op.ResNo);
2213 SDOperand PPCTargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG,
2214 TargetMachine &TM) {
2215 SmallVector<CCValAssign, 16> RVLocs;
2216 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
2217 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
2218 CCState CCInfo(CC, isVarArg, TM, RVLocs);
2219 CCInfo.AnalyzeReturn(Op.Val, RetCC_PPC);
2221 // If this is the first return lowered for this function, add the regs to the
2222 // liveout set for the function.
2223 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2224 for (unsigned i = 0; i != RVLocs.size(); ++i)
2225 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2228 SDOperand Chain = Op.getOperand(0);
2231 // Copy the result values into the output registers.
2232 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2233 CCValAssign &VA = RVLocs[i];
2234 assert(VA.isRegLoc() && "Can only return in registers!");
2235 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
2236 Flag = Chain.getValue(1);
2240 return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Chain, Flag);
2242 return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Chain);
2245 SDOperand PPCTargetLowering::LowerSTACKRESTORE(SDOperand Op, SelectionDAG &DAG,
2246 const PPCSubtarget &Subtarget) {
2247 // When we pop the dynamic allocation we need to restore the SP link.
2249 // Get the corect type for pointers.
2250 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2252 // Construct the stack pointer operand.
2253 bool IsPPC64 = Subtarget.isPPC64();
2254 unsigned SP = IsPPC64 ? PPC::X1 : PPC::R1;
2255 SDOperand StackPtr = DAG.getRegister(SP, PtrVT);
2257 // Get the operands for the STACKRESTORE.
2258 SDOperand Chain = Op.getOperand(0);
2259 SDOperand SaveSP = Op.getOperand(1);
2261 // Load the old link SP.
2262 SDOperand LoadLinkSP = DAG.getLoad(PtrVT, Chain, StackPtr, NULL, 0);
2264 // Restore the stack pointer.
2265 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), SP, SaveSP);
2267 // Store the old link SP.
2268 return DAG.getStore(Chain, LoadLinkSP, StackPtr, NULL, 0);
2271 SDOperand PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
2273 const PPCSubtarget &Subtarget) {
2274 MachineFunction &MF = DAG.getMachineFunction();
2275 bool IsPPC64 = Subtarget.isPPC64();
2276 bool isMachoABI = Subtarget.isMachoABI();
2278 // Get current frame pointer save index. The users of this index will be
2279 // primarily DYNALLOC instructions.
2280 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2281 int FPSI = FI->getFramePointerSaveIndex();
2283 // If the frame pointer save index hasn't been defined yet.
2285 // Find out what the fix offset of the frame pointer save area.
2286 int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isMachoABI);
2288 // Allocate the frame index for frame pointer save area.
2289 FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
2291 FI->setFramePointerSaveIndex(FPSI);
2295 SDOperand Chain = Op.getOperand(0);
2296 SDOperand Size = Op.getOperand(1);
2298 // Get the corect type for pointers.
2299 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2301 SDOperand NegSize = DAG.getNode(ISD::SUB, PtrVT,
2302 DAG.getConstant(0, PtrVT), Size);
2303 // Construct a node for the frame pointer save index.
2304 SDOperand FPSIdx = DAG.getFrameIndex(FPSI, PtrVT);
2305 // Build a DYNALLOC node.
2306 SDOperand Ops[3] = { Chain, NegSize, FPSIdx };
2307 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
2308 return DAG.getNode(PPCISD::DYNALLOC, VTs, Ops, 3);
2311 SDOperand PPCTargetLowering::LowerAtomicLAS(SDOperand Op, SelectionDAG &DAG) {
2312 MVT::ValueType VT = Op.Val->getValueType(0);
2313 SDOperand Chain = Op.getOperand(0);
2314 SDOperand Ptr = Op.getOperand(1);
2315 SDOperand Incr = Op.getOperand(2);
2317 // Issue a "load and reserve".
2318 std::vector<MVT::ValueType> VTs;
2320 VTs.push_back(MVT::Other);
2322 SDOperand Label = DAG.getConstant(PPCAtomicLabelIndex++, MVT::i32);
2328 SDOperand Load = DAG.getNode(PPCISD::LARX, VTs, Ops, 3);
2329 Chain = Load.getValue(1);
2331 // Compute new value.
2332 SDOperand NewVal = DAG.getNode(ISD::ADD, VT, Load, Incr);
2334 // Issue a "store and check".
2335 SDOperand Ops2[] = {
2341 SDOperand Store = DAG.getNode(PPCISD::STCX, MVT::Other, Ops2, 4);
2342 SDOperand OutOps[] = { Load, Store };
2343 return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other),
2347 SDOperand PPCTargetLowering::LowerAtomicLCS(SDOperand Op, SelectionDAG &DAG) {
2348 MVT::ValueType VT = Op.Val->getValueType(0);
2349 SDOperand Chain = Op.getOperand(0);
2350 SDOperand Ptr = Op.getOperand(1);
2351 SDOperand NewVal = Op.getOperand(2);
2352 SDOperand OldVal = Op.getOperand(3);
2354 // Issue a "load and reserve".
2355 std::vector<MVT::ValueType> VTs;
2357 VTs.push_back(MVT::Other);
2359 SDOperand Label = DAG.getConstant(PPCAtomicLabelIndex++, MVT::i32);
2365 SDOperand Load = DAG.getNode(PPCISD::LARX, VTs, Ops, 3);
2366 Chain = Load.getValue(1);
2368 // Compare and unreserve if not equal.
2369 SDOperand Ops2[] = {
2371 OldVal, // Old value
2372 Load, // Value in memory
2375 Chain = DAG.getNode(PPCISD::CMP_UNRESERVE, MVT::Other, Ops2, 4);
2377 // Issue a "store and check".
2378 SDOperand Ops3[] = {
2384 SDOperand Store = DAG.getNode(PPCISD::STCX, MVT::Other, Ops3, 4);
2385 SDOperand OutOps[] = { Load, Store };
2386 return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other),
2390 SDOperand PPCTargetLowering::LowerAtomicSWAP(SDOperand Op, SelectionDAG &DAG) {
2391 MVT::ValueType VT = Op.Val->getValueType(0);
2392 SDOperand Chain = Op.getOperand(0);
2393 SDOperand Ptr = Op.getOperand(1);
2394 SDOperand NewVal = Op.getOperand(2);
2396 // Issue a "load and reserve".
2397 std::vector<MVT::ValueType> VTs;
2399 VTs.push_back(MVT::Other);
2401 SDOperand Label = DAG.getConstant(PPCAtomicLabelIndex++, MVT::i32);
2407 SDOperand Load = DAG.getNode(PPCISD::LARX, VTs, Ops, 3);
2408 Chain = Load.getValue(1);
2410 // Issue a "store and check".
2411 SDOperand Ops2[] = {
2417 SDOperand Store = DAG.getNode(PPCISD::STCX, MVT::Other, Ops2, 4);
2418 SDOperand OutOps[] = { Load, Store };
2419 return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other),
2423 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
2425 SDOperand PPCTargetLowering::LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) {
2426 // Not FP? Not a fsel.
2427 if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
2428 !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
2431 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2433 // Cannot handle SETEQ/SETNE.
2434 if (CC == ISD::SETEQ || CC == ISD::SETNE) return SDOperand();
2436 MVT::ValueType ResVT = Op.getValueType();
2437 MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
2438 SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2439 SDOperand TV = Op.getOperand(2), FV = Op.getOperand(3);
2441 // If the RHS of the comparison is a 0.0, we don't need to do the
2442 // subtraction at all.
2443 if (isFloatingPointZero(RHS))
2445 default: break; // SETUO etc aren't handled by fsel.
2449 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
2453 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
2454 LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
2455 return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
2459 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
2463 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
2464 LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
2465 return DAG.getNode(PPCISD::FSEL, ResVT,
2466 DAG.getNode(ISD::FNEG, MVT::f64, LHS), TV, FV);
2471 default: break; // SETUO etc aren't handled by fsel.
2475 Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
2476 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
2477 Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2478 return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
2482 Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
2483 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
2484 Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2485 return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
2489 Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
2490 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
2491 Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2492 return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
2496 Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
2497 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
2498 Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
2499 return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
2504 // FIXME: Split this code up when LegalizeDAGTypes lands.
2505 SDOperand PPCTargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
2506 assert(MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
2507 SDOperand Src = Op.getOperand(0);
2508 if (Src.getValueType() == MVT::f32)
2509 Src = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Src);
2512 switch (Op.getValueType()) {
2513 default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
2515 Tmp = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Src);
2518 Tmp = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Src);
2522 // Convert the FP value to an int value through memory.
2523 SDOperand FIPtr = DAG.CreateStackTemporary(MVT::f64);
2525 // Emit a store to the stack slot.
2526 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Tmp, FIPtr, NULL, 0);
2528 // Result is a load from the stack slot. If loading 4 bytes, make sure to
2530 if (Op.getValueType() == MVT::i32)
2531 FIPtr = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr,
2532 DAG.getConstant(4, FIPtr.getValueType()));
2533 return DAG.getLoad(Op.getValueType(), Chain, FIPtr, NULL, 0);
2536 SDOperand PPCTargetLowering::LowerFP_ROUND_INREG(SDOperand Op,
2537 SelectionDAG &DAG) {
2538 assert(Op.getValueType() == MVT::ppcf128);
2539 SDNode *Node = Op.Val;
2540 assert(Node->getOperand(0).getValueType() == MVT::ppcf128);
2541 assert(Node->getOperand(0).Val->getOpcode() == ISD::BUILD_PAIR);
2542 SDOperand Lo = Node->getOperand(0).Val->getOperand(0);
2543 SDOperand Hi = Node->getOperand(0).Val->getOperand(1);
2545 // This sequence changes FPSCR to do round-to-zero, adds the two halves
2546 // of the long double, and puts FPSCR back the way it was. We do not
2547 // actually model FPSCR.
2548 std::vector<MVT::ValueType> NodeTys;
2549 SDOperand Ops[4], Result, MFFSreg, InFlag, FPreg;
2551 NodeTys.push_back(MVT::f64); // Return register
2552 NodeTys.push_back(MVT::Flag); // Returns a flag for later insns
2553 Result = DAG.getNode(PPCISD::MFFS, NodeTys, &InFlag, 0);
2554 MFFSreg = Result.getValue(0);
2555 InFlag = Result.getValue(1);
2558 NodeTys.push_back(MVT::Flag); // Returns a flag
2559 Ops[0] = DAG.getConstant(31, MVT::i32);
2561 Result = DAG.getNode(PPCISD::MTFSB1, NodeTys, Ops, 2);
2562 InFlag = Result.getValue(0);
2565 NodeTys.push_back(MVT::Flag); // Returns a flag
2566 Ops[0] = DAG.getConstant(30, MVT::i32);
2568 Result = DAG.getNode(PPCISD::MTFSB0, NodeTys, Ops, 2);
2569 InFlag = Result.getValue(0);
2572 NodeTys.push_back(MVT::f64); // result of add
2573 NodeTys.push_back(MVT::Flag); // Returns a flag
2577 Result = DAG.getNode(PPCISD::FADDRTZ, NodeTys, Ops, 3);
2578 FPreg = Result.getValue(0);
2579 InFlag = Result.getValue(1);
2582 NodeTys.push_back(MVT::f64);
2583 Ops[0] = DAG.getConstant(1, MVT::i32);
2587 Result = DAG.getNode(PPCISD::MTFSF, NodeTys, Ops, 4);
2588 FPreg = Result.getValue(0);
2590 // We know the low half is about to be thrown away, so just use something
2592 return DAG.getNode(ISD::BUILD_PAIR, Lo.getValueType(), FPreg, FPreg);
2595 SDOperand PPCTargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
2596 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
2597 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
2600 if (Op.getOperand(0).getValueType() == MVT::i64) {
2601 SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, Op.getOperand(0));
2602 SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Bits);
2603 if (Op.getValueType() == MVT::f32)
2604 FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP, DAG.getIntPtrConstant(0));
2608 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2609 "Unhandled SINT_TO_FP type in custom expander!");
2610 // Since we only generate this in 64-bit mode, we can take advantage of
2611 // 64-bit registers. In particular, sign extend the input value into the
2612 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
2613 // then lfd it and fcfid it.
2614 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2615 int FrameIdx = FrameInfo->CreateStackObject(8, 8);
2616 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2617 SDOperand FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
2619 SDOperand Ext64 = DAG.getNode(PPCISD::EXTSW_32, MVT::i32,
2622 // STD the extended value into the stack slot.
2623 MachineMemOperand MO(PseudoSourceValue::getFixedStack(),
2624 MachineMemOperand::MOStore, FrameIdx, 8, 8);
2625 SDOperand Store = DAG.getNode(PPCISD::STD_32, MVT::Other,
2626 DAG.getEntryNode(), Ext64, FIdx,
2627 DAG.getMemOperand(MO));
2628 // Load the value as a double.
2629 SDOperand Ld = DAG.getLoad(MVT::f64, Store, FIdx, NULL, 0);
2631 // FCFID it and return it.
2632 SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Ld);
2633 if (Op.getValueType() == MVT::f32)
2634 FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP, DAG.getIntPtrConstant(0));
2638 SDOperand PPCTargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
2640 The rounding mode is in bits 30:31 of FPSR, and has the following
2647 FLT_ROUNDS, on the other hand, expects the following:
2654 To perform the conversion, we do:
2655 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
2658 MachineFunction &MF = DAG.getMachineFunction();
2659 MVT::ValueType VT = Op.getValueType();
2660 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2661 std::vector<MVT::ValueType> NodeTys;
2662 SDOperand MFFSreg, InFlag;
2664 // Save FP Control Word to register
2665 NodeTys.push_back(MVT::f64); // return register
2666 NodeTys.push_back(MVT::Flag); // unused in this context
2667 SDOperand Chain = DAG.getNode(PPCISD::MFFS, NodeTys, &InFlag, 0);
2669 // Save FP register to stack slot
2670 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
2671 SDOperand StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
2672 SDOperand Store = DAG.getStore(DAG.getEntryNode(), Chain,
2673 StackSlot, NULL, 0);
2675 // Load FP Control Word from low 32 bits of stack slot.
2676 SDOperand Four = DAG.getConstant(4, PtrVT);
2677 SDOperand Addr = DAG.getNode(ISD::ADD, PtrVT, StackSlot, Four);
2678 SDOperand CWD = DAG.getLoad(MVT::i32, Store, Addr, NULL, 0);
2680 // Transform as necessary
2682 DAG.getNode(ISD::AND, MVT::i32,
2683 CWD, DAG.getConstant(3, MVT::i32));
2685 DAG.getNode(ISD::SRL, MVT::i32,
2686 DAG.getNode(ISD::AND, MVT::i32,
2687 DAG.getNode(ISD::XOR, MVT::i32,
2688 CWD, DAG.getConstant(3, MVT::i32)),
2689 DAG.getConstant(3, MVT::i32)),
2690 DAG.getConstant(1, MVT::i8));
2693 DAG.getNode(ISD::XOR, MVT::i32, CWD1, CWD2);
2695 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
2696 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
2699 SDOperand PPCTargetLowering::LowerSHL_PARTS(SDOperand Op, SelectionDAG &DAG) {
2700 MVT::ValueType VT = Op.getValueType();
2701 unsigned BitWidth = MVT::getSizeInBits(VT);
2702 assert(Op.getNumOperands() == 3 &&
2703 VT == Op.getOperand(1).getValueType() &&
2706 // Expand into a bunch of logical ops. Note that these ops
2707 // depend on the PPC behavior for oversized shift amounts.
2708 SDOperand Lo = Op.getOperand(0);
2709 SDOperand Hi = Op.getOperand(1);
2710 SDOperand Amt = Op.getOperand(2);
2711 MVT::ValueType AmtVT = Amt.getValueType();
2713 SDOperand Tmp1 = DAG.getNode(ISD::SUB, AmtVT,
2714 DAG.getConstant(BitWidth, AmtVT), Amt);
2715 SDOperand Tmp2 = DAG.getNode(PPCISD::SHL, VT, Hi, Amt);
2716 SDOperand Tmp3 = DAG.getNode(PPCISD::SRL, VT, Lo, Tmp1);
2717 SDOperand Tmp4 = DAG.getNode(ISD::OR , VT, Tmp2, Tmp3);
2718 SDOperand Tmp5 = DAG.getNode(ISD::ADD, AmtVT, Amt,
2719 DAG.getConstant(-BitWidth, AmtVT));
2720 SDOperand Tmp6 = DAG.getNode(PPCISD::SHL, VT, Lo, Tmp5);
2721 SDOperand OutHi = DAG.getNode(ISD::OR, VT, Tmp4, Tmp6);
2722 SDOperand OutLo = DAG.getNode(PPCISD::SHL, VT, Lo, Amt);
2723 SDOperand OutOps[] = { OutLo, OutHi };
2724 return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, VT),
2728 SDOperand PPCTargetLowering::LowerSRL_PARTS(SDOperand Op, SelectionDAG &DAG) {
2729 MVT::ValueType VT = Op.getValueType();
2730 unsigned BitWidth = MVT::getSizeInBits(VT);
2731 assert(Op.getNumOperands() == 3 &&
2732 VT == Op.getOperand(1).getValueType() &&
2735 // Expand into a bunch of logical ops. Note that these ops
2736 // depend on the PPC behavior for oversized shift amounts.
2737 SDOperand Lo = Op.getOperand(0);
2738 SDOperand Hi = Op.getOperand(1);
2739 SDOperand Amt = Op.getOperand(2);
2740 MVT::ValueType AmtVT = Amt.getValueType();
2742 SDOperand Tmp1 = DAG.getNode(ISD::SUB, AmtVT,
2743 DAG.getConstant(BitWidth, AmtVT), Amt);
2744 SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, VT, Lo, Amt);
2745 SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, VT, Hi, Tmp1);
2746 SDOperand Tmp4 = DAG.getNode(ISD::OR , VT, Tmp2, Tmp3);
2747 SDOperand Tmp5 = DAG.getNode(ISD::ADD, AmtVT, Amt,
2748 DAG.getConstant(-BitWidth, AmtVT));
2749 SDOperand Tmp6 = DAG.getNode(PPCISD::SRL, VT, Hi, Tmp5);
2750 SDOperand OutLo = DAG.getNode(ISD::OR, VT, Tmp4, Tmp6);
2751 SDOperand OutHi = DAG.getNode(PPCISD::SRL, VT, Hi, Amt);
2752 SDOperand OutOps[] = { OutLo, OutHi };
2753 return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, VT),
2757 SDOperand PPCTargetLowering::LowerSRA_PARTS(SDOperand Op, SelectionDAG &DAG) {
2758 MVT::ValueType VT = Op.getValueType();
2759 unsigned BitWidth = MVT::getSizeInBits(VT);
2760 assert(Op.getNumOperands() == 3 &&
2761 VT == Op.getOperand(1).getValueType() &&
2764 // Expand into a bunch of logical ops, followed by a select_cc.
2765 SDOperand Lo = Op.getOperand(0);
2766 SDOperand Hi = Op.getOperand(1);
2767 SDOperand Amt = Op.getOperand(2);
2768 MVT::ValueType AmtVT = Amt.getValueType();
2770 SDOperand Tmp1 = DAG.getNode(ISD::SUB, AmtVT,
2771 DAG.getConstant(BitWidth, AmtVT), Amt);
2772 SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, VT, Lo, Amt);
2773 SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, VT, Hi, Tmp1);
2774 SDOperand Tmp4 = DAG.getNode(ISD::OR , VT, Tmp2, Tmp3);
2775 SDOperand Tmp5 = DAG.getNode(ISD::ADD, AmtVT, Amt,
2776 DAG.getConstant(-BitWidth, AmtVT));
2777 SDOperand Tmp6 = DAG.getNode(PPCISD::SRA, VT, Hi, Tmp5);
2778 SDOperand OutHi = DAG.getNode(PPCISD::SRA, VT, Hi, Amt);
2779 SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, AmtVT),
2780 Tmp4, Tmp6, ISD::SETLE);
2781 SDOperand OutOps[] = { OutLo, OutHi };
2782 return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, VT),
2786 //===----------------------------------------------------------------------===//
2787 // Vector related lowering.
2790 // If this is a vector of constants or undefs, get the bits. A bit in
2791 // UndefBits is set if the corresponding element of the vector is an
2792 // ISD::UNDEF value. For undefs, the corresponding VectorBits values are
2793 // zero. Return true if this is not an array of constants, false if it is.
2795 static bool GetConstantBuildVectorBits(SDNode *BV, uint64_t VectorBits[2],
2796 uint64_t UndefBits[2]) {
2797 // Start with zero'd results.
2798 VectorBits[0] = VectorBits[1] = UndefBits[0] = UndefBits[1] = 0;
2800 unsigned EltBitSize = MVT::getSizeInBits(BV->getOperand(0).getValueType());
2801 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2802 SDOperand OpVal = BV->getOperand(i);
2804 unsigned PartNo = i >= e/2; // In the upper 128 bits?
2805 unsigned SlotNo = e/2 - (i & (e/2-1))-1; // Which subpiece of the uint64_t.
2807 uint64_t EltBits = 0;
2808 if (OpVal.getOpcode() == ISD::UNDEF) {
2809 uint64_t EltUndefBits = ~0U >> (32-EltBitSize);
2810 UndefBits[PartNo] |= EltUndefBits << (SlotNo*EltBitSize);
2812 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2813 EltBits = CN->getValue() & (~0U >> (32-EltBitSize));
2814 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2815 assert(CN->getValueType(0) == MVT::f32 &&
2816 "Only one legal FP vector type!");
2817 EltBits = FloatToBits(CN->getValueAPF().convertToFloat());
2819 // Nonconstant element.
2823 VectorBits[PartNo] |= EltBits << (SlotNo*EltBitSize);
2826 //printf("%llx %llx %llx %llx\n",
2827 // VectorBits[0], VectorBits[1], UndefBits[0], UndefBits[1]);
2831 // If this is a splat (repetition) of a value across the whole vector, return
2832 // the smallest size that splats it. For example, "0x01010101010101..." is a
2833 // splat of 0x01, 0x0101, and 0x01010101. We return SplatBits = 0x01 and
2834 // SplatSize = 1 byte.
2835 static bool isConstantSplat(const uint64_t Bits128[2],
2836 const uint64_t Undef128[2],
2837 unsigned &SplatBits, unsigned &SplatUndef,
2838 unsigned &SplatSize) {
2840 // Don't let undefs prevent splats from matching. See if the top 64-bits are
2841 // the same as the lower 64-bits, ignoring undefs.
2842 if ((Bits128[0] & ~Undef128[1]) != (Bits128[1] & ~Undef128[0]))
2843 return false; // Can't be a splat if two pieces don't match.
2845 uint64_t Bits64 = Bits128[0] | Bits128[1];
2846 uint64_t Undef64 = Undef128[0] & Undef128[1];
2848 // Check that the top 32-bits are the same as the lower 32-bits, ignoring
2850 if ((Bits64 & (~Undef64 >> 32)) != ((Bits64 >> 32) & ~Undef64))
2851 return false; // Can't be a splat if two pieces don't match.
2853 uint32_t Bits32 = uint32_t(Bits64) | uint32_t(Bits64 >> 32);
2854 uint32_t Undef32 = uint32_t(Undef64) & uint32_t(Undef64 >> 32);
2856 // If the top 16-bits are different than the lower 16-bits, ignoring
2857 // undefs, we have an i32 splat.
2858 if ((Bits32 & (~Undef32 >> 16)) != ((Bits32 >> 16) & ~Undef32)) {
2860 SplatUndef = Undef32;
2865 uint16_t Bits16 = uint16_t(Bits32) | uint16_t(Bits32 >> 16);
2866 uint16_t Undef16 = uint16_t(Undef32) & uint16_t(Undef32 >> 16);
2868 // If the top 8-bits are different than the lower 8-bits, ignoring
2869 // undefs, we have an i16 splat.
2870 if ((Bits16 & (uint16_t(~Undef16) >> 8)) != ((Bits16 >> 8) & ~Undef16)) {
2872 SplatUndef = Undef16;
2877 // Otherwise, we have an 8-bit splat.
2878 SplatBits = uint8_t(Bits16) | uint8_t(Bits16 >> 8);
2879 SplatUndef = uint8_t(Undef16) & uint8_t(Undef16 >> 8);
2884 /// BuildSplatI - Build a canonical splati of Val with an element size of
2885 /// SplatSize. Cast the result to VT.
2886 static SDOperand BuildSplatI(int Val, unsigned SplatSize, MVT::ValueType VT,
2887 SelectionDAG &DAG) {
2888 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
2890 static const MVT::ValueType VTys[] = { // canonical VT to use for each size.
2891 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
2894 MVT::ValueType ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
2896 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
2900 MVT::ValueType CanonicalVT = VTys[SplatSize-1];
2902 // Build a canonical splat for this value.
2903 SDOperand Elt = DAG.getConstant(Val, MVT::getVectorElementType(CanonicalVT));
2904 SmallVector<SDOperand, 8> Ops;
2905 Ops.assign(MVT::getVectorNumElements(CanonicalVT), Elt);
2906 SDOperand Res = DAG.getNode(ISD::BUILD_VECTOR, CanonicalVT,
2907 &Ops[0], Ops.size());
2908 return DAG.getNode(ISD::BIT_CONVERT, ReqVT, Res);
2911 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
2912 /// specified intrinsic ID.
2913 static SDOperand BuildIntrinsicOp(unsigned IID, SDOperand LHS, SDOperand RHS,
2915 MVT::ValueType DestVT = MVT::Other) {
2916 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
2917 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DestVT,
2918 DAG.getConstant(IID, MVT::i32), LHS, RHS);
2921 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
2922 /// specified intrinsic ID.
2923 static SDOperand BuildIntrinsicOp(unsigned IID, SDOperand Op0, SDOperand Op1,
2924 SDOperand Op2, SelectionDAG &DAG,
2925 MVT::ValueType DestVT = MVT::Other) {
2926 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
2927 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DestVT,
2928 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
2932 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
2933 /// amount. The result has the specified value type.
2934 static SDOperand BuildVSLDOI(SDOperand LHS, SDOperand RHS, unsigned Amt,
2935 MVT::ValueType VT, SelectionDAG &DAG) {
2936 // Force LHS/RHS to be the right type.
2937 LHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, LHS);
2938 RHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, RHS);
2941 for (unsigned i = 0; i != 16; ++i)
2942 Ops[i] = DAG.getConstant(i+Amt, MVT::i32);
2943 SDOperand T = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v16i8, LHS, RHS,
2944 DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops,16));
2945 return DAG.getNode(ISD::BIT_CONVERT, VT, T);
2948 // If this is a case we can't handle, return null and let the default
2949 // expansion code take care of it. If we CAN select this case, and if it
2950 // selects to a single instruction, return Op. Otherwise, if we can codegen
2951 // this case more efficiently than a constant pool load, lower it to the
2952 // sequence of ops that should be used.
2953 SDOperand PPCTargetLowering::LowerBUILD_VECTOR(SDOperand Op,
2954 SelectionDAG &DAG) {
2955 // If this is a vector of constants or undefs, get the bits. A bit in
2956 // UndefBits is set if the corresponding element of the vector is an
2957 // ISD::UNDEF value. For undefs, the corresponding VectorBits values are
2959 uint64_t VectorBits[2];
2960 uint64_t UndefBits[2];
2961 if (GetConstantBuildVectorBits(Op.Val, VectorBits, UndefBits))
2962 return SDOperand(); // Not a constant vector.
2964 // If this is a splat (repetition) of a value across the whole vector, return
2965 // the smallest size that splats it. For example, "0x01010101010101..." is a
2966 // splat of 0x01, 0x0101, and 0x01010101. We return SplatBits = 0x01 and
2967 // SplatSize = 1 byte.
2968 unsigned SplatBits, SplatUndef, SplatSize;
2969 if (isConstantSplat(VectorBits, UndefBits, SplatBits, SplatUndef, SplatSize)){
2970 bool HasAnyUndefs = (UndefBits[0] | UndefBits[1]) != 0;
2972 // First, handle single instruction cases.
2975 if (SplatBits == 0) {
2976 // Canonicalize all zero vectors to be v4i32.
2977 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
2978 SDOperand Z = DAG.getConstant(0, MVT::i32);
2979 Z = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Z, Z, Z, Z);
2980 Op = DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Z);
2985 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
2986 int32_t SextVal= int32_t(SplatBits << (32-8*SplatSize)) >> (32-8*SplatSize);
2987 if (SextVal >= -16 && SextVal <= 15)
2988 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG);
2991 // Two instruction sequences.
2993 // If this value is in the range [-32,30] and is even, use:
2994 // tmp = VSPLTI[bhw], result = add tmp, tmp
2995 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
2996 Op = BuildSplatI(SextVal >> 1, SplatSize, Op.getValueType(), DAG);
2997 return DAG.getNode(ISD::ADD, Op.getValueType(), Op, Op);
3000 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
3001 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
3003 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
3004 // Make -1 and vspltisw -1:
3005 SDOperand OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG);
3007 // Make the VSLW intrinsic, computing 0x8000_0000.
3008 SDOperand Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
3011 // xor by OnesV to invert it.
3012 Res = DAG.getNode(ISD::XOR, MVT::v4i32, Res, OnesV);
3013 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
3016 // Check to see if this is a wide variety of vsplti*, binop self cases.
3017 unsigned SplatBitSize = SplatSize*8;
3018 static const signed char SplatCsts[] = {
3019 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
3020 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
3023 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
3024 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
3025 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
3026 int i = SplatCsts[idx];
3028 // Figure out what shift amount will be used by altivec if shifted by i in
3030 unsigned TypeShiftAmt = i & (SplatBitSize-1);
3032 // vsplti + shl self.
3033 if (SextVal == (i << (int)TypeShiftAmt)) {
3034 SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
3035 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3036 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
3037 Intrinsic::ppc_altivec_vslw
3039 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
3040 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
3043 // vsplti + srl self.
3044 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3045 SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
3046 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3047 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
3048 Intrinsic::ppc_altivec_vsrw
3050 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
3051 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
3054 // vsplti + sra self.
3055 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3056 SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
3057 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3058 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
3059 Intrinsic::ppc_altivec_vsraw
3061 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
3062 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
3065 // vsplti + rol self.
3066 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
3067 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
3068 SDOperand Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
3069 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3070 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
3071 Intrinsic::ppc_altivec_vrlw
3073 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
3074 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
3077 // t = vsplti c, result = vsldoi t, t, 1
3078 if (SextVal == ((i << 8) | (i >> (TypeShiftAmt-8)))) {
3079 SDOperand T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
3080 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG);
3082 // t = vsplti c, result = vsldoi t, t, 2
3083 if (SextVal == ((i << 16) | (i >> (TypeShiftAmt-16)))) {
3084 SDOperand T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
3085 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG);
3087 // t = vsplti c, result = vsldoi t, t, 3
3088 if (SextVal == ((i << 24) | (i >> (TypeShiftAmt-24)))) {
3089 SDOperand T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
3090 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG);
3094 // Three instruction sequences.
3096 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
3097 if (SextVal >= 0 && SextVal <= 31) {
3098 SDOperand LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG);
3099 SDOperand RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG);
3100 LHS = DAG.getNode(ISD::SUB, LHS.getValueType(), LHS, RHS);
3101 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), LHS);
3103 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
3104 if (SextVal >= -31 && SextVal <= 0) {
3105 SDOperand LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG);
3106 SDOperand RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG);
3107 LHS = DAG.getNode(ISD::ADD, LHS.getValueType(), LHS, RHS);
3108 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), LHS);
3115 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
3116 /// the specified operations to build the shuffle.
3117 static SDOperand GeneratePerfectShuffle(unsigned PFEntry, SDOperand LHS,
3118 SDOperand RHS, SelectionDAG &DAG) {
3119 unsigned OpNum = (PFEntry >> 26) & 0x0F;
3120 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
3121 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
3124 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
3136 if (OpNum == OP_COPY) {
3137 if (LHSID == (1*9+2)*9+3) return LHS;
3138 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
3142 SDOperand OpLHS, OpRHS;
3143 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG);
3144 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG);
3146 unsigned ShufIdxs[16];
3148 default: assert(0 && "Unknown i32 permute!");
3150 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
3151 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
3152 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
3153 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
3156 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
3157 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
3158 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
3159 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
3162 for (unsigned i = 0; i != 16; ++i)
3163 ShufIdxs[i] = (i&3)+0;
3166 for (unsigned i = 0; i != 16; ++i)
3167 ShufIdxs[i] = (i&3)+4;
3170 for (unsigned i = 0; i != 16; ++i)
3171 ShufIdxs[i] = (i&3)+8;
3174 for (unsigned i = 0; i != 16; ++i)
3175 ShufIdxs[i] = (i&3)+12;
3178 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG);
3180 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG);
3182 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG);
3185 for (unsigned i = 0; i != 16; ++i)
3186 Ops[i] = DAG.getConstant(ShufIdxs[i], MVT::i32);
3188 return DAG.getNode(ISD::VECTOR_SHUFFLE, OpLHS.getValueType(), OpLHS, OpRHS,
3189 DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops, 16));
3192 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
3193 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
3194 /// return the code it can be lowered into. Worst case, it can always be
3195 /// lowered into a vperm.
3196 SDOperand PPCTargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op,
3197 SelectionDAG &DAG) {
3198 SDOperand V1 = Op.getOperand(0);
3199 SDOperand V2 = Op.getOperand(1);
3200 SDOperand PermMask = Op.getOperand(2);
3202 // Cases that are handled by instructions that take permute immediates
3203 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
3204 // selected by the instruction selector.
3205 if (V2.getOpcode() == ISD::UNDEF) {
3206 if (PPC::isSplatShuffleMask(PermMask.Val, 1) ||
3207 PPC::isSplatShuffleMask(PermMask.Val, 2) ||
3208 PPC::isSplatShuffleMask(PermMask.Val, 4) ||
3209 PPC::isVPKUWUMShuffleMask(PermMask.Val, true) ||
3210 PPC::isVPKUHUMShuffleMask(PermMask.Val, true) ||
3211 PPC::isVSLDOIShuffleMask(PermMask.Val, true) != -1 ||
3212 PPC::isVMRGLShuffleMask(PermMask.Val, 1, true) ||
3213 PPC::isVMRGLShuffleMask(PermMask.Val, 2, true) ||
3214 PPC::isVMRGLShuffleMask(PermMask.Val, 4, true) ||
3215 PPC::isVMRGHShuffleMask(PermMask.Val, 1, true) ||
3216 PPC::isVMRGHShuffleMask(PermMask.Val, 2, true) ||
3217 PPC::isVMRGHShuffleMask(PermMask.Val, 4, true)) {
3222 // Altivec has a variety of "shuffle immediates" that take two vector inputs
3223 // and produce a fixed permutation. If any of these match, do not lower to
3225 if (PPC::isVPKUWUMShuffleMask(PermMask.Val, false) ||
3226 PPC::isVPKUHUMShuffleMask(PermMask.Val, false) ||
3227 PPC::isVSLDOIShuffleMask(PermMask.Val, false) != -1 ||
3228 PPC::isVMRGLShuffleMask(PermMask.Val, 1, false) ||
3229 PPC::isVMRGLShuffleMask(PermMask.Val, 2, false) ||
3230 PPC::isVMRGLShuffleMask(PermMask.Val, 4, false) ||
3231 PPC::isVMRGHShuffleMask(PermMask.Val, 1, false) ||
3232 PPC::isVMRGHShuffleMask(PermMask.Val, 2, false) ||
3233 PPC::isVMRGHShuffleMask(PermMask.Val, 4, false))
3236 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
3237 // perfect shuffle table to emit an optimal matching sequence.
3238 unsigned PFIndexes[4];
3239 bool isFourElementShuffle = true;
3240 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
3241 unsigned EltNo = 8; // Start out undef.
3242 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
3243 if (PermMask.getOperand(i*4+j).getOpcode() == ISD::UNDEF)
3244 continue; // Undef, ignore it.
3246 unsigned ByteSource =
3247 cast<ConstantSDNode>(PermMask.getOperand(i*4+j))->getValue();
3248 if ((ByteSource & 3) != j) {
3249 isFourElementShuffle = false;
3254 EltNo = ByteSource/4;
3255 } else if (EltNo != ByteSource/4) {
3256 isFourElementShuffle = false;
3260 PFIndexes[i] = EltNo;
3263 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
3264 // perfect shuffle vector to determine if it is cost effective to do this as
3265 // discrete instructions, or whether we should use a vperm.
3266 if (isFourElementShuffle) {
3267 // Compute the index in the perfect shuffle table.
3268 unsigned PFTableIndex =
3269 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3271 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3272 unsigned Cost = (PFEntry >> 30);
3274 // Determining when to avoid vperm is tricky. Many things affect the cost
3275 // of vperm, particularly how many times the perm mask needs to be computed.
3276 // For example, if the perm mask can be hoisted out of a loop or is already
3277 // used (perhaps because there are multiple permutes with the same shuffle
3278 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
3279 // the loop requires an extra register.
3281 // As a compromise, we only emit discrete instructions if the shuffle can be
3282 // generated in 3 or fewer operations. When we have loop information
3283 // available, if this block is within a loop, we should avoid using vperm
3284 // for 3-operation perms and use a constant pool load instead.
3286 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG);
3289 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
3290 // vector that will get spilled to the constant pool.
3291 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
3293 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
3294 // that it is in input element units, not in bytes. Convert now.
3295 MVT::ValueType EltVT = MVT::getVectorElementType(V1.getValueType());
3296 unsigned BytesPerElement = MVT::getSizeInBits(EltVT)/8;
3298 SmallVector<SDOperand, 16> ResultMask;
3299 for (unsigned i = 0, e = PermMask.getNumOperands(); i != e; ++i) {
3301 if (PermMask.getOperand(i).getOpcode() == ISD::UNDEF)
3304 SrcElt = cast<ConstantSDNode>(PermMask.getOperand(i))->getValue();
3306 for (unsigned j = 0; j != BytesPerElement; ++j)
3307 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
3311 SDOperand VPermMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8,
3312 &ResultMask[0], ResultMask.size());
3313 return DAG.getNode(PPCISD::VPERM, V1.getValueType(), V1, V2, VPermMask);
3316 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
3317 /// altivec comparison. If it is, return true and fill in Opc/isDot with
3318 /// information about the intrinsic.
3319 static bool getAltivecCompareInfo(SDOperand Intrin, int &CompareOpc,
3321 unsigned IntrinsicID = cast<ConstantSDNode>(Intrin.getOperand(0))->getValue();
3324 switch (IntrinsicID) {
3325 default: return false;
3326 // Comparison predicates.
3327 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
3328 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
3329 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
3330 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
3331 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
3332 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
3333 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
3334 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
3335 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
3336 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
3337 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
3338 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
3339 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
3341 // Normal Comparisons.
3342 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
3343 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
3344 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
3345 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
3346 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
3347 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
3348 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
3349 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
3350 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
3351 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
3352 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
3353 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
3354 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
3359 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
3360 /// lower, do it, otherwise return null.
3361 SDOperand PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op,
3362 SelectionDAG &DAG) {
3363 // If this is a lowered altivec predicate compare, CompareOpc is set to the
3364 // opcode number of the comparison.
3367 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
3368 return SDOperand(); // Don't custom lower most intrinsics.
3370 // If this is a non-dot comparison, make the VCMP node and we are done.
3372 SDOperand Tmp = DAG.getNode(PPCISD::VCMP, Op.getOperand(2).getValueType(),
3373 Op.getOperand(1), Op.getOperand(2),
3374 DAG.getConstant(CompareOpc, MVT::i32));
3375 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Tmp);
3378 // Create the PPCISD altivec 'dot' comparison node.
3380 Op.getOperand(2), // LHS
3381 Op.getOperand(3), // RHS
3382 DAG.getConstant(CompareOpc, MVT::i32)
3384 std::vector<MVT::ValueType> VTs;
3385 VTs.push_back(Op.getOperand(2).getValueType());
3386 VTs.push_back(MVT::Flag);
3387 SDOperand CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops, 3);
3389 // Now that we have the comparison, emit a copy from the CR to a GPR.
3390 // This is flagged to the above dot comparison.
3391 SDOperand Flags = DAG.getNode(PPCISD::MFCR, MVT::i32,
3392 DAG.getRegister(PPC::CR6, MVT::i32),
3393 CompNode.getValue(1));
3395 // Unpack the result based on how the target uses it.
3396 unsigned BitNo; // Bit # of CR6.
3397 bool InvertBit; // Invert result?
3398 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
3399 default: // Can't happen, don't crash on invalid number though.
3400 case 0: // Return the value of the EQ bit of CR6.
3401 BitNo = 0; InvertBit = false;
3403 case 1: // Return the inverted value of the EQ bit of CR6.
3404 BitNo = 0; InvertBit = true;
3406 case 2: // Return the value of the LT bit of CR6.
3407 BitNo = 2; InvertBit = false;
3409 case 3: // Return the inverted value of the LT bit of CR6.
3410 BitNo = 2; InvertBit = true;
3414 // Shift the bit into the low position.
3415 Flags = DAG.getNode(ISD::SRL, MVT::i32, Flags,
3416 DAG.getConstant(8-(3-BitNo), MVT::i32));
3418 Flags = DAG.getNode(ISD::AND, MVT::i32, Flags,
3419 DAG.getConstant(1, MVT::i32));
3421 // If we are supposed to, toggle the bit.
3423 Flags = DAG.getNode(ISD::XOR, MVT::i32, Flags,
3424 DAG.getConstant(1, MVT::i32));
3428 SDOperand PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op,
3429 SelectionDAG &DAG) {
3430 // Create a stack slot that is 16-byte aligned.
3431 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3432 int FrameIdx = FrameInfo->CreateStackObject(16, 16);
3433 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3434 SDOperand FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
3436 // Store the input value into Value#0 of the stack slot.
3437 SDOperand Store = DAG.getStore(DAG.getEntryNode(),
3438 Op.getOperand(0), FIdx, NULL, 0);
3440 return DAG.getLoad(Op.getValueType(), Store, FIdx, NULL, 0);
3443 SDOperand PPCTargetLowering::LowerMUL(SDOperand Op, SelectionDAG &DAG) {
3444 if (Op.getValueType() == MVT::v4i32) {
3445 SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3447 SDOperand Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG);
3448 SDOperand Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG); // +16 as shift amt.
3450 SDOperand RHSSwap = // = vrlw RHS, 16
3451 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG);
3453 // Shrinkify inputs to v8i16.
3454 LHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, LHS);
3455 RHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, RHS);
3456 RHSSwap = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, RHSSwap);
3458 // Low parts multiplied together, generating 32-bit results (we ignore the
3460 SDOperand LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
3461 LHS, RHS, DAG, MVT::v4i32);
3463 SDOperand HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
3464 LHS, RHSSwap, Zero, DAG, MVT::v4i32);
3465 // Shift the high parts up 16 bits.
3466 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, Neg16, DAG);
3467 return DAG.getNode(ISD::ADD, MVT::v4i32, LoProd, HiProd);
3468 } else if (Op.getValueType() == MVT::v8i16) {
3469 SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3471 SDOperand Zero = BuildSplatI(0, 1, MVT::v8i16, DAG);
3473 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
3474 LHS, RHS, Zero, DAG);
3475 } else if (Op.getValueType() == MVT::v16i8) {
3476 SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3478 // Multiply the even 8-bit parts, producing 16-bit sums.
3479 SDOperand EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
3480 LHS, RHS, DAG, MVT::v8i16);
3481 EvenParts = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, EvenParts);
3483 // Multiply the odd 8-bit parts, producing 16-bit sums.
3484 SDOperand OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
3485 LHS, RHS, DAG, MVT::v8i16);
3486 OddParts = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, OddParts);
3488 // Merge the results together.
3490 for (unsigned i = 0; i != 8; ++i) {
3491 Ops[i*2 ] = DAG.getConstant(2*i+1, MVT::i8);
3492 Ops[i*2+1] = DAG.getConstant(2*i+1+16, MVT::i8);
3494 return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v16i8, EvenParts, OddParts,
3495 DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops, 16));
3497 assert(0 && "Unknown mul to lower!");
3502 /// LowerOperation - Provide custom lowering hooks for some operations.
3504 SDOperand PPCTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3505 switch (Op.getOpcode()) {
3506 default: assert(0 && "Wasn't expecting to be able to lower this!");
3507 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
3508 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
3509 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
3510 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
3511 case ISD::SETCC: return LowerSETCC(Op, DAG);
3513 return LowerVASTART(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
3514 VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
3517 return LowerVAARG(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
3518 VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
3520 case ISD::FORMAL_ARGUMENTS:
3521 return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex,
3522 VarArgsStackOffset, VarArgsNumGPR,
3523 VarArgsNumFPR, PPCSubTarget);
3525 case ISD::CALL: return LowerCALL(Op, DAG, PPCSubTarget,
3526 getTargetMachine());
3527 case ISD::RET: return LowerRET(Op, DAG, getTargetMachine());
3528 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
3529 case ISD::DYNAMIC_STACKALLOC:
3530 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
3532 case ISD::ATOMIC_LAS: return LowerAtomicLAS(Op, DAG);
3533 case ISD::ATOMIC_LCS: return LowerAtomicLCS(Op, DAG);
3534 case ISD::ATOMIC_SWAP: return LowerAtomicSWAP(Op, DAG);
3536 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
3537 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
3538 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
3539 case ISD::FP_ROUND_INREG: return LowerFP_ROUND_INREG(Op, DAG);
3540 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
3542 // Lower 64-bit shifts.
3543 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
3544 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
3545 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
3547 // Vector-related lowering.
3548 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
3549 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3550 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3551 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
3552 case ISD::MUL: return LowerMUL(Op, DAG);
3554 // Frame & Return address.
3555 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3556 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
3561 SDNode *PPCTargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
3562 switch (N->getOpcode()) {
3563 default: assert(0 && "Wasn't expecting to be able to lower this!");
3564 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(SDOperand(N, 0), DAG).Val;
3569 //===----------------------------------------------------------------------===//
3570 // Other Lowering Code
3571 //===----------------------------------------------------------------------===//
3574 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
3575 MachineBasicBlock *BB) {
3576 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3577 assert((MI->getOpcode() == PPC::SELECT_CC_I4 ||
3578 MI->getOpcode() == PPC::SELECT_CC_I8 ||
3579 MI->getOpcode() == PPC::SELECT_CC_F4 ||
3580 MI->getOpcode() == PPC::SELECT_CC_F8 ||
3581 MI->getOpcode() == PPC::SELECT_CC_VRRC) &&
3582 "Unexpected instr type to insert");
3584 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
3585 // control-flow pattern. The incoming instruction knows the destination vreg
3586 // to set, the condition code register to branch on, the true/false values to
3587 // select between, and a branch opcode to use.
3588 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3589 ilist<MachineBasicBlock>::iterator It = BB;
3595 // cmpTY ccX, r1, r2
3597 // fallthrough --> copy0MBB
3598 MachineBasicBlock *thisMBB = BB;
3599 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
3600 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
3601 unsigned SelectPred = MI->getOperand(4).getImm();
3602 BuildMI(BB, TII->get(PPC::BCC))
3603 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
3604 MachineFunction *F = BB->getParent();
3605 F->getBasicBlockList().insert(It, copy0MBB);
3606 F->getBasicBlockList().insert(It, sinkMBB);
3607 // Update machine-CFG edges by first adding all successors of the current
3608 // block to the new block which will contain the Phi node for the select.
3609 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
3610 e = BB->succ_end(); i != e; ++i)
3611 sinkMBB->addSuccessor(*i);
3612 // Next, remove all successors of the current block, and add the true
3613 // and fallthrough blocks as its successors.
3614 while(!BB->succ_empty())
3615 BB->removeSuccessor(BB->succ_begin());
3616 BB->addSuccessor(copy0MBB);
3617 BB->addSuccessor(sinkMBB);
3620 // %FalseValue = ...
3621 // # fallthrough to sinkMBB
3624 // Update machine-CFG edges
3625 BB->addSuccessor(sinkMBB);
3628 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
3631 BuildMI(BB, TII->get(PPC::PHI), MI->getOperand(0).getReg())
3632 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
3633 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
3635 delete MI; // The pseudo instruction is gone now.
3639 //===----------------------------------------------------------------------===//
3640 // Target Optimization Hooks
3641 //===----------------------------------------------------------------------===//
3643 SDOperand PPCTargetLowering::PerformDAGCombine(SDNode *N,
3644 DAGCombinerInfo &DCI) const {
3645 TargetMachine &TM = getTargetMachine();
3646 SelectionDAG &DAG = DCI.DAG;
3647 switch (N->getOpcode()) {
3650 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
3651 if (C->getValue() == 0) // 0 << V -> 0.
3652 return N->getOperand(0);
3656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
3657 if (C->getValue() == 0) // 0 >>u V -> 0.
3658 return N->getOperand(0);
3662 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
3663 if (C->getValue() == 0 || // 0 >>s V -> 0.
3664 C->isAllOnesValue()) // -1 >>s V -> -1.
3665 return N->getOperand(0);
3669 case ISD::SINT_TO_FP:
3670 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
3671 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
3672 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
3673 // We allow the src/dst to be either f32/f64, but the intermediate
3674 // type must be i64.
3675 if (N->getOperand(0).getValueType() == MVT::i64 &&
3676 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
3677 SDOperand Val = N->getOperand(0).getOperand(0);
3678 if (Val.getValueType() == MVT::f32) {
3679 Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
3680 DCI.AddToWorklist(Val.Val);
3683 Val = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Val);
3684 DCI.AddToWorklist(Val.Val);
3685 Val = DAG.getNode(PPCISD::FCFID, MVT::f64, Val);
3686 DCI.AddToWorklist(Val.Val);
3687 if (N->getValueType(0) == MVT::f32) {
3688 Val = DAG.getNode(ISD::FP_ROUND, MVT::f32, Val,
3689 DAG.getIntPtrConstant(0));
3690 DCI.AddToWorklist(Val.Val);
3693 } else if (N->getOperand(0).getValueType() == MVT::i32) {
3694 // If the intermediate type is i32, we can avoid the load/store here
3701 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
3702 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
3703 !cast<StoreSDNode>(N)->isTruncatingStore() &&
3704 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
3705 N->getOperand(1).getValueType() == MVT::i32 &&
3706 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
3707 SDOperand Val = N->getOperand(1).getOperand(0);
3708 if (Val.getValueType() == MVT::f32) {
3709 Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
3710 DCI.AddToWorklist(Val.Val);
3712 Val = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Val);
3713 DCI.AddToWorklist(Val.Val);
3715 Val = DAG.getNode(PPCISD::STFIWX, MVT::Other, N->getOperand(0), Val,
3716 N->getOperand(2), N->getOperand(3));
3717 DCI.AddToWorklist(Val.Val);
3721 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
3722 if (N->getOperand(1).getOpcode() == ISD::BSWAP &&
3723 N->getOperand(1).Val->hasOneUse() &&
3724 (N->getOperand(1).getValueType() == MVT::i32 ||
3725 N->getOperand(1).getValueType() == MVT::i16)) {
3726 SDOperand BSwapOp = N->getOperand(1).getOperand(0);
3727 // Do an any-extend to 32-bits if this is a half-word input.
3728 if (BSwapOp.getValueType() == MVT::i16)
3729 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, BSwapOp);
3731 return DAG.getNode(PPCISD::STBRX, MVT::Other, N->getOperand(0), BSwapOp,
3732 N->getOperand(2), N->getOperand(3),
3733 DAG.getValueType(N->getOperand(1).getValueType()));
3737 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
3738 if (ISD::isNON_EXTLoad(N->getOperand(0).Val) &&
3739 N->getOperand(0).hasOneUse() &&
3740 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
3741 SDOperand Load = N->getOperand(0);
3742 LoadSDNode *LD = cast<LoadSDNode>(Load);
3743 // Create the byte-swapping load.
3744 std::vector<MVT::ValueType> VTs;
3745 VTs.push_back(MVT::i32);
3746 VTs.push_back(MVT::Other);
3747 SDOperand MO = DAG.getMemOperand(LD->getMemOperand());
3749 LD->getChain(), // Chain
3750 LD->getBasePtr(), // Ptr
3752 DAG.getValueType(N->getValueType(0)) // VT
3754 SDOperand BSLoad = DAG.getNode(PPCISD::LBRX, VTs, Ops, 4);
3756 // If this is an i16 load, insert the truncate.
3757 SDOperand ResVal = BSLoad;
3758 if (N->getValueType(0) == MVT::i16)
3759 ResVal = DAG.getNode(ISD::TRUNCATE, MVT::i16, BSLoad);
3761 // First, combine the bswap away. This makes the value produced by the
3763 DCI.CombineTo(N, ResVal);
3765 // Next, combine the load away, we give it a bogus result value but a real
3766 // chain result. The result value is dead because the bswap is dead.
3767 DCI.CombineTo(Load.Val, ResVal, BSLoad.getValue(1));
3769 // Return N so it doesn't get rechecked!
3770 return SDOperand(N, 0);
3774 case PPCISD::VCMP: {
3775 // If a VCMPo node already exists with exactly the same operands as this
3776 // node, use its result instead of this node (VCMPo computes both a CR6 and
3777 // a normal output).
3779 if (!N->getOperand(0).hasOneUse() &&
3780 !N->getOperand(1).hasOneUse() &&
3781 !N->getOperand(2).hasOneUse()) {
3783 // Scan all of the users of the LHS, looking for VCMPo's that match.
3784 SDNode *VCMPoNode = 0;
3786 SDNode *LHSN = N->getOperand(0).Val;
3787 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
3789 if ((*UI).getUser()->getOpcode() == PPCISD::VCMPo &&
3790 (*UI).getUser()->getOperand(1) == N->getOperand(1) &&
3791 (*UI).getUser()->getOperand(2) == N->getOperand(2) &&
3792 (*UI).getUser()->getOperand(0) == N->getOperand(0)) {
3793 VCMPoNode = UI->getUser();
3797 // If there is no VCMPo node, or if the flag value has a single use, don't
3799 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
3802 // Look at the (necessarily single) use of the flag value. If it has a
3803 // chain, this transformation is more complex. Note that multiple things
3804 // could use the value result, which we should ignore.
3805 SDNode *FlagUser = 0;
3806 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
3807 FlagUser == 0; ++UI) {
3808 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
3809 SDNode *User = UI->getUser();
3810 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
3811 if (User->getOperand(i) == SDOperand(VCMPoNode, 1)) {
3818 // If the user is a MFCR instruction, we know this is safe. Otherwise we
3819 // give up for right now.
3820 if (FlagUser->getOpcode() == PPCISD::MFCR)
3821 return SDOperand(VCMPoNode, 0);
3826 // If this is a branch on an altivec predicate comparison, lower this so
3827 // that we don't have to do a MFCR: instead, branch directly on CR6. This
3828 // lowering is done pre-legalize, because the legalizer lowers the predicate
3829 // compare down to code that is difficult to reassemble.
3830 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
3831 SDOperand LHS = N->getOperand(2), RHS = N->getOperand(3);
3835 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3836 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
3837 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
3838 assert(isDot && "Can't compare against a vector result!");
3840 // If this is a comparison against something other than 0/1, then we know
3841 // that the condition is never/always true.
3842 unsigned Val = cast<ConstantSDNode>(RHS)->getValue();
3843 if (Val != 0 && Val != 1) {
3844 if (CC == ISD::SETEQ) // Cond never true, remove branch.
3845 return N->getOperand(0);
3846 // Always !=, turn it into an unconditional branch.
3847 return DAG.getNode(ISD::BR, MVT::Other,
3848 N->getOperand(0), N->getOperand(4));
3851 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
3853 // Create the PPCISD altivec 'dot' comparison node.
3854 std::vector<MVT::ValueType> VTs;
3856 LHS.getOperand(2), // LHS of compare
3857 LHS.getOperand(3), // RHS of compare
3858 DAG.getConstant(CompareOpc, MVT::i32)
3860 VTs.push_back(LHS.getOperand(2).getValueType());
3861 VTs.push_back(MVT::Flag);
3862 SDOperand CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops, 3);
3864 // Unpack the result based on how the target uses it.
3865 PPC::Predicate CompOpc;
3866 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getValue()) {
3867 default: // Can't happen, don't crash on invalid number though.
3868 case 0: // Branch on the value of the EQ bit of CR6.
3869 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
3871 case 1: // Branch on the inverted value of the EQ bit of CR6.
3872 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
3874 case 2: // Branch on the value of the LT bit of CR6.
3875 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
3877 case 3: // Branch on the inverted value of the LT bit of CR6.
3878 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
3882 return DAG.getNode(PPCISD::COND_BRANCH, MVT::Other, N->getOperand(0),
3883 DAG.getConstant(CompOpc, MVT::i32),
3884 DAG.getRegister(PPC::CR6, MVT::i32),
3885 N->getOperand(4), CompNode.getValue(1));
3894 //===----------------------------------------------------------------------===//
3895 // Inline Assembly Support
3896 //===----------------------------------------------------------------------===//
3898 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
3902 const SelectionDAG &DAG,
3903 unsigned Depth) const {
3904 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3905 switch (Op.getOpcode()) {
3907 case PPCISD::LBRX: {
3908 // lhbrx is known to have the top bits cleared out.
3909 if (cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::i16)
3910 KnownZero = 0xFFFF0000;
3913 case ISD::INTRINSIC_WO_CHAIN: {
3914 switch (cast<ConstantSDNode>(Op.getOperand(0))->getValue()) {
3916 case Intrinsic::ppc_altivec_vcmpbfp_p:
3917 case Intrinsic::ppc_altivec_vcmpeqfp_p:
3918 case Intrinsic::ppc_altivec_vcmpequb_p:
3919 case Intrinsic::ppc_altivec_vcmpequh_p:
3920 case Intrinsic::ppc_altivec_vcmpequw_p:
3921 case Intrinsic::ppc_altivec_vcmpgefp_p:
3922 case Intrinsic::ppc_altivec_vcmpgtfp_p:
3923 case Intrinsic::ppc_altivec_vcmpgtsb_p:
3924 case Intrinsic::ppc_altivec_vcmpgtsh_p:
3925 case Intrinsic::ppc_altivec_vcmpgtsw_p:
3926 case Intrinsic::ppc_altivec_vcmpgtub_p:
3927 case Intrinsic::ppc_altivec_vcmpgtuh_p:
3928 case Intrinsic::ppc_altivec_vcmpgtuw_p:
3929 KnownZero = ~1U; // All bits but the low one are known to be zero.
3937 /// getConstraintType - Given a constraint, return the type of
3938 /// constraint it is for this target.
3939 PPCTargetLowering::ConstraintType
3940 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
3941 if (Constraint.size() == 1) {
3942 switch (Constraint[0]) {
3949 return C_RegisterClass;
3952 return TargetLowering::getConstraintType(Constraint);
3955 std::pair<unsigned, const TargetRegisterClass*>
3956 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3957 MVT::ValueType VT) const {
3958 if (Constraint.size() == 1) {
3959 // GCC RS6000 Constraint Letters
3960 switch (Constraint[0]) {
3963 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
3964 return std::make_pair(0U, PPC::G8RCRegisterClass);
3965 return std::make_pair(0U, PPC::GPRCRegisterClass);
3968 return std::make_pair(0U, PPC::F4RCRegisterClass);
3969 else if (VT == MVT::f64)
3970 return std::make_pair(0U, PPC::F8RCRegisterClass);
3973 return std::make_pair(0U, PPC::VRRCRegisterClass);
3975 return std::make_pair(0U, PPC::CRRCRegisterClass);
3979 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3983 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3984 /// vector. If it is invalid, don't add anything to Ops.
3985 void PPCTargetLowering::LowerAsmOperandForConstraint(SDOperand Op, char Letter,
3986 std::vector<SDOperand>&Ops,
3987 SelectionDAG &DAG) {
3988 SDOperand Result(0,0);
3999 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
4000 if (!CST) return; // Must be an immediate to match.
4001 unsigned Value = CST->getValue();
4003 default: assert(0 && "Unknown constraint letter!");
4004 case 'I': // "I" is a signed 16-bit constant.
4005 if ((short)Value == (int)Value)
4006 Result = DAG.getTargetConstant(Value, Op.getValueType());
4008 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
4009 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
4010 if ((short)Value == 0)
4011 Result = DAG.getTargetConstant(Value, Op.getValueType());
4013 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
4014 if ((Value >> 16) == 0)
4015 Result = DAG.getTargetConstant(Value, Op.getValueType());
4017 case 'M': // "M" is a constant that is greater than 31.
4019 Result = DAG.getTargetConstant(Value, Op.getValueType());
4021 case 'N': // "N" is a positive constant that is an exact power of two.
4022 if ((int)Value > 0 && isPowerOf2_32(Value))
4023 Result = DAG.getTargetConstant(Value, Op.getValueType());
4025 case 'O': // "O" is the constant zero.
4027 Result = DAG.getTargetConstant(Value, Op.getValueType());
4029 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
4030 if ((short)-Value == (int)-Value)
4031 Result = DAG.getTargetConstant(Value, Op.getValueType());
4039 Ops.push_back(Result);
4043 // Handle standard constraint letters.
4044 TargetLowering::LowerAsmOperandForConstraint(Op, Letter, Ops, DAG);
4047 // isLegalAddressingMode - Return true if the addressing mode represented
4048 // by AM is legal for this target, for a load/store of the specified type.
4049 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
4050 const Type *Ty) const {
4051 // FIXME: PPC does not allow r+i addressing modes for vectors!
4053 // PPC allows a sign-extended 16-bit immediate field.
4054 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
4057 // No global is ever allowed as a base.
4061 // PPC only support r+r,
4063 case 0: // "r+i" or just "i", depending on HasBaseReg.
4066 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
4068 // Otherwise we have r+r or r+i.
4071 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
4073 // Allow 2*r as r+r.
4076 // No other scales are supported.
4083 /// isLegalAddressImmediate - Return true if the integer value can be used
4084 /// as the offset of the target addressing mode for load / store of the
4086 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
4087 // PPC allows a sign-extended 16-bit immediate field.
4088 return (V > -(1 << 16) && V < (1 << 16)-1);
4091 bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) const {
4095 SDOperand PPCTargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4096 // Depths > 0 not supported yet!
4097 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4100 MachineFunction &MF = DAG.getMachineFunction();
4101 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4102 int RAIdx = FuncInfo->getReturnAddrSaveIndex();
4104 bool isPPC64 = PPCSubTarget.isPPC64();
4106 PPCFrameInfo::getReturnSaveOffset(isPPC64, PPCSubTarget.isMachoABI());
4108 // Set up a frame object for the return address.
4109 RAIdx = MF.getFrameInfo()->CreateFixedObject(isPPC64 ? 8 : 4, Offset);
4111 // Remember it for next time.
4112 FuncInfo->setReturnAddrSaveIndex(RAIdx);
4114 // Make sure the function really does not optimize away the store of the RA
4116 FuncInfo->setLRStoreRequired();
4119 // Just load the return address off the stack.
4120 SDOperand RetAddrFI = DAG.getFrameIndex(RAIdx, getPointerTy());
4121 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4124 SDOperand PPCTargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4125 // Depths > 0 not supported yet!
4126 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4129 MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4130 bool isPPC64 = PtrVT == MVT::i64;
4132 MachineFunction &MF = DAG.getMachineFunction();
4133 MachineFrameInfo *MFI = MF.getFrameInfo();
4134 bool is31 = (NoFramePointerElim || MFI->hasVarSizedObjects())
4135 && MFI->getStackSize();
4138 return DAG.getCopyFromReg(DAG.getEntryNode(), is31 ? PPC::X31 : PPC::X1,
4141 return DAG.getCopyFromReg(DAG.getEntryNode(), is31 ? PPC::R31 : PPC::R1,