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/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CallingConv.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/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/DerivedTypes.h"
41 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
42 CCValAssign::LocInfo &LocInfo,
43 ISD::ArgFlagsTy &ArgFlags,
45 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
47 CCValAssign::LocInfo &LocInfo,
48 ISD::ArgFlagsTy &ArgFlags,
50 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
52 CCValAssign::LocInfo &LocInfo,
53 ISD::ArgFlagsTy &ArgFlags,
56 static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc",
57 cl::desc("enable preincrement load/store generation on PPC (experimental)"),
60 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
61 if (TM.getSubtargetImpl()->isDarwin())
62 return new TargetLoweringObjectFileMachO(TM);
63 return new TargetLoweringObjectFileELF(false, true);
67 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
68 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
72 // Use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
78 addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
79 addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
81 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
82 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
83 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
85 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87 // PowerPC has pre-inc load and store's.
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99 // This is used in the ppcf128->int sequence. Note it has different semantics
100 // from FP_ROUND: that rounds to nearest, this rounds to zero.
101 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
103 // PowerPC has no SREM/UREM instructions
104 setOperationAction(ISD::SREM, MVT::i32, Expand);
105 setOperationAction(ISD::UREM, MVT::i32, Expand);
106 setOperationAction(ISD::SREM, MVT::i64, Expand);
107 setOperationAction(ISD::UREM, MVT::i64, Expand);
109 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
110 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
111 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
112 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
113 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
114 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
115 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
116 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
117 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
119 // We don't support sin/cos/sqrt/fmod/pow
120 setOperationAction(ISD::FSIN , MVT::f64, Expand);
121 setOperationAction(ISD::FCOS , MVT::f64, Expand);
122 setOperationAction(ISD::FREM , MVT::f64, Expand);
123 setOperationAction(ISD::FPOW , MVT::f64, Expand);
124 setOperationAction(ISD::FSIN , MVT::f32, Expand);
125 setOperationAction(ISD::FCOS , MVT::f32, Expand);
126 setOperationAction(ISD::FREM , MVT::f32, Expand);
127 setOperationAction(ISD::FPOW , MVT::f32, Expand);
129 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
131 // If we're enabling GP optimizations, use hardware square root
132 if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
133 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
134 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
137 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
138 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
140 // PowerPC does not have BSWAP, CTPOP or CTTZ
141 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
142 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
143 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
144 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
145 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
146 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
148 // PowerPC does not have ROTR
149 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
150 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
152 // PowerPC does not have Select
153 setOperationAction(ISD::SELECT, MVT::i32, Expand);
154 setOperationAction(ISD::SELECT, MVT::i64, Expand);
155 setOperationAction(ISD::SELECT, MVT::f32, Expand);
156 setOperationAction(ISD::SELECT, MVT::f64, Expand);
158 // PowerPC wants to turn select_cc of FP into fsel when possible.
159 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
160 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
162 // PowerPC wants to optimize integer setcc a bit
163 setOperationAction(ISD::SETCC, MVT::i32, Custom);
165 // PowerPC does not have BRCOND which requires SetCC
166 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
168 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
170 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
171 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
173 // PowerPC does not have [U|S]INT_TO_FP
174 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
175 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
177 setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
178 setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
179 setOperationAction(ISD::BIT_CONVERT, MVT::i64, Expand);
180 setOperationAction(ISD::BIT_CONVERT, MVT::f64, Expand);
182 // We cannot sextinreg(i1). Expand to shifts.
183 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
185 // Support label based line numbers.
186 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
187 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
189 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
190 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
191 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
192 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
195 // We want to legalize GlobalAddress and ConstantPool nodes into the
196 // appropriate instructions to materialize the address.
197 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
198 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
199 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
200 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
201 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
202 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
203 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
204 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
206 // RET must be custom lowered, to meet ABI requirements.
207 setOperationAction(ISD::RET , MVT::Other, Custom);
210 setOperationAction(ISD::TRAP, MVT::Other, Legal);
212 // TRAMPOLINE is custom lowered.
213 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
215 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
216 setOperationAction(ISD::VASTART , MVT::Other, Custom);
218 // VAARG is custom lowered with the SVR4 ABI
219 if (TM.getSubtarget<PPCSubtarget>().isSVR4ABI())
220 setOperationAction(ISD::VAARG, MVT::Other, Custom);
222 setOperationAction(ISD::VAARG, MVT::Other, Expand);
224 // Use the default implementation.
225 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
226 setOperationAction(ISD::VAEND , MVT::Other, Expand);
227 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
228 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
229 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
230 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
232 // We want to custom lower some of our intrinsics.
233 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
235 // Comparisons that require checking two conditions.
236 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
237 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
238 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
239 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
240 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
243 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
244 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
247 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
249 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
250 // They also have instructions for converting between i64 and fp.
251 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
252 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
253 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
254 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
255 // This is just the low 32 bits of a (signed) fp->i64 conversion.
256 // We cannot do this with Promote because i64 is not a legal type.
257 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
259 // FIXME: disable this lowered code. This generates 64-bit register values,
260 // and we don't model the fact that the top part is clobbered by calls. We
261 // need to flag these together so that the value isn't live across a call.
262 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
264 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
265 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
268 if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
269 // 64-bit PowerPC implementations can support i64 types directly
270 addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
271 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
272 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
273 // 64-bit PowerPC wants to expand i128 shifts itself.
274 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
275 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
276 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
278 // 32-bit PowerPC wants to expand i64 shifts itself.
279 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
280 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
281 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
284 if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
285 // First set operation action for all vector types to expand. Then we
286 // will selectively turn on ones that can be effectively codegen'd.
287 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
288 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
289 MVT VT = (MVT::SimpleValueType)i;
291 // add/sub are legal for all supported vector VT's.
292 setOperationAction(ISD::ADD , VT, Legal);
293 setOperationAction(ISD::SUB , VT, Legal);
295 // We promote all shuffles to v16i8.
296 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
297 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
299 // We promote all non-typed operations to v4i32.
300 setOperationAction(ISD::AND , VT, Promote);
301 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
302 setOperationAction(ISD::OR , VT, Promote);
303 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
304 setOperationAction(ISD::XOR , VT, Promote);
305 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
306 setOperationAction(ISD::LOAD , VT, Promote);
307 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
308 setOperationAction(ISD::SELECT, VT, Promote);
309 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
310 setOperationAction(ISD::STORE, VT, Promote);
311 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
313 // No other operations are legal.
314 setOperationAction(ISD::MUL , VT, Expand);
315 setOperationAction(ISD::SDIV, VT, Expand);
316 setOperationAction(ISD::SREM, VT, Expand);
317 setOperationAction(ISD::UDIV, VT, Expand);
318 setOperationAction(ISD::UREM, VT, Expand);
319 setOperationAction(ISD::FDIV, VT, Expand);
320 setOperationAction(ISD::FNEG, VT, Expand);
321 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
322 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
323 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
324 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
325 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
326 setOperationAction(ISD::UDIVREM, VT, Expand);
327 setOperationAction(ISD::SDIVREM, VT, Expand);
328 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
329 setOperationAction(ISD::FPOW, VT, Expand);
330 setOperationAction(ISD::CTPOP, VT, Expand);
331 setOperationAction(ISD::CTLZ, VT, Expand);
332 setOperationAction(ISD::CTTZ, VT, Expand);
335 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
336 // with merges, splats, etc.
337 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
339 setOperationAction(ISD::AND , MVT::v4i32, Legal);
340 setOperationAction(ISD::OR , MVT::v4i32, Legal);
341 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
342 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
343 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
344 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
346 addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
347 addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
348 addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
349 addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
351 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
352 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
353 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
354 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
356 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
357 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
359 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
360 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
361 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
362 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
365 setShiftAmountType(MVT::i32);
366 setBooleanContents(ZeroOrOneBooleanContent);
368 if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
369 setStackPointerRegisterToSaveRestore(PPC::X1);
370 setExceptionPointerRegister(PPC::X3);
371 setExceptionSelectorRegister(PPC::X4);
373 setStackPointerRegisterToSaveRestore(PPC::R1);
374 setExceptionPointerRegister(PPC::R3);
375 setExceptionSelectorRegister(PPC::R4);
378 // We have target-specific dag combine patterns for the following nodes:
379 setTargetDAGCombine(ISD::SINT_TO_FP);
380 setTargetDAGCombine(ISD::STORE);
381 setTargetDAGCombine(ISD::BR_CC);
382 setTargetDAGCombine(ISD::BSWAP);
384 // Darwin long double math library functions have $LDBL128 appended.
385 if (TM.getSubtarget<PPCSubtarget>().isDarwin()) {
386 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
387 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
388 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
389 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
390 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
391 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
392 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
393 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
394 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
395 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
398 computeRegisterProperties();
401 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
402 /// function arguments in the caller parameter area.
403 unsigned PPCTargetLowering::getByValTypeAlignment(const Type *Ty) const {
404 TargetMachine &TM = getTargetMachine();
405 // Darwin passes everything on 4 byte boundary.
406 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
412 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
415 case PPCISD::FSEL: return "PPCISD::FSEL";
416 case PPCISD::FCFID: return "PPCISD::FCFID";
417 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
418 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
419 case PPCISD::STFIWX: return "PPCISD::STFIWX";
420 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
421 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
422 case PPCISD::VPERM: return "PPCISD::VPERM";
423 case PPCISD::Hi: return "PPCISD::Hi";
424 case PPCISD::Lo: return "PPCISD::Lo";
425 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
426 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
427 case PPCISD::SRL: return "PPCISD::SRL";
428 case PPCISD::SRA: return "PPCISD::SRA";
429 case PPCISD::SHL: return "PPCISD::SHL";
430 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
431 case PPCISD::STD_32: return "PPCISD::STD_32";
432 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4";
433 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin";
434 case PPCISD::MTCTR: return "PPCISD::MTCTR";
435 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin";
436 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4";
437 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
438 case PPCISD::MFCR: return "PPCISD::MFCR";
439 case PPCISD::VCMP: return "PPCISD::VCMP";
440 case PPCISD::VCMPo: return "PPCISD::VCMPo";
441 case PPCISD::LBRX: return "PPCISD::LBRX";
442 case PPCISD::STBRX: return "PPCISD::STBRX";
443 case PPCISD::LARX: return "PPCISD::LARX";
444 case PPCISD::STCX: return "PPCISD::STCX";
445 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
446 case PPCISD::MFFS: return "PPCISD::MFFS";
447 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
448 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
449 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
450 case PPCISD::MTFSF: return "PPCISD::MTFSF";
451 case PPCISD::TAILCALL: return "PPCISD::TAILCALL";
452 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
456 MVT PPCTargetLowering::getSetCCResultType(MVT VT) const {
460 /// getFunctionAlignment - Return the Log2 alignment of this function.
461 unsigned PPCTargetLowering::getFunctionAlignment(const Function *F) const {
462 if (getTargetMachine().getSubtarget<PPCSubtarget>().isDarwin())
463 return F->hasFnAttr(Attribute::OptimizeForSize) ? 2 : 4;
468 //===----------------------------------------------------------------------===//
469 // Node matching predicates, for use by the tblgen matching code.
470 //===----------------------------------------------------------------------===//
472 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
473 static bool isFloatingPointZero(SDValue Op) {
474 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
475 return CFP->getValueAPF().isZero();
476 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
477 // Maybe this has already been legalized into the constant pool?
478 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
479 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
480 return CFP->getValueAPF().isZero();
485 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
486 /// true if Op is undef or if it matches the specified value.
487 static bool isConstantOrUndef(int Op, int Val) {
488 return Op < 0 || Op == Val;
491 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
492 /// VPKUHUM instruction.
493 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
495 for (unsigned i = 0; i != 16; ++i)
496 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
499 for (unsigned i = 0; i != 8; ++i)
500 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
501 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
507 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
508 /// VPKUWUM instruction.
509 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
511 for (unsigned i = 0; i != 16; i += 2)
512 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
513 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
516 for (unsigned i = 0; i != 8; i += 2)
517 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
518 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
519 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
520 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
526 /// isVMerge - Common function, used to match vmrg* shuffles.
528 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
529 unsigned LHSStart, unsigned RHSStart) {
530 assert(N->getValueType(0) == MVT::v16i8 &&
531 "PPC only supports shuffles by bytes!");
532 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
533 "Unsupported merge size!");
535 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
536 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
537 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
538 LHSStart+j+i*UnitSize) ||
539 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
540 RHSStart+j+i*UnitSize))
546 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
547 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
548 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
551 return isVMerge(N, UnitSize, 8, 24);
552 return isVMerge(N, UnitSize, 8, 8);
555 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
556 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
557 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
560 return isVMerge(N, UnitSize, 0, 16);
561 return isVMerge(N, UnitSize, 0, 0);
565 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
566 /// amount, otherwise return -1.
567 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
568 assert(N->getValueType(0) == MVT::v16i8 &&
569 "PPC only supports shuffles by bytes!");
571 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
573 // Find the first non-undef value in the shuffle mask.
575 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
578 if (i == 16) return -1; // all undef.
580 // Otherwise, check to see if the rest of the elements are consecutively
581 // numbered from this value.
582 unsigned ShiftAmt = SVOp->getMaskElt(i);
583 if (ShiftAmt < i) return -1;
587 // Check the rest of the elements to see if they are consecutive.
588 for (++i; i != 16; ++i)
589 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
592 // Check the rest of the elements to see if they are consecutive.
593 for (++i; i != 16; ++i)
594 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
600 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
601 /// specifies a splat of a single element that is suitable for input to
602 /// VSPLTB/VSPLTH/VSPLTW.
603 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
604 assert(N->getValueType(0) == MVT::v16i8 &&
605 (EltSize == 1 || EltSize == 2 || EltSize == 4));
607 // This is a splat operation if each element of the permute is the same, and
608 // if the value doesn't reference the second vector.
609 unsigned ElementBase = N->getMaskElt(0);
611 // FIXME: Handle UNDEF elements too!
612 if (ElementBase >= 16)
615 // Check that the indices are consecutive, in the case of a multi-byte element
616 // splatted with a v16i8 mask.
617 for (unsigned i = 1; i != EltSize; ++i)
618 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
621 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
622 if (N->getMaskElt(i) < 0) continue;
623 for (unsigned j = 0; j != EltSize; ++j)
624 if (N->getMaskElt(i+j) != N->getMaskElt(j))
630 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
632 bool PPC::isAllNegativeZeroVector(SDNode *N) {
633 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
635 APInt APVal, APUndef;
639 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32))
640 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
641 return CFP->getValueAPF().isNegZero();
646 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
647 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
648 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
649 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
650 assert(isSplatShuffleMask(SVOp, EltSize));
651 return SVOp->getMaskElt(0) / EltSize;
654 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
655 /// by using a vspltis[bhw] instruction of the specified element size, return
656 /// the constant being splatted. The ByteSize field indicates the number of
657 /// bytes of each element [124] -> [bhw].
658 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
661 // If ByteSize of the splat is bigger than the element size of the
662 // build_vector, then we have a case where we are checking for a splat where
663 // multiple elements of the buildvector are folded together into a single
664 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
665 unsigned EltSize = 16/N->getNumOperands();
666 if (EltSize < ByteSize) {
667 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
668 SDValue UniquedVals[4];
669 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
671 // See if all of the elements in the buildvector agree across.
672 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
673 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
674 // If the element isn't a constant, bail fully out.
675 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
678 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
679 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
680 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
681 return SDValue(); // no match.
684 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
685 // either constant or undef values that are identical for each chunk. See
686 // if these chunks can form into a larger vspltis*.
688 // Check to see if all of the leading entries are either 0 or -1. If
689 // neither, then this won't fit into the immediate field.
690 bool LeadingZero = true;
691 bool LeadingOnes = true;
692 for (unsigned i = 0; i != Multiple-1; ++i) {
693 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
695 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
696 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
698 // Finally, check the least significant entry.
700 if (UniquedVals[Multiple-1].getNode() == 0)
701 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
702 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
704 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
707 if (UniquedVals[Multiple-1].getNode() == 0)
708 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
709 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
710 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
711 return DAG.getTargetConstant(Val, MVT::i32);
717 // Check to see if this buildvec has a single non-undef value in its elements.
718 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
719 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
720 if (OpVal.getNode() == 0)
721 OpVal = N->getOperand(i);
722 else if (OpVal != N->getOperand(i))
726 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
728 unsigned ValSizeInBytes = EltSize;
730 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
731 Value = CN->getZExtValue();
732 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
733 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
734 Value = FloatToBits(CN->getValueAPF().convertToFloat());
737 // If the splat value is larger than the element value, then we can never do
738 // this splat. The only case that we could fit the replicated bits into our
739 // immediate field for would be zero, and we prefer to use vxor for it.
740 if (ValSizeInBytes < ByteSize) return SDValue();
742 // If the element value is larger than the splat value, cut it in half and
743 // check to see if the two halves are equal. Continue doing this until we
744 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
745 while (ValSizeInBytes > ByteSize) {
746 ValSizeInBytes >>= 1;
748 // If the top half equals the bottom half, we're still ok.
749 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
750 (Value & ((1 << (8*ValSizeInBytes))-1)))
754 // Properly sign extend the value.
755 int ShAmt = (4-ByteSize)*8;
756 int MaskVal = ((int)Value << ShAmt) >> ShAmt;
758 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
759 if (MaskVal == 0) return SDValue();
761 // Finally, if this value fits in a 5 bit sext field, return it
762 if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
763 return DAG.getTargetConstant(MaskVal, MVT::i32);
767 //===----------------------------------------------------------------------===//
768 // Addressing Mode Selection
769 //===----------------------------------------------------------------------===//
771 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
772 /// or 64-bit immediate, and if the value can be accurately represented as a
773 /// sign extension from a 16-bit value. If so, this returns true and the
775 static bool isIntS16Immediate(SDNode *N, short &Imm) {
776 if (N->getOpcode() != ISD::Constant)
779 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
780 if (N->getValueType(0) == MVT::i32)
781 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
783 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
785 static bool isIntS16Immediate(SDValue Op, short &Imm) {
786 return isIntS16Immediate(Op.getNode(), Imm);
790 /// SelectAddressRegReg - Given the specified addressed, check to see if it
791 /// can be represented as an indexed [r+r] operation. Returns false if it
792 /// can be more efficiently represented with [r+imm].
793 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
795 SelectionDAG &DAG) const {
797 if (N.getOpcode() == ISD::ADD) {
798 if (isIntS16Immediate(N.getOperand(1), imm))
800 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
803 Base = N.getOperand(0);
804 Index = N.getOperand(1);
806 } else if (N.getOpcode() == ISD::OR) {
807 if (isIntS16Immediate(N.getOperand(1), imm))
808 return false; // r+i can fold it if we can.
810 // If this is an or of disjoint bitfields, we can codegen this as an add
811 // (for better address arithmetic) if the LHS and RHS of the OR are provably
813 APInt LHSKnownZero, LHSKnownOne;
814 APInt RHSKnownZero, RHSKnownOne;
815 DAG.ComputeMaskedBits(N.getOperand(0),
816 APInt::getAllOnesValue(N.getOperand(0)
817 .getValueSizeInBits()),
818 LHSKnownZero, LHSKnownOne);
820 if (LHSKnownZero.getBoolValue()) {
821 DAG.ComputeMaskedBits(N.getOperand(1),
822 APInt::getAllOnesValue(N.getOperand(1)
823 .getValueSizeInBits()),
824 RHSKnownZero, RHSKnownOne);
825 // If all of the bits are known zero on the LHS or RHS, the add won't
827 if (~(LHSKnownZero | RHSKnownZero) == 0) {
828 Base = N.getOperand(0);
829 Index = N.getOperand(1);
838 /// Returns true if the address N can be represented by a base register plus
839 /// a signed 16-bit displacement [r+imm], and if it is not better
840 /// represented as reg+reg.
841 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
843 SelectionDAG &DAG) const {
844 // FIXME dl should come from parent load or store, not from address
845 DebugLoc dl = N.getDebugLoc();
846 // If this can be more profitably realized as r+r, fail.
847 if (SelectAddressRegReg(N, Disp, Base, DAG))
850 if (N.getOpcode() == ISD::ADD) {
852 if (isIntS16Immediate(N.getOperand(1), imm)) {
853 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
854 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
855 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
857 Base = N.getOperand(0);
859 return true; // [r+i]
860 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
861 // Match LOAD (ADD (X, Lo(G))).
862 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
863 && "Cannot handle constant offsets yet!");
864 Disp = N.getOperand(1).getOperand(0); // The global address.
865 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
866 Disp.getOpcode() == ISD::TargetConstantPool ||
867 Disp.getOpcode() == ISD::TargetJumpTable);
868 Base = N.getOperand(0);
869 return true; // [&g+r]
871 } else if (N.getOpcode() == ISD::OR) {
873 if (isIntS16Immediate(N.getOperand(1), imm)) {
874 // If this is an or of disjoint bitfields, we can codegen this as an add
875 // (for better address arithmetic) if the LHS and RHS of the OR are
876 // provably disjoint.
877 APInt LHSKnownZero, LHSKnownOne;
878 DAG.ComputeMaskedBits(N.getOperand(0),
879 APInt::getAllOnesValue(N.getOperand(0)
880 .getValueSizeInBits()),
881 LHSKnownZero, LHSKnownOne);
883 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
884 // If all of the bits are known zero on the LHS or RHS, the add won't
886 Base = N.getOperand(0);
887 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
891 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
892 // Loading from a constant address.
894 // If this address fits entirely in a 16-bit sext immediate field, codegen
897 if (isIntS16Immediate(CN, Imm)) {
898 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
899 Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
903 // Handle 32-bit sext immediates with LIS + addr mode.
904 if (CN->getValueType(0) == MVT::i32 ||
905 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
906 int Addr = (int)CN->getZExtValue();
908 // Otherwise, break this down into an LIS + disp.
909 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
911 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
912 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
913 Base = SDValue(DAG.getTargetNode(Opc, dl, CN->getValueType(0), Base), 0);
918 Disp = DAG.getTargetConstant(0, getPointerTy());
919 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
920 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
923 return true; // [r+0]
926 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
927 /// represented as an indexed [r+r] operation.
928 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
930 SelectionDAG &DAG) const {
931 // Check to see if we can easily represent this as an [r+r] address. This
932 // will fail if it thinks that the address is more profitably represented as
933 // reg+imm, e.g. where imm = 0.
934 if (SelectAddressRegReg(N, Base, Index, DAG))
937 // If the operand is an addition, always emit this as [r+r], since this is
938 // better (for code size, and execution, as the memop does the add for free)
939 // than emitting an explicit add.
940 if (N.getOpcode() == ISD::ADD) {
941 Base = N.getOperand(0);
942 Index = N.getOperand(1);
946 // Otherwise, do it the hard way, using R0 as the base register.
947 Base = DAG.getRegister(PPC::R0, N.getValueType());
952 /// SelectAddressRegImmShift - Returns true if the address N can be
953 /// represented by a base register plus a signed 14-bit displacement
954 /// [r+imm*4]. Suitable for use by STD and friends.
955 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
957 SelectionDAG &DAG) const {
958 // FIXME dl should come from the parent load or store, not the address
959 DebugLoc dl = N.getDebugLoc();
960 // If this can be more profitably realized as r+r, fail.
961 if (SelectAddressRegReg(N, Disp, Base, DAG))
964 if (N.getOpcode() == ISD::ADD) {
966 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
967 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
968 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
969 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
971 Base = N.getOperand(0);
973 return true; // [r+i]
974 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
975 // Match LOAD (ADD (X, Lo(G))).
976 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
977 && "Cannot handle constant offsets yet!");
978 Disp = N.getOperand(1).getOperand(0); // The global address.
979 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
980 Disp.getOpcode() == ISD::TargetConstantPool ||
981 Disp.getOpcode() == ISD::TargetJumpTable);
982 Base = N.getOperand(0);
983 return true; // [&g+r]
985 } else if (N.getOpcode() == ISD::OR) {
987 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
988 // If this is an or of disjoint bitfields, we can codegen this as an add
989 // (for better address arithmetic) if the LHS and RHS of the OR are
990 // provably disjoint.
991 APInt LHSKnownZero, LHSKnownOne;
992 DAG.ComputeMaskedBits(N.getOperand(0),
993 APInt::getAllOnesValue(N.getOperand(0)
994 .getValueSizeInBits()),
995 LHSKnownZero, LHSKnownOne);
996 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
997 // If all of the bits are known zero on the LHS or RHS, the add won't
999 Base = N.getOperand(0);
1000 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1004 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1005 // Loading from a constant address. Verify low two bits are clear.
1006 if ((CN->getZExtValue() & 3) == 0) {
1007 // If this address fits entirely in a 14-bit sext immediate field, codegen
1010 if (isIntS16Immediate(CN, Imm)) {
1011 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1012 Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
1016 // Fold the low-part of 32-bit absolute addresses into addr mode.
1017 if (CN->getValueType(0) == MVT::i32 ||
1018 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1019 int Addr = (int)CN->getZExtValue();
1021 // Otherwise, break this down into an LIS + disp.
1022 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1023 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1024 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1025 Base = SDValue(DAG.getTargetNode(Opc, dl, CN->getValueType(0), Base),0);
1031 Disp = DAG.getTargetConstant(0, getPointerTy());
1032 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1033 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1036 return true; // [r+0]
1040 /// getPreIndexedAddressParts - returns true by value, base pointer and
1041 /// offset pointer and addressing mode by reference if the node's address
1042 /// can be legally represented as pre-indexed load / store address.
1043 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1045 ISD::MemIndexedMode &AM,
1046 SelectionDAG &DAG) const {
1047 // Disabled by default for now.
1048 if (!EnablePPCPreinc) return false;
1052 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1053 Ptr = LD->getBasePtr();
1054 VT = LD->getMemoryVT();
1056 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1058 Ptr = ST->getBasePtr();
1059 VT = ST->getMemoryVT();
1063 // PowerPC doesn't have preinc load/store instructions for vectors.
1067 // TODO: Check reg+reg first.
1069 // LDU/STU use reg+imm*4, others use reg+imm.
1070 if (VT != MVT::i64) {
1072 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1076 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1080 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1081 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1082 // sext i32 to i64 when addr mode is r+i.
1083 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1084 LD->getExtensionType() == ISD::SEXTLOAD &&
1085 isa<ConstantSDNode>(Offset))
1093 //===----------------------------------------------------------------------===//
1094 // LowerOperation implementation
1095 //===----------------------------------------------------------------------===//
1097 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1098 SelectionDAG &DAG) {
1099 MVT PtrVT = Op.getValueType();
1100 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1101 Constant *C = CP->getConstVal();
1102 SDValue CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
1103 SDValue Zero = DAG.getConstant(0, PtrVT);
1104 // FIXME there isn't really any debug info here
1105 DebugLoc dl = Op.getDebugLoc();
1107 const TargetMachine &TM = DAG.getTarget();
1109 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, CPI, Zero);
1110 SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, CPI, Zero);
1112 // If this is a non-darwin platform, we don't support non-static relo models
1114 if (TM.getRelocationModel() == Reloc::Static ||
1115 !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1116 // Generate non-pic code that has direct accesses to the constant pool.
1117 // The address of the global is just (hi(&g)+lo(&g)).
1118 return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1121 if (TM.getRelocationModel() == Reloc::PIC_) {
1122 // With PIC, the first instruction is actually "GR+hi(&G)".
1123 Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1124 DAG.getNode(PPCISD::GlobalBaseReg,
1125 DebugLoc::getUnknownLoc(), PtrVT), Hi);
1128 Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1132 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
1133 MVT PtrVT = Op.getValueType();
1134 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1135 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1136 SDValue Zero = DAG.getConstant(0, PtrVT);
1137 // FIXME there isn't really any debug loc here
1138 DebugLoc dl = Op.getDebugLoc();
1140 const TargetMachine &TM = DAG.getTarget();
1142 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, JTI, Zero);
1143 SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, JTI, Zero);
1145 // If this is a non-darwin platform, we don't support non-static relo models
1147 if (TM.getRelocationModel() == Reloc::Static ||
1148 !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1149 // Generate non-pic code that has direct accesses to the constant pool.
1150 // The address of the global is just (hi(&g)+lo(&g)).
1151 return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1154 if (TM.getRelocationModel() == Reloc::PIC_) {
1155 // With PIC, the first instruction is actually "GR+hi(&G)".
1156 Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1157 DAG.getNode(PPCISD::GlobalBaseReg,
1158 DebugLoc::getUnknownLoc(), PtrVT), Hi);
1161 Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1165 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1166 SelectionDAG &DAG) {
1167 llvm_unreachable("TLS not implemented for PPC.");
1168 return SDValue(); // Not reached
1171 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1172 SelectionDAG &DAG) {
1173 MVT PtrVT = Op.getValueType();
1174 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1175 GlobalValue *GV = GSDN->getGlobal();
1176 SDValue GA = DAG.getTargetGlobalAddress(GV, PtrVT, GSDN->getOffset());
1177 SDValue Zero = DAG.getConstant(0, PtrVT);
1178 // FIXME there isn't really any debug info here
1179 DebugLoc dl = GSDN->getDebugLoc();
1181 const TargetMachine &TM = DAG.getTarget();
1183 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, GA, Zero);
1184 SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, GA, Zero);
1186 // If this is a non-darwin platform, we don't support non-static relo models
1188 if (TM.getRelocationModel() == Reloc::Static ||
1189 !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1190 // Generate non-pic code that has direct accesses to globals.
1191 // The address of the global is just (hi(&g)+lo(&g)).
1192 return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1195 if (TM.getRelocationModel() == Reloc::PIC_) {
1196 // With PIC, the first instruction is actually "GR+hi(&G)".
1197 Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1198 DAG.getNode(PPCISD::GlobalBaseReg,
1199 DebugLoc::getUnknownLoc(), PtrVT), Hi);
1202 Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1204 if (!TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV))
1207 // If the global is weak or external, we have to go through the lazy
1209 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Lo, NULL, 0);
1212 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
1213 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1214 DebugLoc dl = Op.getDebugLoc();
1216 // If we're comparing for equality to zero, expose the fact that this is
1217 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1218 // fold the new nodes.
1219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1220 if (C->isNullValue() && CC == ISD::SETEQ) {
1221 MVT VT = Op.getOperand(0).getValueType();
1222 SDValue Zext = Op.getOperand(0);
1223 if (VT.bitsLT(MVT::i32)) {
1225 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1227 unsigned Log2b = Log2_32(VT.getSizeInBits());
1228 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1229 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1230 DAG.getConstant(Log2b, MVT::i32));
1231 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1233 // Leave comparisons against 0 and -1 alone for now, since they're usually
1234 // optimized. FIXME: revisit this when we can custom lower all setcc
1236 if (C->isAllOnesValue() || C->isNullValue())
1240 // If we have an integer seteq/setne, turn it into a compare against zero
1241 // by xor'ing the rhs with the lhs, which is faster than setting a
1242 // condition register, reading it back out, and masking the correct bit. The
1243 // normal approach here uses sub to do this instead of xor. Using xor exposes
1244 // the result to other bit-twiddling opportunities.
1245 MVT LHSVT = Op.getOperand(0).getValueType();
1246 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1247 MVT VT = Op.getValueType();
1248 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1250 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1255 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1256 int VarArgsFrameIndex,
1257 int VarArgsStackOffset,
1258 unsigned VarArgsNumGPR,
1259 unsigned VarArgsNumFPR,
1260 const PPCSubtarget &Subtarget) {
1262 llvm_unreachable("VAARG not yet implemented for the SVR4 ABI!");
1263 return SDValue(); // Not reached
1266 SDValue PPCTargetLowering::LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
1267 SDValue Chain = Op.getOperand(0);
1268 SDValue Trmp = Op.getOperand(1); // trampoline
1269 SDValue FPtr = Op.getOperand(2); // nested function
1270 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1271 DebugLoc dl = Op.getDebugLoc();
1273 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1274 bool isPPC64 = (PtrVT == MVT::i64);
1275 const Type *IntPtrTy =
1276 DAG.getTargetLoweringInfo().getTargetData()->getIntPtrType();
1278 TargetLowering::ArgListTy Args;
1279 TargetLowering::ArgListEntry Entry;
1281 Entry.Ty = IntPtrTy;
1282 Entry.Node = Trmp; Args.push_back(Entry);
1284 // TrampSize == (isPPC64 ? 48 : 40);
1285 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1286 isPPC64 ? MVT::i64 : MVT::i32);
1287 Args.push_back(Entry);
1289 Entry.Node = FPtr; Args.push_back(Entry);
1290 Entry.Node = Nest; Args.push_back(Entry);
1292 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1293 std::pair<SDValue, SDValue> CallResult =
1294 LowerCallTo(Chain, Op.getValueType().getTypeForMVT(),
1295 false, false, false, false, 0, CallingConv::C, false,
1296 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1300 { CallResult.first, CallResult.second };
1302 return DAG.getMergeValues(Ops, 2, dl);
1305 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1306 int VarArgsFrameIndex,
1307 int VarArgsStackOffset,
1308 unsigned VarArgsNumGPR,
1309 unsigned VarArgsNumFPR,
1310 const PPCSubtarget &Subtarget) {
1311 DebugLoc dl = Op.getDebugLoc();
1313 if (Subtarget.isDarwinABI()) {
1314 // vastart just stores the address of the VarArgsFrameIndex slot into the
1315 // memory location argument.
1316 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1317 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1318 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1319 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1322 // For the SVR4 ABI we follow the layout of the va_list struct.
1323 // We suppose the given va_list is already allocated.
1326 // char gpr; /* index into the array of 8 GPRs
1327 // * stored in the register save area
1328 // * gpr=0 corresponds to r3,
1329 // * gpr=1 to r4, etc.
1331 // char fpr; /* index into the array of 8 FPRs
1332 // * stored in the register save area
1333 // * fpr=0 corresponds to f1,
1334 // * fpr=1 to f2, etc.
1336 // char *overflow_arg_area;
1337 // /* location on stack that holds
1338 // * the next overflow argument
1340 // char *reg_save_area;
1341 // /* where r3:r10 and f1:f8 (if saved)
1347 SDValue ArgGPR = DAG.getConstant(VarArgsNumGPR, MVT::i32);
1348 SDValue ArgFPR = DAG.getConstant(VarArgsNumFPR, MVT::i32);
1351 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1353 SDValue StackOffsetFI = DAG.getFrameIndex(VarArgsStackOffset, PtrVT);
1354 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1356 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1357 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1359 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1360 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1362 uint64_t FPROffset = 1;
1363 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1365 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1367 // Store first byte : number of int regs
1368 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1369 Op.getOperand(1), SV, 0, MVT::i8);
1370 uint64_t nextOffset = FPROffset;
1371 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1374 // Store second byte : number of float regs
1375 SDValue secondStore =
1376 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, SV, nextOffset, MVT::i8);
1377 nextOffset += StackOffset;
1378 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1380 // Store second word : arguments given on stack
1381 SDValue thirdStore =
1382 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, SV, nextOffset);
1383 nextOffset += FrameOffset;
1384 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1386 // Store third word : arguments given in registers
1387 return DAG.getStore(thirdStore, dl, FR, nextPtr, SV, nextOffset);
1391 #include "PPCGenCallingConv.inc"
1393 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1394 CCValAssign::LocInfo &LocInfo,
1395 ISD::ArgFlagsTy &ArgFlags,
1400 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1402 CCValAssign::LocInfo &LocInfo,
1403 ISD::ArgFlagsTy &ArgFlags,
1405 static const unsigned ArgRegs[] = {
1406 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1407 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1409 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1411 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1413 // Skip one register if the first unallocated register has an even register
1414 // number and there are still argument registers available which have not been
1415 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1416 // need to skip a register if RegNum is odd.
1417 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1418 State.AllocateReg(ArgRegs[RegNum]);
1421 // Always return false here, as this function only makes sure that the first
1422 // unallocated register has an odd register number and does not actually
1423 // allocate a register for the current argument.
1427 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1429 CCValAssign::LocInfo &LocInfo,
1430 ISD::ArgFlagsTy &ArgFlags,
1432 static const unsigned ArgRegs[] = {
1433 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1437 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1439 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1441 // If there is only one Floating-point register left we need to put both f64
1442 // values of a split ppc_fp128 value on the stack.
1443 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1444 State.AllocateReg(ArgRegs[RegNum]);
1447 // Always return false here, as this function only makes sure that the two f64
1448 // values a ppc_fp128 value is split into are both passed in registers or both
1449 // passed on the stack and does not actually allocate a register for the
1450 // current argument.
1454 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1455 /// depending on which subtarget is selected.
1456 static const unsigned *GetFPR(const PPCSubtarget &Subtarget) {
1457 if (Subtarget.isDarwinABI()) {
1458 static const unsigned FPR[] = {
1459 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1460 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1466 static const unsigned FPR[] = {
1467 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1473 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1475 static unsigned CalculateStackSlotSize(SDValue Arg, ISD::ArgFlagsTy Flags,
1476 unsigned PtrByteSize) {
1477 MVT ArgVT = Arg.getValueType();
1478 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1479 if (Flags.isByVal())
1480 ArgSize = Flags.getByValSize();
1481 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1487 PPCTargetLowering::LowerFORMAL_ARGUMENTS_SVR4(SDValue Op,
1489 int &VarArgsFrameIndex,
1490 int &VarArgsStackOffset,
1491 unsigned &VarArgsNumGPR,
1492 unsigned &VarArgsNumFPR,
1493 const PPCSubtarget &Subtarget) {
1494 // SVR4 ABI Stack Frame Layout:
1495 // +-----------------------------------+
1496 // +--> | Back chain |
1497 // | +-----------------------------------+
1498 // | | Floating-point register save area |
1499 // | +-----------------------------------+
1500 // | | General register save area |
1501 // | +-----------------------------------+
1502 // | | CR save word |
1503 // | +-----------------------------------+
1504 // | | VRSAVE save word |
1505 // | +-----------------------------------+
1506 // | | Alignment padding |
1507 // | +-----------------------------------+
1508 // | | Vector register save area |
1509 // | +-----------------------------------+
1510 // | | Local variable space |
1511 // | +-----------------------------------+
1512 // | | Parameter list area |
1513 // | +-----------------------------------+
1514 // | | LR save word |
1515 // | +-----------------------------------+
1516 // SP--> +--- | Back chain |
1517 // +-----------------------------------+
1520 // System V Application Binary Interface PowerPC Processor Supplement
1521 // AltiVec Technology Programming Interface Manual
1523 MachineFunction &MF = DAG.getMachineFunction();
1524 MachineFrameInfo *MFI = MF.getFrameInfo();
1525 SmallVector<SDValue, 8> ArgValues;
1526 SDValue Root = Op.getOperand(0);
1527 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1528 DebugLoc dl = Op.getDebugLoc();
1530 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1531 // Potential tail calls could cause overwriting of argument stack slots.
1532 unsigned CC = MF.getFunction()->getCallingConv();
1533 bool isImmutable = !(PerformTailCallOpt && (CC==CallingConv::Fast));
1534 unsigned PtrByteSize = 4;
1536 // Assign locations to all of the incoming arguments.
1537 SmallVector<CCValAssign, 16> ArgLocs;
1538 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
1540 // Reserve space for the linkage area on the stack.
1541 CCInfo.AllocateStack(PPCFrameInfo::getLinkageSize(false, false), PtrByteSize);
1543 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_PPC_SVR4);
1545 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1546 CCValAssign &VA = ArgLocs[i];
1548 // Arguments stored in registers.
1549 if (VA.isRegLoc()) {
1550 TargetRegisterClass *RC;
1551 MVT ValVT = VA.getValVT();
1553 switch (ValVT.getSimpleVT()) {
1555 llvm_unreachable("ValVT not supported by FORMAL_ARGUMENTS Lowering");
1557 RC = PPC::GPRCRegisterClass;
1560 RC = PPC::F4RCRegisterClass;
1563 RC = PPC::F8RCRegisterClass;
1569 RC = PPC::VRRCRegisterClass;
1573 // Transform the arguments stored in physical registers into virtual ones.
1574 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1575 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, ValVT);
1577 ArgValues.push_back(ArgValue);
1579 // Argument stored in memory.
1580 assert(VA.isMemLoc());
1582 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1583 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1586 // Create load nodes to retrieve arguments from the stack.
1587 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1588 ArgValues.push_back(DAG.getLoad(VA.getValVT(), dl, Root, FIN, NULL, 0));
1592 // Assign locations to all of the incoming aggregate by value arguments.
1593 // Aggregates passed by value are stored in the local variable space of the
1594 // caller's stack frame, right above the parameter list area.
1595 SmallVector<CCValAssign, 16> ByValArgLocs;
1596 CCState CCByValInfo(CC, isVarArg, getTargetMachine(),
1597 ByValArgLocs, *DAG.getContext());
1599 // Reserve stack space for the allocations in CCInfo.
1600 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1602 CCByValInfo.AnalyzeFormalArguments(Op.getNode(), CC_PPC_SVR4_ByVal);
1604 // Area that is at least reserved in the caller of this function.
1605 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1607 // Set the size that is at least reserved in caller of this function. Tail
1608 // call optimized function's reserved stack space needs to be aligned so that
1609 // taking the difference between two stack areas will result in an aligned
1611 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1614 std::max(MinReservedArea,
1615 PPCFrameInfo::getMinCallFrameSize(false, false));
1617 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
1618 getStackAlignment();
1619 unsigned AlignMask = TargetAlign-1;
1620 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1622 FI->setMinReservedArea(MinReservedArea);
1624 SmallVector<SDValue, 8> MemOps;
1626 // If the function takes variable number of arguments, make a frame index for
1627 // the start of the first vararg value... for expansion of llvm.va_start.
1629 static const unsigned GPArgRegs[] = {
1630 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1631 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1633 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
1635 static const unsigned FPArgRegs[] = {
1636 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1639 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
1641 VarArgsNumGPR = CCInfo.getFirstUnallocated(GPArgRegs, NumGPArgRegs);
1642 VarArgsNumFPR = CCInfo.getFirstUnallocated(FPArgRegs, NumFPArgRegs);
1644 // Make room for NumGPArgRegs and NumFPArgRegs.
1645 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
1646 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
1648 VarArgsStackOffset = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1649 CCInfo.getNextStackOffset());
1651 VarArgsFrameIndex = MFI->CreateStackObject(Depth, 8);
1652 SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1654 // The fixed integer arguments of a variadic function are
1655 // stored to the VarArgsFrameIndex on the stack.
1656 unsigned GPRIndex = 0;
1657 for (; GPRIndex != VarArgsNumGPR; ++GPRIndex) {
1658 SDValue Val = DAG.getRegister(GPArgRegs[GPRIndex], PtrVT);
1659 SDValue Store = DAG.getStore(Root, dl, Val, FIN, NULL, 0);
1660 MemOps.push_back(Store);
1661 // Increment the address by four for the next argument to store
1662 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1663 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1666 // If this function is vararg, store any remaining integer argument regs
1667 // to their spots on the stack so that they may be loaded by deferencing the
1668 // result of va_next.
1669 for (; GPRIndex != NumGPArgRegs; ++GPRIndex) {
1670 unsigned VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
1672 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1673 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1674 MemOps.push_back(Store);
1675 // Increment the address by four for the next argument to store
1676 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1677 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1680 // FIXME SVR4: We only need to save FP argument registers if CR bit 6 is
1683 // The double arguments are stored to the VarArgsFrameIndex
1685 unsigned FPRIndex = 0;
1686 for (FPRIndex = 0; FPRIndex != VarArgsNumFPR; ++FPRIndex) {
1687 SDValue Val = DAG.getRegister(FPArgRegs[FPRIndex], MVT::f64);
1688 SDValue Store = DAG.getStore(Root, dl, Val, FIN, NULL, 0);
1689 MemOps.push_back(Store);
1690 // Increment the address by eight for the next argument to store
1691 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
1693 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1696 for (; FPRIndex != NumFPArgRegs; ++FPRIndex) {
1697 unsigned VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
1699 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::f64);
1700 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1701 MemOps.push_back(Store);
1702 // Increment the address by eight for the next argument to store
1703 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
1705 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1709 if (!MemOps.empty())
1710 Root = DAG.getNode(ISD::TokenFactor, dl,
1711 MVT::Other, &MemOps[0], MemOps.size());
1714 ArgValues.push_back(Root);
1716 // Return the new list of results.
1717 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1718 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1722 PPCTargetLowering::LowerFORMAL_ARGUMENTS_Darwin(SDValue Op,
1724 int &VarArgsFrameIndex,
1725 const PPCSubtarget &Subtarget) {
1726 // TODO: add description of PPC stack frame format, or at least some docs.
1728 MachineFunction &MF = DAG.getMachineFunction();
1729 MachineFrameInfo *MFI = MF.getFrameInfo();
1730 SmallVector<SDValue, 8> ArgValues;
1731 SDValue Root = Op.getOperand(0);
1732 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1733 DebugLoc dl = Op.getDebugLoc();
1735 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1736 bool isPPC64 = PtrVT == MVT::i64;
1737 // Potential tail calls could cause overwriting of argument stack slots.
1738 unsigned CC = MF.getFunction()->getCallingConv();
1739 bool isImmutable = !(PerformTailCallOpt && (CC==CallingConv::Fast));
1740 unsigned PtrByteSize = isPPC64 ? 8 : 4;
1742 unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, true);
1743 // Area that is at least reserved in caller of this function.
1744 unsigned MinReservedArea = ArgOffset;
1746 static const unsigned GPR_32[] = { // 32-bit registers.
1747 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1748 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1750 static const unsigned GPR_64[] = { // 64-bit registers.
1751 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1752 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1755 static const unsigned *FPR = GetFPR(Subtarget);
1757 static const unsigned VR[] = {
1758 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1759 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1762 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
1763 const unsigned Num_FPR_Regs = 13;
1764 const unsigned Num_VR_Regs = array_lengthof( VR);
1766 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1768 const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1770 // In 32-bit non-varargs functions, the stack space for vectors is after the
1771 // stack space for non-vectors. We do not use this space unless we have
1772 // too many vectors to fit in registers, something that only occurs in
1773 // constructed examples:), but we have to walk the arglist to figure
1774 // that out...for the pathological case, compute VecArgOffset as the
1775 // start of the vector parameter area. Computing VecArgOffset is the
1776 // entire point of the following loop.
1777 unsigned VecArgOffset = ArgOffset;
1778 if (!isVarArg && !isPPC64) {
1779 for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues()-1; ArgNo != e;
1781 MVT ObjectVT = Op.getValue(ArgNo).getValueType();
1782 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
1783 ISD::ArgFlagsTy Flags =
1784 cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1786 if (Flags.isByVal()) {
1787 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
1788 ObjSize = Flags.getByValSize();
1790 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1791 VecArgOffset += ArgSize;
1795 switch(ObjectVT.getSimpleVT()) {
1796 default: llvm_unreachable("Unhandled argument type!");
1799 VecArgOffset += isPPC64 ? 8 : 4;
1801 case MVT::i64: // PPC64
1809 // Nothing to do, we're only looking at Nonvector args here.
1814 // We've found where the vector parameter area in memory is. Skip the
1815 // first 12 parameters; these don't use that memory.
1816 VecArgOffset = ((VecArgOffset+15)/16)*16;
1817 VecArgOffset += 12*16;
1819 // Add DAG nodes to load the arguments or copy them out of registers. On
1820 // entry to a function on PPC, the arguments start after the linkage area,
1821 // although the first ones are often in registers.
1823 SmallVector<SDValue, 8> MemOps;
1824 unsigned nAltivecParamsAtEnd = 0;
1825 for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues() - 1;
1826 ArgNo != e; ++ArgNo) {
1828 bool needsLoad = false;
1829 MVT ObjectVT = Op.getValue(ArgNo).getValueType();
1830 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
1831 unsigned ArgSize = ObjSize;
1832 ISD::ArgFlagsTy Flags =
1833 cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1835 unsigned CurArgOffset = ArgOffset;
1837 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
1838 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
1839 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
1840 if (isVarArg || isPPC64) {
1841 MinReservedArea = ((MinReservedArea+15)/16)*16;
1842 MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
1845 } else nAltivecParamsAtEnd++;
1847 // Calculate min reserved area.
1848 MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
1852 // FIXME the codegen can be much improved in some cases.
1853 // We do not have to keep everything in memory.
1854 if (Flags.isByVal()) {
1855 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
1856 ObjSize = Flags.getByValSize();
1857 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1858 // Objects of size 1 and 2 are right justified, everything else is
1859 // left justified. This means the memory address is adjusted forwards.
1860 if (ObjSize==1 || ObjSize==2) {
1861 CurArgOffset = CurArgOffset + (4 - ObjSize);
1863 // The value of the object is its address.
1864 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset);
1865 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1866 ArgValues.push_back(FIN);
1867 if (ObjSize==1 || ObjSize==2) {
1868 if (GPR_idx != Num_GPR_Regs) {
1869 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
1870 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1871 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
1872 NULL, 0, ObjSize==1 ? MVT::i8 : MVT::i16 );
1873 MemOps.push_back(Store);
1877 ArgOffset += PtrByteSize;
1881 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
1882 // Store whatever pieces of the object are in registers
1883 // to memory. ArgVal will be address of the beginning of
1885 if (GPR_idx != Num_GPR_Regs) {
1886 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
1887 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset);
1888 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1889 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1890 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1891 MemOps.push_back(Store);
1893 ArgOffset += PtrByteSize;
1895 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
1902 switch (ObjectVT.getSimpleVT()) {
1903 default: llvm_unreachable("Unhandled argument type!");
1906 if (GPR_idx != Num_GPR_Regs) {
1907 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
1908 ArgVal = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
1912 ArgSize = PtrByteSize;
1914 // All int arguments reserve stack space in the Darwin ABI.
1915 ArgOffset += PtrByteSize;
1919 case MVT::i64: // PPC64
1920 if (GPR_idx != Num_GPR_Regs) {
1921 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
1922 ArgVal = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1924 if (ObjectVT == MVT::i32) {
1925 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
1926 // value to MVT::i64 and then truncate to the correct register size.
1928 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
1929 DAG.getValueType(ObjectVT));
1930 else if (Flags.isZExt())
1931 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
1932 DAG.getValueType(ObjectVT));
1934 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
1940 ArgSize = PtrByteSize;
1942 // All int arguments reserve stack space in the Darwin ABI.
1948 // Every 4 bytes of argument space consumes one of the GPRs available for
1949 // argument passing.
1950 if (GPR_idx != Num_GPR_Regs) {
1952 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
1955 if (FPR_idx != Num_FPR_Regs) {
1958 if (ObjectVT == MVT::f32)
1959 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
1961 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
1963 ArgVal = DAG.getCopyFromReg(Root, dl, VReg, ObjectVT);
1969 // All FP arguments reserve stack space in the Darwin ABI.
1970 ArgOffset += isPPC64 ? 8 : ObjSize;
1976 // Note that vector arguments in registers don't reserve stack space,
1977 // except in varargs functions.
1978 if (VR_idx != Num_VR_Regs) {
1979 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
1980 ArgVal = DAG.getCopyFromReg(Root, dl, VReg, ObjectVT);
1982 while ((ArgOffset % 16) != 0) {
1983 ArgOffset += PtrByteSize;
1984 if (GPR_idx != Num_GPR_Regs)
1988 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs);
1992 if (!isVarArg && !isPPC64) {
1993 // Vectors go after all the nonvectors.
1994 CurArgOffset = VecArgOffset;
1997 // Vectors are aligned.
1998 ArgOffset = ((ArgOffset+15)/16)*16;
1999 CurArgOffset = ArgOffset;
2007 // We need to load the argument to a virtual register if we determined above
2008 // that we ran out of physical registers of the appropriate type.
2010 int FI = MFI->CreateFixedObject(ObjSize,
2011 CurArgOffset + (ArgSize - ObjSize),
2013 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2014 ArgVal = DAG.getLoad(ObjectVT, dl, Root, FIN, NULL, 0);
2017 ArgValues.push_back(ArgVal);
2020 // Set the size that is at least reserved in caller of this function. Tail
2021 // call optimized function's reserved stack space needs to be aligned so that
2022 // taking the difference between two stack areas will result in an aligned
2024 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2025 // Add the Altivec parameters at the end, if needed.
2026 if (nAltivecParamsAtEnd) {
2027 MinReservedArea = ((MinReservedArea+15)/16)*16;
2028 MinReservedArea += 16*nAltivecParamsAtEnd;
2031 std::max(MinReservedArea,
2032 PPCFrameInfo::getMinCallFrameSize(isPPC64, true));
2033 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
2034 getStackAlignment();
2035 unsigned AlignMask = TargetAlign-1;
2036 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2037 FI->setMinReservedArea(MinReservedArea);
2039 // If the function takes variable number of arguments, make a frame index for
2040 // the start of the first vararg value... for expansion of llvm.va_start.
2042 int Depth = ArgOffset;
2044 VarArgsFrameIndex = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2046 SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
2048 // If this function is vararg, store any remaining integer argument regs
2049 // to their spots on the stack so that they may be loaded by deferencing the
2050 // result of va_next.
2051 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2055 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2057 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2059 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
2060 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
2061 MemOps.push_back(Store);
2062 // Increment the address by four for the next argument to store
2063 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2064 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2068 if (!MemOps.empty())
2069 Root = DAG.getNode(ISD::TokenFactor, dl,
2070 MVT::Other, &MemOps[0], MemOps.size());
2072 ArgValues.push_back(Root);
2074 // Return the new list of results.
2075 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
2076 &ArgValues[0], ArgValues.size());
2079 /// CalculateParameterAndLinkageAreaSize - Get the size of the paramter plus
2080 /// linkage area for the Darwin ABI.
2082 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2086 CallSDNode *TheCall,
2087 unsigned &nAltivecParamsAtEnd) {
2088 // Count how many bytes are to be pushed on the stack, including the linkage
2089 // area, and parameter passing area. We start with 24/48 bytes, which is
2090 // prereserved space for [SP][CR][LR][3 x unused].
2091 unsigned NumBytes = PPCFrameInfo::getLinkageSize(isPPC64, true);
2092 unsigned NumOps = TheCall->getNumArgs();
2093 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2095 // Add up all the space actually used.
2096 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2097 // they all go in registers, but we must reserve stack space for them for
2098 // possible use by the caller. In varargs or 64-bit calls, parameters are
2099 // assigned stack space in order, with padding so Altivec parameters are
2101 nAltivecParamsAtEnd = 0;
2102 for (unsigned i = 0; i != NumOps; ++i) {
2103 SDValue Arg = TheCall->getArg(i);
2104 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
2105 MVT ArgVT = Arg.getValueType();
2106 // Varargs Altivec parameters are padded to a 16 byte boundary.
2107 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2108 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2109 if (!isVarArg && !isPPC64) {
2110 // Non-varargs Altivec parameters go after all the non-Altivec
2111 // parameters; handle those later so we know how much padding we need.
2112 nAltivecParamsAtEnd++;
2115 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2116 NumBytes = ((NumBytes+15)/16)*16;
2118 NumBytes += CalculateStackSlotSize(Arg, Flags, PtrByteSize);
2121 // Allow for Altivec parameters at the end, if needed.
2122 if (nAltivecParamsAtEnd) {
2123 NumBytes = ((NumBytes+15)/16)*16;
2124 NumBytes += 16*nAltivecParamsAtEnd;
2127 // The prolog code of the callee may store up to 8 GPR argument registers to
2128 // the stack, allowing va_start to index over them in memory if its varargs.
2129 // Because we cannot tell if this is needed on the caller side, we have to
2130 // conservatively assume that it is needed. As such, make sure we have at
2131 // least enough stack space for the caller to store the 8 GPRs.
2132 NumBytes = std::max(NumBytes,
2133 PPCFrameInfo::getMinCallFrameSize(isPPC64, true));
2135 // Tail call needs the stack to be aligned.
2136 if (CC==CallingConv::Fast && PerformTailCallOpt) {
2137 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
2138 getStackAlignment();
2139 unsigned AlignMask = TargetAlign-1;
2140 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2146 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2147 /// adjusted to accomodate the arguments for the tailcall.
2148 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool IsTailCall,
2149 unsigned ParamSize) {
2151 if (!IsTailCall) return 0;
2153 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2154 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2155 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2156 // Remember only if the new adjustement is bigger.
2157 if (SPDiff < FI->getTailCallSPDelta())
2158 FI->setTailCallSPDelta(SPDiff);
2163 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
2164 /// following the call is a return. A function is eligible if caller/callee
2165 /// calling conventions match, currently only fastcc supports tail calls, and
2166 /// the function CALL is immediatly followed by a RET.
2168 PPCTargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
2170 SelectionDAG& DAG) const {
2171 // Variable argument functions are not supported.
2172 if (!PerformTailCallOpt || TheCall->isVarArg())
2175 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
2176 MachineFunction &MF = DAG.getMachineFunction();
2177 unsigned CallerCC = MF.getFunction()->getCallingConv();
2178 unsigned CalleeCC = TheCall->getCallingConv();
2179 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2180 // Functions containing by val parameters are not supported.
2181 for (unsigned i = 0; i != TheCall->getNumArgs(); i++) {
2182 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
2183 if (Flags.isByVal()) return false;
2186 SDValue Callee = TheCall->getCallee();
2187 // Non PIC/GOT tail calls are supported.
2188 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2191 // At the moment we can only do local tail calls (in same module, hidden
2192 // or protected) if we are generating PIC.
2193 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2194 return G->getGlobal()->hasHiddenVisibility()
2195 || G->getGlobal()->hasProtectedVisibility();
2202 /// isCallCompatibleAddress - Return the immediate to use if the specified
2203 /// 32-bit value is representable in the immediate field of a BxA instruction.
2204 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2205 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2208 int Addr = C->getZExtValue();
2209 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2210 (Addr << 6 >> 6) != Addr)
2211 return 0; // Top 6 bits have to be sext of immediate.
2213 return DAG.getConstant((int)C->getZExtValue() >> 2,
2214 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2219 struct TailCallArgumentInfo {
2224 TailCallArgumentInfo() : FrameIdx(0) {}
2229 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2231 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2233 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2234 SmallVector<SDValue, 8> &MemOpChains,
2236 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2237 SDValue Arg = TailCallArgs[i].Arg;
2238 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2239 int FI = TailCallArgs[i].FrameIdx;
2240 // Store relative to framepointer.
2241 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2242 PseudoSourceValue::getFixedStack(FI),
2247 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2248 /// the appropriate stack slot for the tail call optimized function call.
2249 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2250 MachineFunction &MF,
2259 // Calculate the new stack slot for the return address.
2260 int SlotSize = isPPC64 ? 8 : 4;
2261 int NewRetAddrLoc = SPDiff + PPCFrameInfo::getReturnSaveOffset(isPPC64,
2263 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2265 MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2266 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2267 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2268 PseudoSourceValue::getFixedStack(NewRetAddr), 0);
2270 // When using the SVR4 ABI there is no need to move the FP stack slot
2271 // as the FP is never overwritten.
2274 SPDiff + PPCFrameInfo::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2275 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc);
2276 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2277 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2278 PseudoSourceValue::getFixedStack(NewFPIdx), 0);
2284 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2285 /// the position of the argument.
2287 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2288 SDValue Arg, int SPDiff, unsigned ArgOffset,
2289 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2290 int Offset = ArgOffset + SPDiff;
2291 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2292 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
2293 MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2294 SDValue FIN = DAG.getFrameIndex(FI, VT);
2295 TailCallArgumentInfo Info;
2297 Info.FrameIdxOp = FIN;
2299 TailCallArguments.push_back(Info);
2302 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2303 /// stack slot. Returns the chain as result and the loaded frame pointers in
2304 /// LROpOut/FPOpout. Used when tail calling.
2305 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2313 // Load the LR and FP stack slot for later adjusting.
2314 MVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2315 LROpOut = getReturnAddrFrameIndex(DAG);
2316 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, NULL, 0);
2317 Chain = SDValue(LROpOut.getNode(), 1);
2319 // When using the SVR4 ABI there is no need to load the FP stack slot
2320 // as the FP is never overwritten.
2322 FPOpOut = getFramePointerFrameIndex(DAG);
2323 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, NULL, 0);
2324 Chain = SDValue(FPOpOut.getNode(), 1);
2330 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2331 /// by "Src" to address "Dst" of size "Size". Alignment information is
2332 /// specified by the specific parameter attribute. The copy will be passed as
2333 /// a byval function parameter.
2334 /// Sometimes what we are copying is the end of a larger object, the part that
2335 /// does not fit in registers.
2337 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2338 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2340 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2341 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2342 false, NULL, 0, NULL, 0);
2345 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
2348 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
2349 SDValue Arg, SDValue PtrOff, int SPDiff,
2350 unsigned ArgOffset, bool isPPC64, bool isTailCall,
2351 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
2352 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments,
2354 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2359 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2361 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2362 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2363 DAG.getConstant(ArgOffset, PtrVT));
2365 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
2366 // Calculate and remember argument location.
2367 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
2372 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
2373 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
2374 SDValue LROp, SDValue FPOp, bool isDarwinABI,
2375 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
2376 MachineFunction &MF = DAG.getMachineFunction();
2378 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
2379 // might overwrite each other in case of tail call optimization.
2380 SmallVector<SDValue, 8> MemOpChains2;
2381 // Do not flag preceeding copytoreg stuff together with the following stuff.
2383 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
2385 if (!MemOpChains2.empty())
2386 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2387 &MemOpChains2[0], MemOpChains2.size());
2389 // Store the return address to the appropriate stack slot.
2390 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
2391 isPPC64, isDarwinABI, dl);
2393 // Emit callseq_end just before tailcall node.
2394 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2395 DAG.getIntPtrConstant(0, true), InFlag);
2396 InFlag = Chain.getValue(1);
2400 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
2401 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
2402 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
2403 SmallVector<SDValue, 8> &Ops, std::vector<MVT> &NodeTys,
2405 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2406 NodeTys.push_back(MVT::Other); // Returns a chain
2407 NodeTys.push_back(MVT::Flag); // Returns a flag for retval copy to use.
2409 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin;
2411 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2412 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2413 // node so that legalize doesn't hack it.
2414 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2415 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
2416 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
2417 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
2418 else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
2419 // If this is an absolute destination address, use the munged value.
2420 Callee = SDValue(Dest, 0);
2422 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
2423 // to do the call, we can't use PPCISD::CALL.
2424 SDValue MTCTROps[] = {Chain, Callee, InFlag};
2425 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
2426 2 + (InFlag.getNode() != 0));
2427 InFlag = Chain.getValue(1);
2430 NodeTys.push_back(MVT::Other);
2431 NodeTys.push_back(MVT::Flag);
2432 Ops.push_back(Chain);
2433 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin;
2435 // Add CTR register as callee so a bctr can be emitted later.
2437 Ops.push_back(DAG.getRegister(PPC::CTR, PtrVT));
2440 // If this is a direct call, pass the chain and the callee.
2441 if (Callee.getNode()) {
2442 Ops.push_back(Chain);
2443 Ops.push_back(Callee);
2445 // If this is a tail call add stack pointer delta.
2447 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
2449 // Add argument registers to the end of the list so that they are known live
2451 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2452 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2453 RegsToPass[i].second.getValueType()));
2458 static SDValue LowerCallReturn(SDValue Op, SelectionDAG &DAG, TargetMachine &TM,
2459 CallSDNode *TheCall, SDValue Chain,
2461 bool isVarArg = TheCall->isVarArg();
2462 DebugLoc dl = TheCall->getDebugLoc();
2463 SmallVector<SDValue, 16> ResultVals;
2464 SmallVector<CCValAssign, 16> RVLocs;
2465 unsigned CallerCC = DAG.getMachineFunction().getFunction()->getCallingConv();
2466 CCState CCRetInfo(CallerCC, isVarArg, TM, RVLocs, *DAG.getContext());
2467 CCRetInfo.AnalyzeCallResult(TheCall, RetCC_PPC);
2469 // Copy all of the result registers out of their specified physreg.
2470 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2471 CCValAssign &VA = RVLocs[i];
2472 MVT VT = VA.getValVT();
2473 assert(VA.isRegLoc() && "Can only return in registers!");
2474 Chain = DAG.getCopyFromReg(Chain, dl,
2475 VA.getLocReg(), VT, InFlag).getValue(1);
2476 ResultVals.push_back(Chain.getValue(0));
2477 InFlag = Chain.getValue(2);
2480 // If the function returns void, just return the chain.
2484 // Otherwise, merge everything together with a MERGE_VALUES node.
2485 ResultVals.push_back(Chain);
2486 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
2487 &ResultVals[0], ResultVals.size());
2488 return Res.getValue(Op.getResNo());
2492 SDValue FinishCall(SelectionDAG &DAG, CallSDNode *TheCall, TargetMachine &TM,
2493 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
2494 SDValue Op, SDValue InFlag, SDValue Chain, SDValue &Callee,
2495 int SPDiff, unsigned NumBytes) {
2496 unsigned CC = TheCall->getCallingConv();
2497 DebugLoc dl = TheCall->getDebugLoc();
2498 bool isTailCall = TheCall->isTailCall()
2499 && CC == CallingConv::Fast && PerformTailCallOpt;
2501 std::vector<MVT> NodeTys;
2502 SmallVector<SDValue, 8> Ops;
2503 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
2504 isTailCall, RegsToPass, Ops, NodeTys,
2505 TM.getSubtarget<PPCSubtarget>().isSVR4ABI());
2507 // When performing tail call optimization the callee pops its arguments off
2508 // the stack. Account for this here so these bytes can be pushed back on in
2509 // PPCRegisterInfo::eliminateCallFramePseudoInstr.
2510 int BytesCalleePops =
2511 (CC==CallingConv::Fast && PerformTailCallOpt) ? NumBytes : 0;
2513 if (InFlag.getNode())
2514 Ops.push_back(InFlag);
2518 assert(InFlag.getNode() &&
2519 "Flag must be set. Depend on flag being set in LowerRET");
2520 Chain = DAG.getNode(PPCISD::TAILCALL, dl,
2521 TheCall->getVTList(), &Ops[0], Ops.size());
2522 return SDValue(Chain.getNode(), Op.getResNo());
2525 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
2526 InFlag = Chain.getValue(1);
2528 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2529 DAG.getIntPtrConstant(BytesCalleePops, true),
2531 if (TheCall->getValueType(0) != MVT::Other)
2532 InFlag = Chain.getValue(1);
2534 return LowerCallReturn(Op, DAG, TM, TheCall, Chain, InFlag);
2537 SDValue PPCTargetLowering::LowerCALL_SVR4(SDValue Op, SelectionDAG &DAG,
2538 const PPCSubtarget &Subtarget,
2539 TargetMachine &TM) {
2540 // See PPCTargetLowering::LowerFORMAL_ARGUMENTS_SVR4() for a description
2541 // of the SVR4 ABI stack frame layout.
2542 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
2543 SDValue Chain = TheCall->getChain();
2544 bool isVarArg = TheCall->isVarArg();
2545 unsigned CC = TheCall->getCallingConv();
2546 assert((CC == CallingConv::C ||
2547 CC == CallingConv::Fast) && "Unknown calling convention!");
2548 bool isTailCall = TheCall->isTailCall()
2549 && CC == CallingConv::Fast && PerformTailCallOpt;
2550 SDValue Callee = TheCall->getCallee();
2551 DebugLoc dl = TheCall->getDebugLoc();
2553 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2554 unsigned PtrByteSize = 4;
2556 MachineFunction &MF = DAG.getMachineFunction();
2558 // Mark this function as potentially containing a function that contains a
2559 // tail call. As a consequence the frame pointer will be used for dynamicalloc
2560 // and restoring the callers stack pointer in this functions epilog. This is
2561 // done because by tail calling the called function might overwrite the value
2562 // in this function's (MF) stack pointer stack slot 0(SP).
2563 if (PerformTailCallOpt && CC==CallingConv::Fast)
2564 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
2566 // Count how many bytes are to be pushed on the stack, including the linkage
2567 // area, parameter list area and the part of the local variable space which
2568 // contains copies of aggregates which are passed by value.
2570 // Assign locations to all of the outgoing arguments.
2571 SmallVector<CCValAssign, 16> ArgLocs;
2572 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
2574 // Reserve space for the linkage area on the stack.
2575 CCInfo.AllocateStack(PPCFrameInfo::getLinkageSize(false, false), PtrByteSize);
2578 // Handle fixed and variable vector arguments differently.
2579 // Fixed vector arguments go into registers as long as registers are
2580 // available. Variable vector arguments always go into memory.
2581 unsigned NumArgs = TheCall->getNumArgs();
2582 unsigned NumFixedArgs = TheCall->getNumFixedArgs();
2584 for (unsigned i = 0; i != NumArgs; ++i) {
2585 MVT ArgVT = TheCall->getArg(i).getValueType();
2586 ISD::ArgFlagsTy ArgFlags = TheCall->getArgFlags(i);
2589 if (i < NumFixedArgs) {
2590 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
2593 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
2599 cerr << "Call operand #" << i << " has unhandled type "
2600 << ArgVT.getMVTString() << "\n";
2602 llvm_unreachable(0);
2606 // All arguments are treated the same.
2607 CCInfo.AnalyzeCallOperands(TheCall, CC_PPC_SVR4);
2610 // Assign locations to all of the outgoing aggregate by value arguments.
2611 SmallVector<CCValAssign, 16> ByValArgLocs;
2612 CCState CCByValInfo(CC, isVarArg, getTargetMachine(), ByValArgLocs,
2615 // Reserve stack space for the allocations in CCInfo.
2616 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2618 CCByValInfo.AnalyzeCallOperands(TheCall, CC_PPC_SVR4_ByVal);
2620 // Size of the linkage area, parameter list area and the part of the local
2621 // space variable where copies of aggregates which are passed by value are
2623 unsigned NumBytes = CCByValInfo.getNextStackOffset();
2625 // Calculate by how many bytes the stack has to be adjusted in case of tail
2626 // call optimization.
2627 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
2629 // Adjust the stack pointer for the new arguments...
2630 // These operations are automatically eliminated by the prolog/epilog pass
2631 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2632 SDValue CallSeqStart = Chain;
2634 // Load the return address and frame pointer so it can be moved somewhere else
2637 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
2640 // Set up a copy of the stack pointer for use loading and storing any
2641 // arguments that may not fit in the registers available for argument
2643 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2645 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2646 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
2647 SmallVector<SDValue, 8> MemOpChains;
2649 // Walk the register/memloc assignments, inserting copies/loads.
2650 for (unsigned i = 0, j = 0, e = ArgLocs.size();
2653 CCValAssign &VA = ArgLocs[i];
2654 SDValue Arg = TheCall->getArg(i);
2655 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
2657 if (Flags.isByVal()) {
2658 // Argument is an aggregate which is passed by value, thus we need to
2659 // create a copy of it in the local variable space of the current stack
2660 // frame (which is the stack frame of the caller) and pass the address of
2661 // this copy to the callee.
2662 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
2663 CCValAssign &ByValVA = ByValArgLocs[j++];
2664 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
2666 // Memory reserved in the local variable space of the callers stack frame.
2667 unsigned LocMemOffset = ByValVA.getLocMemOffset();
2669 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2670 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2672 // Create a copy of the argument in the local area of the current
2674 SDValue MemcpyCall =
2675 CreateCopyOfByValArgument(Arg, PtrOff,
2676 CallSeqStart.getNode()->getOperand(0),
2679 // This must go outside the CALLSEQ_START..END.
2680 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2681 CallSeqStart.getNode()->getOperand(1));
2682 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
2683 NewCallSeqStart.getNode());
2684 Chain = CallSeqStart = NewCallSeqStart;
2686 // Pass the address of the aggregate copy on the stack either in a
2687 // physical register or in the parameter list area of the current stack
2688 // frame to the callee.
2692 if (VA.isRegLoc()) {
2693 // Put argument in a physical register.
2694 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2696 // Put argument in the parameter list area of the current stack frame.
2697 assert(VA.isMemLoc());
2698 unsigned LocMemOffset = VA.getLocMemOffset();
2701 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2702 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2704 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2705 PseudoSourceValue::getStack(), LocMemOffset));
2707 // Calculate and remember argument location.
2708 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
2714 if (!MemOpChains.empty())
2715 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2716 &MemOpChains[0], MemOpChains.size());
2718 // Build a sequence of copy-to-reg nodes chained together with token chain
2719 // and flag operands which copy the outgoing args into the appropriate regs.
2721 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2722 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2723 RegsToPass[i].second, InFlag);
2724 InFlag = Chain.getValue(1);
2727 // Set CR6 to true if this is a vararg call.
2729 SDValue SetCR(DAG.getTargetNode(PPC::CRSET, dl, MVT::i32), 0);
2730 Chain = DAG.getCopyToReg(Chain, dl, PPC::CR1EQ, SetCR, InFlag);
2731 InFlag = Chain.getValue(1);
2735 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
2736 false, TailCallArguments);
2739 return FinishCall(DAG, TheCall, TM, RegsToPass, Op, InFlag, Chain, Callee,
2743 SDValue PPCTargetLowering::LowerCALL_Darwin(SDValue Op, SelectionDAG &DAG,
2744 const PPCSubtarget &Subtarget,
2745 TargetMachine &TM) {
2746 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
2747 SDValue Chain = TheCall->getChain();
2748 bool isVarArg = TheCall->isVarArg();
2749 unsigned CC = TheCall->getCallingConv();
2750 bool isTailCall = TheCall->isTailCall()
2751 && CC == CallingConv::Fast && PerformTailCallOpt;
2752 SDValue Callee = TheCall->getCallee();
2753 unsigned NumOps = TheCall->getNumArgs();
2754 DebugLoc dl = TheCall->getDebugLoc();
2756 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2757 bool isPPC64 = PtrVT == MVT::i64;
2758 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2760 MachineFunction &MF = DAG.getMachineFunction();
2762 // Mark this function as potentially containing a function that contains a
2763 // tail call. As a consequence the frame pointer will be used for dynamicalloc
2764 // and restoring the callers stack pointer in this functions epilog. This is
2765 // done because by tail calling the called function might overwrite the value
2766 // in this function's (MF) stack pointer stack slot 0(SP).
2767 if (PerformTailCallOpt && CC==CallingConv::Fast)
2768 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
2770 unsigned nAltivecParamsAtEnd = 0;
2772 // Count how many bytes are to be pushed on the stack, including the linkage
2773 // area, and parameter passing area. We start with 24/48 bytes, which is
2774 // prereserved space for [SP][CR][LR][3 x unused].
2776 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CC, TheCall,
2777 nAltivecParamsAtEnd);
2779 // Calculate by how many bytes the stack has to be adjusted in case of tail
2780 // call optimization.
2781 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
2783 // Adjust the stack pointer for the new arguments...
2784 // These operations are automatically eliminated by the prolog/epilog pass
2785 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2786 SDValue CallSeqStart = Chain;
2788 // Load the return address and frame pointer so it can be move somewhere else
2791 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
2794 // Set up a copy of the stack pointer for use loading and storing any
2795 // arguments that may not fit in the registers available for argument
2799 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2801 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2803 // Figure out which arguments are going to go in registers, and which in
2804 // memory. Also, if this is a vararg function, floating point operations
2805 // must be stored to our stack, and loaded into integer regs as well, if
2806 // any integer regs are available for argument passing.
2807 unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, true);
2808 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2810 static const unsigned GPR_32[] = { // 32-bit registers.
2811 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2812 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2814 static const unsigned GPR_64[] = { // 64-bit registers.
2815 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2816 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2818 static const unsigned *FPR = GetFPR(Subtarget);
2820 static const unsigned VR[] = {
2821 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2822 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2824 const unsigned NumGPRs = array_lengthof(GPR_32);
2825 const unsigned NumFPRs = 13;
2826 const unsigned NumVRs = array_lengthof(VR);
2828 const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
2830 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2831 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
2833 SmallVector<SDValue, 8> MemOpChains;
2834 for (unsigned i = 0; i != NumOps; ++i) {
2836 SDValue Arg = TheCall->getArg(i);
2837 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
2839 // PtrOff will be used to store the current argument to the stack if a
2840 // register cannot be found for it.
2843 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
2845 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
2847 // On PPC64, promote integers to 64-bit values.
2848 if (isPPC64 && Arg.getValueType() == MVT::i32) {
2849 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
2850 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2851 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
2854 // FIXME memcpy is used way more than necessary. Correctness first.
2855 if (Flags.isByVal()) {
2856 unsigned Size = Flags.getByValSize();
2857 if (Size==1 || Size==2) {
2858 // Very small objects are passed right-justified.
2859 // Everything else is passed left-justified.
2860 MVT VT = (Size==1) ? MVT::i8 : MVT::i16;
2861 if (GPR_idx != NumGPRs) {
2862 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
2864 MemOpChains.push_back(Load.getValue(1));
2865 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2867 ArgOffset += PtrByteSize;
2869 SDValue Const = DAG.getConstant(4 - Size, PtrOff.getValueType());
2870 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
2871 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr,
2872 CallSeqStart.getNode()->getOperand(0),
2874 // This must go outside the CALLSEQ_START..END.
2875 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2876 CallSeqStart.getNode()->getOperand(1));
2877 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
2878 NewCallSeqStart.getNode());
2879 Chain = CallSeqStart = NewCallSeqStart;
2880 ArgOffset += PtrByteSize;
2884 // Copy entire object into memory. There are cases where gcc-generated
2885 // code assumes it is there, even if it could be put entirely into
2886 // registers. (This is not what the doc says.)
2887 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
2888 CallSeqStart.getNode()->getOperand(0),
2890 // This must go outside the CALLSEQ_START..END.
2891 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2892 CallSeqStart.getNode()->getOperand(1));
2893 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode());
2894 Chain = CallSeqStart = NewCallSeqStart;
2895 // And copy the pieces of it that fit into registers.
2896 for (unsigned j=0; j<Size; j+=PtrByteSize) {
2897 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
2898 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2899 if (GPR_idx != NumGPRs) {
2900 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, NULL, 0);
2901 MemOpChains.push_back(Load.getValue(1));
2902 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2903 ArgOffset += PtrByteSize;
2905 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
2912 switch (Arg.getValueType().getSimpleVT()) {
2913 default: llvm_unreachable("Unexpected ValueType for argument!");
2916 if (GPR_idx != NumGPRs) {
2917 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
2919 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2920 isPPC64, isTailCall, false, MemOpChains,
2921 TailCallArguments, dl);
2924 ArgOffset += PtrByteSize;
2928 if (FPR_idx != NumFPRs) {
2929 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
2932 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0);
2933 MemOpChains.push_back(Store);
2935 // Float varargs are always shadowed in available integer registers
2936 if (GPR_idx != NumGPRs) {
2937 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, NULL, 0);
2938 MemOpChains.push_back(Load.getValue(1));
2939 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2941 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
2942 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
2943 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
2944 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, NULL, 0);
2945 MemOpChains.push_back(Load.getValue(1));
2946 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2949 // If we have any FPRs remaining, we may also have GPRs remaining.
2950 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
2952 if (GPR_idx != NumGPRs)
2954 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
2955 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
2959 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2960 isPPC64, isTailCall, false, MemOpChains,
2961 TailCallArguments, dl);
2967 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
2974 // These go aligned on the stack, or in the corresponding R registers
2975 // when within range. The Darwin PPC ABI doc claims they also go in
2976 // V registers; in fact gcc does this only for arguments that are
2977 // prototyped, not for those that match the ... We do it for all
2978 // arguments, seems to work.
2979 while (ArgOffset % 16 !=0) {
2980 ArgOffset += PtrByteSize;
2981 if (GPR_idx != NumGPRs)
2984 // We could elide this store in the case where the object fits
2985 // entirely in R registers. Maybe later.
2986 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2987 DAG.getConstant(ArgOffset, PtrVT));
2988 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0);
2989 MemOpChains.push_back(Store);
2990 if (VR_idx != NumVRs) {
2991 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, NULL, 0);
2992 MemOpChains.push_back(Load.getValue(1));
2993 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
2996 for (unsigned i=0; i<16; i+=PtrByteSize) {
2997 if (GPR_idx == NumGPRs)
2999 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3000 DAG.getConstant(i, PtrVT));
3001 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, NULL, 0);
3002 MemOpChains.push_back(Load.getValue(1));
3003 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3008 // Non-varargs Altivec params generally go in registers, but have
3009 // stack space allocated at the end.
3010 if (VR_idx != NumVRs) {
3011 // Doesn't have GPR space allocated.
3012 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
3013 } else if (nAltivecParamsAtEnd==0) {
3014 // We are emitting Altivec params in order.
3015 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3016 isPPC64, isTailCall, true, MemOpChains,
3017 TailCallArguments, dl);
3023 // If all Altivec parameters fit in registers, as they usually do,
3024 // they get stack space following the non-Altivec parameters. We
3025 // don't track this here because nobody below needs it.
3026 // If there are more Altivec parameters than fit in registers emit
3028 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
3030 // Offset is aligned; skip 1st 12 params which go in V registers.
3031 ArgOffset = ((ArgOffset+15)/16)*16;
3033 for (unsigned i = 0; i != NumOps; ++i) {
3034 SDValue Arg = TheCall->getArg(i);
3035 MVT ArgType = Arg.getValueType();
3036 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
3037 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
3040 // We are emitting Altivec params in order.
3041 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3042 isPPC64, isTailCall, true, MemOpChains,
3043 TailCallArguments, dl);
3050 if (!MemOpChains.empty())
3051 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3052 &MemOpChains[0], MemOpChains.size());
3054 // Build a sequence of copy-to-reg nodes chained together with token chain
3055 // and flag operands which copy the outgoing args into the appropriate regs.
3057 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3058 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3059 RegsToPass[i].second, InFlag);
3060 InFlag = Chain.getValue(1);
3064 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
3065 FPOp, true, TailCallArguments);
3068 return FinishCall(DAG, TheCall, TM, RegsToPass, Op, InFlag, Chain, Callee,
3072 SDValue PPCTargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG,
3073 TargetMachine &TM) {
3074 SmallVector<CCValAssign, 16> RVLocs;
3075 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
3076 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
3077 DebugLoc dl = Op.getDebugLoc();
3078 CCState CCInfo(CC, isVarArg, TM, RVLocs, *DAG.getContext());
3079 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_PPC);
3081 // If this is the first return lowered for this function, add the regs to the
3082 // liveout set for the function.
3083 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3084 for (unsigned i = 0; i != RVLocs.size(); ++i)
3085 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3088 SDValue Chain = Op.getOperand(0);
3090 Chain = GetPossiblePreceedingTailCall(Chain, PPCISD::TAILCALL);
3091 if (Chain.getOpcode() == PPCISD::TAILCALL) {
3092 SDValue TailCall = Chain;
3093 SDValue TargetAddress = TailCall.getOperand(1);
3094 SDValue StackAdjustment = TailCall.getOperand(2);
3096 assert(((TargetAddress.getOpcode() == ISD::Register &&
3097 cast<RegisterSDNode>(TargetAddress)->getReg() == PPC::CTR) ||
3098 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
3099 TargetAddress.getOpcode() == ISD::TargetGlobalAddress ||
3100 isa<ConstantSDNode>(TargetAddress)) &&
3101 "Expecting an global address, external symbol, absolute value or register");
3103 assert(StackAdjustment.getOpcode() == ISD::Constant &&
3104 "Expecting a const value");
3106 SmallVector<SDValue,8> Operands;
3107 Operands.push_back(Chain.getOperand(0));
3108 Operands.push_back(TargetAddress);
3109 Operands.push_back(StackAdjustment);
3110 // Copy registers used by the call. Last operand is a flag so it is not
3112 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
3113 Operands.push_back(Chain.getOperand(i));
3115 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Operands[0],
3121 // Copy the result values into the output registers.
3122 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3123 CCValAssign &VA = RVLocs[i];
3124 assert(VA.isRegLoc() && "Can only return in registers!");
3125 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3126 Op.getOperand(i*2+1), Flag);
3127 Flag = Chain.getValue(1);
3131 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
3133 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
3136 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
3137 const PPCSubtarget &Subtarget) {
3138 // When we pop the dynamic allocation we need to restore the SP link.
3139 DebugLoc dl = Op.getDebugLoc();
3141 // Get the corect type for pointers.
3142 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3144 // Construct the stack pointer operand.
3145 bool IsPPC64 = Subtarget.isPPC64();
3146 unsigned SP = IsPPC64 ? PPC::X1 : PPC::R1;
3147 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
3149 // Get the operands for the STACKRESTORE.
3150 SDValue Chain = Op.getOperand(0);
3151 SDValue SaveSP = Op.getOperand(1);
3153 // Load the old link SP.
3154 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, NULL, 0);
3156 // Restore the stack pointer.
3157 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
3159 // Store the old link SP.
3160 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, NULL, 0);
3166 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
3167 MachineFunction &MF = DAG.getMachineFunction();
3168 bool IsPPC64 = PPCSubTarget.isPPC64();
3169 bool isDarwinABI = PPCSubTarget.isDarwinABI();
3170 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3172 // Get current frame pointer save index. The users of this index will be
3173 // primarily DYNALLOC instructions.
3174 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
3175 int RASI = FI->getReturnAddrSaveIndex();
3177 // If the frame pointer save index hasn't been defined yet.
3179 // Find out what the fix offset of the frame pointer save area.
3180 int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, isDarwinABI);
3181 // Allocate the frame index for frame pointer save area.
3182 RASI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, LROffset);
3184 FI->setReturnAddrSaveIndex(RASI);
3186 return DAG.getFrameIndex(RASI, PtrVT);
3190 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
3191 MachineFunction &MF = DAG.getMachineFunction();
3192 bool IsPPC64 = PPCSubTarget.isPPC64();
3193 bool isDarwinABI = PPCSubTarget.isDarwinABI();
3194 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3196 // Get current frame pointer save index. The users of this index will be
3197 // primarily DYNALLOC instructions.
3198 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
3199 int FPSI = FI->getFramePointerSaveIndex();
3201 // If the frame pointer save index hasn't been defined yet.
3203 // Find out what the fix offset of the frame pointer save area.
3204 int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64,
3207 // Allocate the frame index for frame pointer save area.
3208 FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
3210 FI->setFramePointerSaveIndex(FPSI);
3212 return DAG.getFrameIndex(FPSI, PtrVT);
3215 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3217 const PPCSubtarget &Subtarget) {
3219 SDValue Chain = Op.getOperand(0);
3220 SDValue Size = Op.getOperand(1);
3221 DebugLoc dl = Op.getDebugLoc();
3223 // Get the corect type for pointers.
3224 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3226 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
3227 DAG.getConstant(0, PtrVT), Size);
3228 // Construct a node for the frame pointer save index.
3229 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
3230 // Build a DYNALLOC node.
3231 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
3232 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
3233 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
3236 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
3238 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
3239 // Not FP? Not a fsel.
3240 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
3241 !Op.getOperand(2).getValueType().isFloatingPoint())
3244 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3246 // Cannot handle SETEQ/SETNE.
3247 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
3249 MVT ResVT = Op.getValueType();
3250 MVT CmpVT = Op.getOperand(0).getValueType();
3251 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3252 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
3253 DebugLoc dl = Op.getDebugLoc();
3255 // If the RHS of the comparison is a 0.0, we don't need to do the
3256 // subtraction at all.
3257 if (isFloatingPointZero(RHS))
3259 default: break; // SETUO etc aren't handled by fsel.
3262 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
3265 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
3266 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
3267 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
3270 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
3273 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
3274 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
3275 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
3276 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
3281 default: break; // SETUO etc aren't handled by fsel.
3284 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
3285 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3286 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3287 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
3290 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
3291 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3292 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3293 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
3296 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
3297 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3298 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3299 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
3302 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
3303 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3304 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3305 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
3310 // FIXME: Split this code up when LegalizeDAGTypes lands.
3311 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
3313 assert(Op.getOperand(0).getValueType().isFloatingPoint());
3314 SDValue Src = Op.getOperand(0);
3315 if (Src.getValueType() == MVT::f32)
3316 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
3319 switch (Op.getValueType().getSimpleVT()) {
3320 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
3322 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
3327 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
3331 // Convert the FP value to an int value through memory.
3332 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
3334 // Emit a store to the stack slot.
3335 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, NULL, 0);
3337 // Result is a load from the stack slot. If loading 4 bytes, make sure to
3339 if (Op.getValueType() == MVT::i32)
3340 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
3341 DAG.getConstant(4, FIPtr.getValueType()));
3342 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, NULL, 0);
3345 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3346 DebugLoc dl = Op.getDebugLoc();
3347 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
3348 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
3351 if (Op.getOperand(0).getValueType() == MVT::i64) {
3352 SDValue Bits = DAG.getNode(ISD::BIT_CONVERT, dl,
3353 MVT::f64, Op.getOperand(0));
3354 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
3355 if (Op.getValueType() == MVT::f32)
3356 FP = DAG.getNode(ISD::FP_ROUND, dl,
3357 MVT::f32, FP, DAG.getIntPtrConstant(0));
3361 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
3362 "Unhandled SINT_TO_FP type in custom expander!");
3363 // Since we only generate this in 64-bit mode, we can take advantage of
3364 // 64-bit registers. In particular, sign extend the input value into the
3365 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
3366 // then lfd it and fcfid it.
3367 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3368 int FrameIdx = FrameInfo->CreateStackObject(8, 8);
3369 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3370 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
3372 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
3375 // STD the extended value into the stack slot.
3376 MachineMemOperand MO(PseudoSourceValue::getFixedStack(FrameIdx),
3377 MachineMemOperand::MOStore, 0, 8, 8);
3378 SDValue Store = DAG.getNode(PPCISD::STD_32, dl, MVT::Other,
3379 DAG.getEntryNode(), Ext64, FIdx,
3380 DAG.getMemOperand(MO));
3381 // Load the value as a double.
3382 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, NULL, 0);
3384 // FCFID it and return it.
3385 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
3386 if (Op.getValueType() == MVT::f32)
3387 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
3391 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
3392 DebugLoc dl = Op.getDebugLoc();
3394 The rounding mode is in bits 30:31 of FPSR, and has the following
3401 FLT_ROUNDS, on the other hand, expects the following:
3408 To perform the conversion, we do:
3409 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
3412 MachineFunction &MF = DAG.getMachineFunction();
3413 MVT VT = Op.getValueType();
3414 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3415 std::vector<MVT> NodeTys;
3416 SDValue MFFSreg, InFlag;
3418 // Save FP Control Word to register
3419 NodeTys.push_back(MVT::f64); // return register
3420 NodeTys.push_back(MVT::Flag); // unused in this context
3421 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
3423 // Save FP register to stack slot
3424 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3425 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
3426 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
3427 StackSlot, NULL, 0);
3429 // Load FP Control Word from low 32 bits of stack slot.
3430 SDValue Four = DAG.getConstant(4, PtrVT);
3431 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
3432 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, NULL, 0);
3434 // Transform as necessary
3436 DAG.getNode(ISD::AND, dl, MVT::i32,
3437 CWD, DAG.getConstant(3, MVT::i32));
3439 DAG.getNode(ISD::SRL, dl, MVT::i32,
3440 DAG.getNode(ISD::AND, dl, MVT::i32,
3441 DAG.getNode(ISD::XOR, dl, MVT::i32,
3442 CWD, DAG.getConstant(3, MVT::i32)),
3443 DAG.getConstant(3, MVT::i32)),
3444 DAG.getConstant(1, MVT::i32));
3447 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
3449 return DAG.getNode((VT.getSizeInBits() < 16 ?
3450 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
3453 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) {
3454 MVT VT = Op.getValueType();
3455 unsigned BitWidth = VT.getSizeInBits();
3456 DebugLoc dl = Op.getDebugLoc();
3457 assert(Op.getNumOperands() == 3 &&
3458 VT == Op.getOperand(1).getValueType() &&
3461 // Expand into a bunch of logical ops. Note that these ops
3462 // depend on the PPC behavior for oversized shift amounts.
3463 SDValue Lo = Op.getOperand(0);
3464 SDValue Hi = Op.getOperand(1);
3465 SDValue Amt = Op.getOperand(2);
3466 MVT AmtVT = Amt.getValueType();
3468 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3469 DAG.getConstant(BitWidth, AmtVT), Amt);
3470 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
3471 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
3472 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
3473 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3474 DAG.getConstant(-BitWidth, AmtVT));
3475 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
3476 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3477 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
3478 SDValue OutOps[] = { OutLo, OutHi };
3479 return DAG.getMergeValues(OutOps, 2, dl);
3482 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) {
3483 MVT VT = Op.getValueType();
3484 DebugLoc dl = Op.getDebugLoc();
3485 unsigned BitWidth = VT.getSizeInBits();
3486 assert(Op.getNumOperands() == 3 &&
3487 VT == Op.getOperand(1).getValueType() &&
3490 // Expand into a bunch of logical ops. Note that these ops
3491 // depend on the PPC behavior for oversized shift amounts.
3492 SDValue Lo = Op.getOperand(0);
3493 SDValue Hi = Op.getOperand(1);
3494 SDValue Amt = Op.getOperand(2);
3495 MVT AmtVT = Amt.getValueType();
3497 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3498 DAG.getConstant(BitWidth, AmtVT), Amt);
3499 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3500 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3501 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3502 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3503 DAG.getConstant(-BitWidth, AmtVT));
3504 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
3505 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3506 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
3507 SDValue OutOps[] = { OutLo, OutHi };
3508 return DAG.getMergeValues(OutOps, 2, dl);
3511 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) {
3512 DebugLoc dl = Op.getDebugLoc();
3513 MVT VT = Op.getValueType();
3514 unsigned BitWidth = VT.getSizeInBits();
3515 assert(Op.getNumOperands() == 3 &&
3516 VT == Op.getOperand(1).getValueType() &&
3519 // Expand into a bunch of logical ops, followed by a select_cc.
3520 SDValue Lo = Op.getOperand(0);
3521 SDValue Hi = Op.getOperand(1);
3522 SDValue Amt = Op.getOperand(2);
3523 MVT AmtVT = Amt.getValueType();
3525 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3526 DAG.getConstant(BitWidth, AmtVT), Amt);
3527 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3528 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3529 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3530 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3531 DAG.getConstant(-BitWidth, AmtVT));
3532 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
3533 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
3534 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
3535 Tmp4, Tmp6, ISD::SETLE);
3536 SDValue OutOps[] = { OutLo, OutHi };
3537 return DAG.getMergeValues(OutOps, 2, dl);
3540 //===----------------------------------------------------------------------===//
3541 // Vector related lowering.
3544 /// BuildSplatI - Build a canonical splati of Val with an element size of
3545 /// SplatSize. Cast the result to VT.
3546 static SDValue BuildSplatI(int Val, unsigned SplatSize, MVT VT,
3547 SelectionDAG &DAG, DebugLoc dl) {
3548 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
3550 static const MVT VTys[] = { // canonical VT to use for each size.
3551 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
3554 MVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
3556 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
3560 MVT CanonicalVT = VTys[SplatSize-1];
3562 // Build a canonical splat for this value.
3563 SDValue Elt = DAG.getConstant(Val, MVT::i32);
3564 SmallVector<SDValue, 8> Ops;
3565 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
3566 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
3567 &Ops[0], Ops.size());
3568 return DAG.getNode(ISD::BIT_CONVERT, dl, ReqVT, Res);
3571 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
3572 /// specified intrinsic ID.
3573 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
3574 SelectionDAG &DAG, DebugLoc dl,
3575 MVT DestVT = MVT::Other) {
3576 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
3577 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
3578 DAG.getConstant(IID, MVT::i32), LHS, RHS);
3581 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
3582 /// specified intrinsic ID.
3583 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
3584 SDValue Op2, SelectionDAG &DAG,
3585 DebugLoc dl, MVT DestVT = MVT::Other) {
3586 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
3587 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
3588 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
3592 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
3593 /// amount. The result has the specified value type.
3594 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
3595 MVT VT, SelectionDAG &DAG, DebugLoc dl) {
3596 // Force LHS/RHS to be the right type.
3597 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, LHS);
3598 RHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, RHS);
3601 for (unsigned i = 0; i != 16; ++i)
3603 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
3604 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, T);
3607 // If this is a case we can't handle, return null and let the default
3608 // expansion code take care of it. If we CAN select this case, and if it
3609 // selects to a single instruction, return Op. Otherwise, if we can codegen
3610 // this case more efficiently than a constant pool load, lower it to the
3611 // sequence of ops that should be used.
3612 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3613 DebugLoc dl = Op.getDebugLoc();
3614 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3615 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
3617 // Check if this is a splat of a constant value.
3618 APInt APSplatBits, APSplatUndef;
3619 unsigned SplatBitSize;
3621 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
3622 HasAnyUndefs) || SplatBitSize > 32)
3625 unsigned SplatBits = APSplatBits.getZExtValue();
3626 unsigned SplatUndef = APSplatUndef.getZExtValue();
3627 unsigned SplatSize = SplatBitSize / 8;
3629 // First, handle single instruction cases.
3632 if (SplatBits == 0) {
3633 // Canonicalize all zero vectors to be v4i32.
3634 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
3635 SDValue Z = DAG.getConstant(0, MVT::i32);
3636 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
3637 Op = DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Z);
3642 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
3643 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
3645 if (SextVal >= -16 && SextVal <= 15)
3646 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
3649 // Two instruction sequences.
3651 // If this value is in the range [-32,30] and is even, use:
3652 // tmp = VSPLTI[bhw], result = add tmp, tmp
3653 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
3654 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
3655 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
3656 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3659 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
3660 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
3662 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
3663 // Make -1 and vspltisw -1:
3664 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
3666 // Make the VSLW intrinsic, computing 0x8000_0000.
3667 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
3670 // xor by OnesV to invert it.
3671 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
3672 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3675 // Check to see if this is a wide variety of vsplti*, binop self cases.
3676 static const signed char SplatCsts[] = {
3677 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
3678 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
3681 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
3682 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
3683 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
3684 int i = SplatCsts[idx];
3686 // Figure out what shift amount will be used by altivec if shifted by i in
3688 unsigned TypeShiftAmt = i & (SplatBitSize-1);
3690 // vsplti + shl self.
3691 if (SextVal == (i << (int)TypeShiftAmt)) {
3692 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3693 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3694 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
3695 Intrinsic::ppc_altivec_vslw
3697 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3698 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3701 // vsplti + srl self.
3702 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3703 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3704 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3705 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
3706 Intrinsic::ppc_altivec_vsrw
3708 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3709 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3712 // vsplti + sra self.
3713 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3714 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3715 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3716 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
3717 Intrinsic::ppc_altivec_vsraw
3719 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3720 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3723 // vsplti + rol self.
3724 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
3725 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
3726 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3727 static const unsigned IIDs[] = { // Intrinsic to use for each size.
3728 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
3729 Intrinsic::ppc_altivec_vrlw
3731 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3732 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3735 // t = vsplti c, result = vsldoi t, t, 1
3736 if (SextVal == ((i << 8) | (i >> (TypeShiftAmt-8)))) {
3737 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3738 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
3740 // t = vsplti c, result = vsldoi t, t, 2
3741 if (SextVal == ((i << 16) | (i >> (TypeShiftAmt-16)))) {
3742 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3743 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
3745 // t = vsplti c, result = vsldoi t, t, 3
3746 if (SextVal == ((i << 24) | (i >> (TypeShiftAmt-24)))) {
3747 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3748 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
3752 // Three instruction sequences.
3754 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
3755 if (SextVal >= 0 && SextVal <= 31) {
3756 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
3757 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
3758 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
3759 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), LHS);
3761 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
3762 if (SextVal >= -31 && SextVal <= 0) {
3763 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
3764 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
3765 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
3766 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), LHS);
3772 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
3773 /// the specified operations to build the shuffle.
3774 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
3775 SDValue RHS, SelectionDAG &DAG,
3777 unsigned OpNum = (PFEntry >> 26) & 0x0F;
3778 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
3779 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
3782 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
3794 if (OpNum == OP_COPY) {
3795 if (LHSID == (1*9+2)*9+3) return LHS;
3796 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
3800 SDValue OpLHS, OpRHS;
3801 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
3802 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
3806 default: llvm_unreachable("Unknown i32 permute!");
3808 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
3809 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
3810 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
3811 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
3814 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
3815 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
3816 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
3817 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
3820 for (unsigned i = 0; i != 16; ++i)
3821 ShufIdxs[i] = (i&3)+0;
3824 for (unsigned i = 0; i != 16; ++i)
3825 ShufIdxs[i] = (i&3)+4;
3828 for (unsigned i = 0; i != 16; ++i)
3829 ShufIdxs[i] = (i&3)+8;
3832 for (unsigned i = 0; i != 16; ++i)
3833 ShufIdxs[i] = (i&3)+12;
3836 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
3838 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
3840 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
3842 MVT VT = OpLHS.getValueType();
3843 OpLHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OpLHS);
3844 OpRHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OpRHS);
3845 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
3846 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, T);
3849 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
3850 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
3851 /// return the code it can be lowered into. Worst case, it can always be
3852 /// lowered into a vperm.
3853 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3854 SelectionDAG &DAG) {
3855 DebugLoc dl = Op.getDebugLoc();
3856 SDValue V1 = Op.getOperand(0);
3857 SDValue V2 = Op.getOperand(1);
3858 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3859 MVT VT = Op.getValueType();
3861 // Cases that are handled by instructions that take permute immediates
3862 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
3863 // selected by the instruction selector.
3864 if (V2.getOpcode() == ISD::UNDEF) {
3865 if (PPC::isSplatShuffleMask(SVOp, 1) ||
3866 PPC::isSplatShuffleMask(SVOp, 2) ||
3867 PPC::isSplatShuffleMask(SVOp, 4) ||
3868 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
3869 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
3870 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
3871 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
3872 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
3873 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
3874 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
3875 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
3876 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
3881 // Altivec has a variety of "shuffle immediates" that take two vector inputs
3882 // and produce a fixed permutation. If any of these match, do not lower to
3884 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
3885 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
3886 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
3887 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
3888 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
3889 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
3890 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
3891 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
3892 PPC::isVMRGHShuffleMask(SVOp, 4, false))
3895 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
3896 // perfect shuffle table to emit an optimal matching sequence.
3897 SmallVector<int, 16> PermMask;
3898 SVOp->getMask(PermMask);
3900 unsigned PFIndexes[4];
3901 bool isFourElementShuffle = true;
3902 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
3903 unsigned EltNo = 8; // Start out undef.
3904 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
3905 if (PermMask[i*4+j] < 0)
3906 continue; // Undef, ignore it.
3908 unsigned ByteSource = PermMask[i*4+j];
3909 if ((ByteSource & 3) != j) {
3910 isFourElementShuffle = false;
3915 EltNo = ByteSource/4;
3916 } else if (EltNo != ByteSource/4) {
3917 isFourElementShuffle = false;
3921 PFIndexes[i] = EltNo;
3924 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
3925 // perfect shuffle vector to determine if it is cost effective to do this as
3926 // discrete instructions, or whether we should use a vperm.
3927 if (isFourElementShuffle) {
3928 // Compute the index in the perfect shuffle table.
3929 unsigned PFTableIndex =
3930 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3932 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3933 unsigned Cost = (PFEntry >> 30);
3935 // Determining when to avoid vperm is tricky. Many things affect the cost
3936 // of vperm, particularly how many times the perm mask needs to be computed.
3937 // For example, if the perm mask can be hoisted out of a loop or is already
3938 // used (perhaps because there are multiple permutes with the same shuffle
3939 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
3940 // the loop requires an extra register.
3942 // As a compromise, we only emit discrete instructions if the shuffle can be
3943 // generated in 3 or fewer operations. When we have loop information
3944 // available, if this block is within a loop, we should avoid using vperm
3945 // for 3-operation perms and use a constant pool load instead.
3947 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
3950 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
3951 // vector that will get spilled to the constant pool.
3952 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
3954 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
3955 // that it is in input element units, not in bytes. Convert now.
3956 MVT EltVT = V1.getValueType().getVectorElementType();
3957 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
3959 SmallVector<SDValue, 16> ResultMask;
3960 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
3961 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
3963 for (unsigned j = 0; j != BytesPerElement; ++j)
3964 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
3968 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
3969 &ResultMask[0], ResultMask.size());
3970 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
3973 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
3974 /// altivec comparison. If it is, return true and fill in Opc/isDot with
3975 /// information about the intrinsic.
3976 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
3978 unsigned IntrinsicID =
3979 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
3982 switch (IntrinsicID) {
3983 default: return false;
3984 // Comparison predicates.
3985 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
3986 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
3987 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
3988 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
3989 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
3990 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
3991 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
3992 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
3993 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
3994 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
3995 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
3996 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
3997 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
3999 // Normal Comparisons.
4000 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
4001 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
4002 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
4003 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
4004 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
4005 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
4006 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
4007 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
4008 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
4009 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
4010 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
4011 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
4012 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
4017 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
4018 /// lower, do it, otherwise return null.
4019 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4020 SelectionDAG &DAG) {
4021 // If this is a lowered altivec predicate compare, CompareOpc is set to the
4022 // opcode number of the comparison.
4023 DebugLoc dl = Op.getDebugLoc();
4026 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
4027 return SDValue(); // Don't custom lower most intrinsics.
4029 // If this is a non-dot comparison, make the VCMP node and we are done.
4031 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
4032 Op.getOperand(1), Op.getOperand(2),
4033 DAG.getConstant(CompareOpc, MVT::i32));
4034 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Tmp);
4037 // Create the PPCISD altivec 'dot' comparison node.
4039 Op.getOperand(2), // LHS
4040 Op.getOperand(3), // RHS
4041 DAG.getConstant(CompareOpc, MVT::i32)
4043 std::vector<MVT> VTs;
4044 VTs.push_back(Op.getOperand(2).getValueType());
4045 VTs.push_back(MVT::Flag);
4046 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
4048 // Now that we have the comparison, emit a copy from the CR to a GPR.
4049 // This is flagged to the above dot comparison.
4050 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
4051 DAG.getRegister(PPC::CR6, MVT::i32),
4052 CompNode.getValue(1));
4054 // Unpack the result based on how the target uses it.
4055 unsigned BitNo; // Bit # of CR6.
4056 bool InvertBit; // Invert result?
4057 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
4058 default: // Can't happen, don't crash on invalid number though.
4059 case 0: // Return the value of the EQ bit of CR6.
4060 BitNo = 0; InvertBit = false;
4062 case 1: // Return the inverted value of the EQ bit of CR6.
4063 BitNo = 0; InvertBit = true;
4065 case 2: // Return the value of the LT bit of CR6.
4066 BitNo = 2; InvertBit = false;
4068 case 3: // Return the inverted value of the LT bit of CR6.
4069 BitNo = 2; InvertBit = true;
4073 // Shift the bit into the low position.
4074 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
4075 DAG.getConstant(8-(3-BitNo), MVT::i32));
4077 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
4078 DAG.getConstant(1, MVT::i32));
4080 // If we are supposed to, toggle the bit.
4082 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
4083 DAG.getConstant(1, MVT::i32));
4087 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
4088 SelectionDAG &DAG) {
4089 DebugLoc dl = Op.getDebugLoc();
4090 // Create a stack slot that is 16-byte aligned.
4091 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
4092 int FrameIdx = FrameInfo->CreateStackObject(16, 16);
4093 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4094 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4096 // Store the input value into Value#0 of the stack slot.
4097 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
4098 Op.getOperand(0), FIdx, NULL, 0);
4100 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, NULL, 0);
4103 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) {
4104 DebugLoc dl = Op.getDebugLoc();
4105 if (Op.getValueType() == MVT::v4i32) {
4106 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4108 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
4109 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
4111 SDValue RHSSwap = // = vrlw RHS, 16
4112 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
4114 // Shrinkify inputs to v8i16.
4115 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, LHS);
4116 RHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, RHS);
4117 RHSSwap = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, RHSSwap);
4119 // Low parts multiplied together, generating 32-bit results (we ignore the
4121 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
4122 LHS, RHS, DAG, dl, MVT::v4i32);
4124 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
4125 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
4126 // Shift the high parts up 16 bits.
4127 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
4129 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
4130 } else if (Op.getValueType() == MVT::v8i16) {
4131 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4133 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
4135 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
4136 LHS, RHS, Zero, DAG, dl);
4137 } else if (Op.getValueType() == MVT::v16i8) {
4138 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4140 // Multiply the even 8-bit parts, producing 16-bit sums.
4141 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
4142 LHS, RHS, DAG, dl, MVT::v8i16);
4143 EvenParts = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, EvenParts);
4145 // Multiply the odd 8-bit parts, producing 16-bit sums.
4146 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
4147 LHS, RHS, DAG, dl, MVT::v8i16);
4148 OddParts = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OddParts);
4150 // Merge the results together.
4152 for (unsigned i = 0; i != 8; ++i) {
4154 Ops[i*2+1] = 2*i+1+16;
4156 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
4158 llvm_unreachable("Unknown mul to lower!");
4162 /// LowerOperation - Provide custom lowering hooks for some operations.
4164 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
4165 switch (Op.getOpcode()) {
4166 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
4167 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4168 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4169 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4170 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
4171 case ISD::SETCC: return LowerSETCC(Op, DAG);
4172 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
4174 return LowerVASTART(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
4175 VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
4178 return LowerVAARG(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
4179 VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
4181 case ISD::FORMAL_ARGUMENTS:
4182 if (PPCSubTarget.isSVR4ABI()) {
4183 return LowerFORMAL_ARGUMENTS_SVR4(Op, DAG, VarArgsFrameIndex,
4184 VarArgsStackOffset, VarArgsNumGPR,
4185 VarArgsNumFPR, PPCSubTarget);
4187 return LowerFORMAL_ARGUMENTS_Darwin(Op, DAG, VarArgsFrameIndex,
4192 if (PPCSubTarget.isSVR4ABI()) {
4193 return LowerCALL_SVR4(Op, DAG, PPCSubTarget, getTargetMachine());
4195 return LowerCALL_Darwin(Op, DAG, PPCSubTarget, getTargetMachine());
4198 case ISD::RET: return LowerRET(Op, DAG, getTargetMachine());
4199 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
4200 case ISD::DYNAMIC_STACKALLOC:
4201 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
4203 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
4204 case ISD::FP_TO_UINT:
4205 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
4207 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4208 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
4210 // Lower 64-bit shifts.
4211 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
4212 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
4213 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
4215 // Vector-related lowering.
4216 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4217 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4218 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4219 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4220 case ISD::MUL: return LowerMUL(Op, DAG);
4222 // Frame & Return address.
4223 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4224 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
4229 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
4230 SmallVectorImpl<SDValue>&Results,
4231 SelectionDAG &DAG) {
4232 DebugLoc dl = N->getDebugLoc();
4233 switch (N->getOpcode()) {
4235 assert(false && "Do not know how to custom type legalize this operation!");
4237 case ISD::FP_ROUND_INREG: {
4238 assert(N->getValueType(0) == MVT::ppcf128);
4239 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
4240 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
4241 MVT::f64, N->getOperand(0),
4242 DAG.getIntPtrConstant(0));
4243 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
4244 MVT::f64, N->getOperand(0),
4245 DAG.getIntPtrConstant(1));
4247 // This sequence changes FPSCR to do round-to-zero, adds the two halves
4248 // of the long double, and puts FPSCR back the way it was. We do not
4249 // actually model FPSCR.
4250 std::vector<MVT> NodeTys;
4251 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
4253 NodeTys.push_back(MVT::f64); // Return register
4254 NodeTys.push_back(MVT::Flag); // Returns a flag for later insns
4255 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4256 MFFSreg = Result.getValue(0);
4257 InFlag = Result.getValue(1);
4260 NodeTys.push_back(MVT::Flag); // Returns a flag
4261 Ops[0] = DAG.getConstant(31, MVT::i32);
4263 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
4264 InFlag = Result.getValue(0);
4267 NodeTys.push_back(MVT::Flag); // Returns a flag
4268 Ops[0] = DAG.getConstant(30, MVT::i32);
4270 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
4271 InFlag = Result.getValue(0);
4274 NodeTys.push_back(MVT::f64); // result of add
4275 NodeTys.push_back(MVT::Flag); // Returns a flag
4279 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
4280 FPreg = Result.getValue(0);
4281 InFlag = Result.getValue(1);
4284 NodeTys.push_back(MVT::f64);
4285 Ops[0] = DAG.getConstant(1, MVT::i32);
4289 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
4290 FPreg = Result.getValue(0);
4292 // We know the low half is about to be thrown away, so just use something
4294 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
4298 case ISD::FP_TO_SINT:
4299 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
4305 //===----------------------------------------------------------------------===//
4306 // Other Lowering Code
4307 //===----------------------------------------------------------------------===//
4310 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
4311 bool is64bit, unsigned BinOpcode) const {
4312 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
4313 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4315 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4316 MachineFunction *F = BB->getParent();
4317 MachineFunction::iterator It = BB;
4320 unsigned dest = MI->getOperand(0).getReg();
4321 unsigned ptrA = MI->getOperand(1).getReg();
4322 unsigned ptrB = MI->getOperand(2).getReg();
4323 unsigned incr = MI->getOperand(3).getReg();
4324 DebugLoc dl = MI->getDebugLoc();
4326 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
4327 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4328 F->insert(It, loopMBB);
4329 F->insert(It, exitMBB);
4330 exitMBB->transferSuccessors(BB);
4332 MachineRegisterInfo &RegInfo = F->getRegInfo();
4333 unsigned TmpReg = (!BinOpcode) ? incr :
4334 RegInfo.createVirtualRegister(
4335 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4336 (const TargetRegisterClass *) &PPC::GPRCRegClass);
4340 // fallthrough --> loopMBB
4341 BB->addSuccessor(loopMBB);
4344 // l[wd]arx dest, ptr
4345 // add r0, dest, incr
4346 // st[wd]cx. r0, ptr
4348 // fallthrough --> exitMBB
4350 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
4351 .addReg(ptrA).addReg(ptrB);
4353 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
4354 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4355 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
4356 BuildMI(BB, dl, TII->get(PPC::BCC))
4357 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
4358 BB->addSuccessor(loopMBB);
4359 BB->addSuccessor(exitMBB);
4368 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
4369 MachineBasicBlock *BB,
4370 bool is8bit, // operation
4371 unsigned BinOpcode) const {
4372 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
4373 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4374 // In 64 bit mode we have to use 64 bits for addresses, even though the
4375 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
4376 // registers without caring whether they're 32 or 64, but here we're
4377 // doing actual arithmetic on the addresses.
4378 bool is64bit = PPCSubTarget.isPPC64();
4380 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4381 MachineFunction *F = BB->getParent();
4382 MachineFunction::iterator It = BB;
4385 unsigned dest = MI->getOperand(0).getReg();
4386 unsigned ptrA = MI->getOperand(1).getReg();
4387 unsigned ptrB = MI->getOperand(2).getReg();
4388 unsigned incr = MI->getOperand(3).getReg();
4389 DebugLoc dl = MI->getDebugLoc();
4391 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
4392 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4393 F->insert(It, loopMBB);
4394 F->insert(It, exitMBB);
4395 exitMBB->transferSuccessors(BB);
4397 MachineRegisterInfo &RegInfo = F->getRegInfo();
4398 const TargetRegisterClass *RC =
4399 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4400 (const TargetRegisterClass *) &PPC::GPRCRegClass;
4401 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
4402 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
4403 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
4404 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
4405 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
4406 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
4407 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
4408 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
4409 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
4410 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
4411 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
4413 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
4417 // fallthrough --> loopMBB
4418 BB->addSuccessor(loopMBB);
4420 // The 4-byte load must be aligned, while a char or short may be
4421 // anywhere in the word. Hence all this nasty bookkeeping code.
4422 // add ptr1, ptrA, ptrB [copy if ptrA==0]
4423 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
4424 // xori shift, shift1, 24 [16]
4425 // rlwinm ptr, ptr1, 0, 0, 29
4426 // slw incr2, incr, shift
4427 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
4428 // slw mask, mask2, shift
4430 // lwarx tmpDest, ptr
4431 // add tmp, tmpDest, incr2
4432 // andc tmp2, tmpDest, mask
4433 // and tmp3, tmp, mask
4434 // or tmp4, tmp3, tmp2
4437 // fallthrough --> exitMBB
4438 // srw dest, tmpDest, shift
4440 if (ptrA!=PPC::R0) {
4441 Ptr1Reg = RegInfo.createVirtualRegister(RC);
4442 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
4443 .addReg(ptrA).addReg(ptrB);
4447 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
4448 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
4449 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
4450 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
4452 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
4453 .addReg(Ptr1Reg).addImm(0).addImm(61);
4455 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
4456 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
4457 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
4458 .addReg(incr).addReg(ShiftReg);
4460 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
4462 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4463 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
4465 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4466 .addReg(Mask2Reg).addReg(ShiftReg);
4469 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4470 .addReg(PPC::R0).addReg(PtrReg);
4472 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
4473 .addReg(Incr2Reg).addReg(TmpDestReg);
4474 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
4475 .addReg(TmpDestReg).addReg(MaskReg);
4476 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
4477 .addReg(TmpReg).addReg(MaskReg);
4478 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
4479 .addReg(Tmp3Reg).addReg(Tmp2Reg);
4480 BuildMI(BB, dl, TII->get(PPC::STWCX))
4481 .addReg(Tmp4Reg).addReg(PPC::R0).addReg(PtrReg);
4482 BuildMI(BB, dl, TII->get(PPC::BCC))
4483 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
4484 BB->addSuccessor(loopMBB);
4485 BB->addSuccessor(exitMBB);
4490 BuildMI(BB, dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg).addReg(ShiftReg);
4495 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4496 MachineBasicBlock *BB) const {
4497 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4499 // To "insert" these instructions we actually have to insert their
4500 // control-flow patterns.
4501 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4502 MachineFunction::iterator It = BB;
4505 MachineFunction *F = BB->getParent();
4507 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
4508 MI->getOpcode() == PPC::SELECT_CC_I8 ||
4509 MI->getOpcode() == PPC::SELECT_CC_F4 ||
4510 MI->getOpcode() == PPC::SELECT_CC_F8 ||
4511 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
4513 // The incoming instruction knows the destination vreg to set, the
4514 // condition code register to branch on, the true/false values to
4515 // select between, and a branch opcode to use.
4520 // cmpTY ccX, r1, r2
4522 // fallthrough --> copy0MBB
4523 MachineBasicBlock *thisMBB = BB;
4524 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4525 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4526 unsigned SelectPred = MI->getOperand(4).getImm();
4527 DebugLoc dl = MI->getDebugLoc();
4528 BuildMI(BB, dl, TII->get(PPC::BCC))
4529 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
4530 F->insert(It, copy0MBB);
4531 F->insert(It, sinkMBB);
4532 // Update machine-CFG edges by transferring all successors of the current
4533 // block to the new block which will contain the Phi node for the select.
4534 sinkMBB->transferSuccessors(BB);
4535 // Next, add the true and fallthrough blocks as its successors.
4536 BB->addSuccessor(copy0MBB);
4537 BB->addSuccessor(sinkMBB);
4540 // %FalseValue = ...
4541 // # fallthrough to sinkMBB
4544 // Update machine-CFG edges
4545 BB->addSuccessor(sinkMBB);
4548 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4551 BuildMI(BB, dl, TII->get(PPC::PHI), MI->getOperand(0).getReg())
4552 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
4553 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4555 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
4556 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
4557 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
4558 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
4559 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
4560 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
4561 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
4562 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
4564 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
4565 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
4566 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
4567 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
4568 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
4569 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
4570 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
4571 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
4573 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
4574 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
4575 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
4576 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
4577 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
4578 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
4579 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
4580 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
4582 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
4583 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
4584 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
4585 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
4586 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
4587 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
4588 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
4589 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
4591 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
4592 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
4593 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
4594 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
4595 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
4596 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
4597 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
4598 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
4600 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
4601 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
4602 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
4603 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
4604 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
4605 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
4606 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
4607 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
4609 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
4610 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
4611 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
4612 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
4613 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
4614 BB = EmitAtomicBinary(MI, BB, false, 0);
4615 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
4616 BB = EmitAtomicBinary(MI, BB, true, 0);
4618 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
4619 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
4620 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
4622 unsigned dest = MI->getOperand(0).getReg();
4623 unsigned ptrA = MI->getOperand(1).getReg();
4624 unsigned ptrB = MI->getOperand(2).getReg();
4625 unsigned oldval = MI->getOperand(3).getReg();
4626 unsigned newval = MI->getOperand(4).getReg();
4627 DebugLoc dl = MI->getDebugLoc();
4629 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
4630 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
4631 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
4632 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4633 F->insert(It, loop1MBB);
4634 F->insert(It, loop2MBB);
4635 F->insert(It, midMBB);
4636 F->insert(It, exitMBB);
4637 exitMBB->transferSuccessors(BB);
4641 // fallthrough --> loopMBB
4642 BB->addSuccessor(loop1MBB);
4645 // l[wd]arx dest, ptr
4646 // cmp[wd] dest, oldval
4649 // st[wd]cx. newval, ptr
4653 // st[wd]cx. dest, ptr
4656 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
4657 .addReg(ptrA).addReg(ptrB);
4658 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
4659 .addReg(oldval).addReg(dest);
4660 BuildMI(BB, dl, TII->get(PPC::BCC))
4661 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
4662 BB->addSuccessor(loop2MBB);
4663 BB->addSuccessor(midMBB);
4666 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4667 .addReg(newval).addReg(ptrA).addReg(ptrB);
4668 BuildMI(BB, dl, TII->get(PPC::BCC))
4669 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
4670 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
4671 BB->addSuccessor(loop1MBB);
4672 BB->addSuccessor(exitMBB);
4675 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4676 .addReg(dest).addReg(ptrA).addReg(ptrB);
4677 BB->addSuccessor(exitMBB);
4682 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
4683 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
4684 // We must use 64-bit registers for addresses when targeting 64-bit,
4685 // since we're actually doing arithmetic on them. Other registers
4687 bool is64bit = PPCSubTarget.isPPC64();
4688 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
4690 unsigned dest = MI->getOperand(0).getReg();
4691 unsigned ptrA = MI->getOperand(1).getReg();
4692 unsigned ptrB = MI->getOperand(2).getReg();
4693 unsigned oldval = MI->getOperand(3).getReg();
4694 unsigned newval = MI->getOperand(4).getReg();
4695 DebugLoc dl = MI->getDebugLoc();
4697 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
4698 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
4699 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
4700 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4701 F->insert(It, loop1MBB);
4702 F->insert(It, loop2MBB);
4703 F->insert(It, midMBB);
4704 F->insert(It, exitMBB);
4705 exitMBB->transferSuccessors(BB);
4707 MachineRegisterInfo &RegInfo = F->getRegInfo();
4708 const TargetRegisterClass *RC =
4709 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4710 (const TargetRegisterClass *) &PPC::GPRCRegClass;
4711 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
4712 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
4713 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
4714 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
4715 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
4716 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
4717 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
4718 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
4719 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
4720 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
4721 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
4722 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
4723 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
4725 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
4728 // fallthrough --> loopMBB
4729 BB->addSuccessor(loop1MBB);
4731 // The 4-byte load must be aligned, while a char or short may be
4732 // anywhere in the word. Hence all this nasty bookkeeping code.
4733 // add ptr1, ptrA, ptrB [copy if ptrA==0]
4734 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
4735 // xori shift, shift1, 24 [16]
4736 // rlwinm ptr, ptr1, 0, 0, 29
4737 // slw newval2, newval, shift
4738 // slw oldval2, oldval,shift
4739 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
4740 // slw mask, mask2, shift
4741 // and newval3, newval2, mask
4742 // and oldval3, oldval2, mask
4744 // lwarx tmpDest, ptr
4745 // and tmp, tmpDest, mask
4746 // cmpw tmp, oldval3
4749 // andc tmp2, tmpDest, mask
4750 // or tmp4, tmp2, newval3
4755 // stwcx. tmpDest, ptr
4757 // srw dest, tmpDest, shift
4758 if (ptrA!=PPC::R0) {
4759 Ptr1Reg = RegInfo.createVirtualRegister(RC);
4760 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
4761 .addReg(ptrA).addReg(ptrB);
4765 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
4766 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
4767 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
4768 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
4770 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
4771 .addReg(Ptr1Reg).addImm(0).addImm(61);
4773 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
4774 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
4775 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
4776 .addReg(newval).addReg(ShiftReg);
4777 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
4778 .addReg(oldval).addReg(ShiftReg);
4780 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
4782 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4783 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
4784 .addReg(Mask3Reg).addImm(65535);
4786 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4787 .addReg(Mask2Reg).addReg(ShiftReg);
4788 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
4789 .addReg(NewVal2Reg).addReg(MaskReg);
4790 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
4791 .addReg(OldVal2Reg).addReg(MaskReg);
4794 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4795 .addReg(PPC::R0).addReg(PtrReg);
4796 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
4797 .addReg(TmpDestReg).addReg(MaskReg);
4798 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
4799 .addReg(TmpReg).addReg(OldVal3Reg);
4800 BuildMI(BB, dl, TII->get(PPC::BCC))
4801 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
4802 BB->addSuccessor(loop2MBB);
4803 BB->addSuccessor(midMBB);
4806 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
4807 .addReg(TmpDestReg).addReg(MaskReg);
4808 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
4809 .addReg(Tmp2Reg).addReg(NewVal3Reg);
4810 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
4811 .addReg(PPC::R0).addReg(PtrReg);
4812 BuildMI(BB, dl, TII->get(PPC::BCC))
4813 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
4814 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
4815 BB->addSuccessor(loop1MBB);
4816 BB->addSuccessor(exitMBB);
4819 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
4820 .addReg(PPC::R0).addReg(PtrReg);
4821 BB->addSuccessor(exitMBB);
4826 BuildMI(BB, dl, TII->get(PPC::SRW),dest).addReg(TmpReg).addReg(ShiftReg);
4828 llvm_unreachable("Unexpected instr type to insert");
4831 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
4835 //===----------------------------------------------------------------------===//
4836 // Target Optimization Hooks
4837 //===----------------------------------------------------------------------===//
4839 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
4840 DAGCombinerInfo &DCI) const {
4841 TargetMachine &TM = getTargetMachine();
4842 SelectionDAG &DAG = DCI.DAG;
4843 DebugLoc dl = N->getDebugLoc();
4844 switch (N->getOpcode()) {
4847 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4848 if (C->getZExtValue() == 0) // 0 << V -> 0.
4849 return N->getOperand(0);
4853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4854 if (C->getZExtValue() == 0) // 0 >>u V -> 0.
4855 return N->getOperand(0);
4859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4860 if (C->getZExtValue() == 0 || // 0 >>s V -> 0.
4861 C->isAllOnesValue()) // -1 >>s V -> -1.
4862 return N->getOperand(0);
4866 case ISD::SINT_TO_FP:
4867 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
4868 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
4869 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
4870 // We allow the src/dst to be either f32/f64, but the intermediate
4871 // type must be i64.
4872 if (N->getOperand(0).getValueType() == MVT::i64 &&
4873 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
4874 SDValue Val = N->getOperand(0).getOperand(0);
4875 if (Val.getValueType() == MVT::f32) {
4876 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
4877 DCI.AddToWorklist(Val.getNode());
4880 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
4881 DCI.AddToWorklist(Val.getNode());
4882 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
4883 DCI.AddToWorklist(Val.getNode());
4884 if (N->getValueType(0) == MVT::f32) {
4885 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
4886 DAG.getIntPtrConstant(0));
4887 DCI.AddToWorklist(Val.getNode());
4890 } else if (N->getOperand(0).getValueType() == MVT::i32) {
4891 // If the intermediate type is i32, we can avoid the load/store here
4898 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
4899 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
4900 !cast<StoreSDNode>(N)->isTruncatingStore() &&
4901 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
4902 N->getOperand(1).getValueType() == MVT::i32 &&
4903 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
4904 SDValue Val = N->getOperand(1).getOperand(0);
4905 if (Val.getValueType() == MVT::f32) {
4906 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
4907 DCI.AddToWorklist(Val.getNode());
4909 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
4910 DCI.AddToWorklist(Val.getNode());
4912 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
4913 N->getOperand(2), N->getOperand(3));
4914 DCI.AddToWorklist(Val.getNode());
4918 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
4919 if (N->getOperand(1).getOpcode() == ISD::BSWAP &&
4920 N->getOperand(1).getNode()->hasOneUse() &&
4921 (N->getOperand(1).getValueType() == MVT::i32 ||
4922 N->getOperand(1).getValueType() == MVT::i16)) {
4923 SDValue BSwapOp = N->getOperand(1).getOperand(0);
4924 // Do an any-extend to 32-bits if this is a half-word input.
4925 if (BSwapOp.getValueType() == MVT::i16)
4926 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
4928 return DAG.getNode(PPCISD::STBRX, dl, MVT::Other, N->getOperand(0),
4929 BSwapOp, N->getOperand(2), N->getOperand(3),
4930 DAG.getValueType(N->getOperand(1).getValueType()));
4934 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
4935 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
4936 N->getOperand(0).hasOneUse() &&
4937 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
4938 SDValue Load = N->getOperand(0);
4939 LoadSDNode *LD = cast<LoadSDNode>(Load);
4940 // Create the byte-swapping load.
4941 std::vector<MVT> VTs;
4942 VTs.push_back(MVT::i32);
4943 VTs.push_back(MVT::Other);
4944 SDValue MO = DAG.getMemOperand(LD->getMemOperand());
4946 LD->getChain(), // Chain
4947 LD->getBasePtr(), // Ptr
4949 DAG.getValueType(N->getValueType(0)) // VT
4951 SDValue BSLoad = DAG.getNode(PPCISD::LBRX, dl, VTs, Ops, 4);
4953 // If this is an i16 load, insert the truncate.
4954 SDValue ResVal = BSLoad;
4955 if (N->getValueType(0) == MVT::i16)
4956 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
4958 // First, combine the bswap away. This makes the value produced by the
4960 DCI.CombineTo(N, ResVal);
4962 // Next, combine the load away, we give it a bogus result value but a real
4963 // chain result. The result value is dead because the bswap is dead.
4964 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
4966 // Return N so it doesn't get rechecked!
4967 return SDValue(N, 0);
4971 case PPCISD::VCMP: {
4972 // If a VCMPo node already exists with exactly the same operands as this
4973 // node, use its result instead of this node (VCMPo computes both a CR6 and
4974 // a normal output).
4976 if (!N->getOperand(0).hasOneUse() &&
4977 !N->getOperand(1).hasOneUse() &&
4978 !N->getOperand(2).hasOneUse()) {
4980 // Scan all of the users of the LHS, looking for VCMPo's that match.
4981 SDNode *VCMPoNode = 0;
4983 SDNode *LHSN = N->getOperand(0).getNode();
4984 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
4986 if (UI->getOpcode() == PPCISD::VCMPo &&
4987 UI->getOperand(1) == N->getOperand(1) &&
4988 UI->getOperand(2) == N->getOperand(2) &&
4989 UI->getOperand(0) == N->getOperand(0)) {
4994 // If there is no VCMPo node, or if the flag value has a single use, don't
4996 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
4999 // Look at the (necessarily single) use of the flag value. If it has a
5000 // chain, this transformation is more complex. Note that multiple things
5001 // could use the value result, which we should ignore.
5002 SDNode *FlagUser = 0;
5003 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
5004 FlagUser == 0; ++UI) {
5005 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
5007 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
5008 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
5015 // If the user is a MFCR instruction, we know this is safe. Otherwise we
5016 // give up for right now.
5017 if (FlagUser->getOpcode() == PPCISD::MFCR)
5018 return SDValue(VCMPoNode, 0);
5023 // If this is a branch on an altivec predicate comparison, lower this so
5024 // that we don't have to do a MFCR: instead, branch directly on CR6. This
5025 // lowering is done pre-legalize, because the legalizer lowers the predicate
5026 // compare down to code that is difficult to reassemble.
5027 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
5028 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
5032 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
5033 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
5034 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
5035 assert(isDot && "Can't compare against a vector result!");
5037 // If this is a comparison against something other than 0/1, then we know
5038 // that the condition is never/always true.
5039 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
5040 if (Val != 0 && Val != 1) {
5041 if (CC == ISD::SETEQ) // Cond never true, remove branch.
5042 return N->getOperand(0);
5043 // Always !=, turn it into an unconditional branch.
5044 return DAG.getNode(ISD::BR, dl, MVT::Other,
5045 N->getOperand(0), N->getOperand(4));
5048 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
5050 // Create the PPCISD altivec 'dot' comparison node.
5051 std::vector<MVT> VTs;
5053 LHS.getOperand(2), // LHS of compare
5054 LHS.getOperand(3), // RHS of compare
5055 DAG.getConstant(CompareOpc, MVT::i32)
5057 VTs.push_back(LHS.getOperand(2).getValueType());
5058 VTs.push_back(MVT::Flag);
5059 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5061 // Unpack the result based on how the target uses it.
5062 PPC::Predicate CompOpc;
5063 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
5064 default: // Can't happen, don't crash on invalid number though.
5065 case 0: // Branch on the value of the EQ bit of CR6.
5066 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
5068 case 1: // Branch on the inverted value of the EQ bit of CR6.
5069 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
5071 case 2: // Branch on the value of the LT bit of CR6.
5072 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
5074 case 3: // Branch on the inverted value of the LT bit of CR6.
5075 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
5079 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
5080 DAG.getConstant(CompOpc, MVT::i32),
5081 DAG.getRegister(PPC::CR6, MVT::i32),
5082 N->getOperand(4), CompNode.getValue(1));
5091 //===----------------------------------------------------------------------===//
5092 // Inline Assembly Support
5093 //===----------------------------------------------------------------------===//
5095 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
5099 const SelectionDAG &DAG,
5100 unsigned Depth) const {
5101 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
5102 switch (Op.getOpcode()) {
5104 case PPCISD::LBRX: {
5105 // lhbrx is known to have the top bits cleared out.
5106 if (cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::i16)
5107 KnownZero = 0xFFFF0000;
5110 case ISD::INTRINSIC_WO_CHAIN: {
5111 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
5113 case Intrinsic::ppc_altivec_vcmpbfp_p:
5114 case Intrinsic::ppc_altivec_vcmpeqfp_p:
5115 case Intrinsic::ppc_altivec_vcmpequb_p:
5116 case Intrinsic::ppc_altivec_vcmpequh_p:
5117 case Intrinsic::ppc_altivec_vcmpequw_p:
5118 case Intrinsic::ppc_altivec_vcmpgefp_p:
5119 case Intrinsic::ppc_altivec_vcmpgtfp_p:
5120 case Intrinsic::ppc_altivec_vcmpgtsb_p:
5121 case Intrinsic::ppc_altivec_vcmpgtsh_p:
5122 case Intrinsic::ppc_altivec_vcmpgtsw_p:
5123 case Intrinsic::ppc_altivec_vcmpgtub_p:
5124 case Intrinsic::ppc_altivec_vcmpgtuh_p:
5125 case Intrinsic::ppc_altivec_vcmpgtuw_p:
5126 KnownZero = ~1U; // All bits but the low one are known to be zero.
5134 /// getConstraintType - Given a constraint, return the type of
5135 /// constraint it is for this target.
5136 PPCTargetLowering::ConstraintType
5137 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
5138 if (Constraint.size() == 1) {
5139 switch (Constraint[0]) {
5146 return C_RegisterClass;
5149 return TargetLowering::getConstraintType(Constraint);
5152 std::pair<unsigned, const TargetRegisterClass*>
5153 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5155 if (Constraint.size() == 1) {
5156 // GCC RS6000 Constraint Letters
5157 switch (Constraint[0]) {
5160 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
5161 return std::make_pair(0U, PPC::G8RCRegisterClass);
5162 return std::make_pair(0U, PPC::GPRCRegisterClass);
5165 return std::make_pair(0U, PPC::F4RCRegisterClass);
5166 else if (VT == MVT::f64)
5167 return std::make_pair(0U, PPC::F8RCRegisterClass);
5170 return std::make_pair(0U, PPC::VRRCRegisterClass);
5172 return std::make_pair(0U, PPC::CRRCRegisterClass);
5176 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5180 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5181 /// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
5182 /// it means one of the asm constraint of the inline asm instruction being
5183 /// processed is 'm'.
5184 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, char Letter,
5186 std::vector<SDValue>&Ops,
5187 SelectionDAG &DAG) const {
5188 SDValue Result(0,0);
5199 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
5200 if (!CST) return; // Must be an immediate to match.
5201 unsigned Value = CST->getZExtValue();
5203 default: llvm_unreachable("Unknown constraint letter!");
5204 case 'I': // "I" is a signed 16-bit constant.
5205 if ((short)Value == (int)Value)
5206 Result = DAG.getTargetConstant(Value, Op.getValueType());
5208 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
5209 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
5210 if ((short)Value == 0)
5211 Result = DAG.getTargetConstant(Value, Op.getValueType());
5213 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
5214 if ((Value >> 16) == 0)
5215 Result = DAG.getTargetConstant(Value, Op.getValueType());
5217 case 'M': // "M" is a constant that is greater than 31.
5219 Result = DAG.getTargetConstant(Value, Op.getValueType());
5221 case 'N': // "N" is a positive constant that is an exact power of two.
5222 if ((int)Value > 0 && isPowerOf2_32(Value))
5223 Result = DAG.getTargetConstant(Value, Op.getValueType());
5225 case 'O': // "O" is the constant zero.
5227 Result = DAG.getTargetConstant(Value, Op.getValueType());
5229 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
5230 if ((short)-Value == (int)-Value)
5231 Result = DAG.getTargetConstant(Value, Op.getValueType());
5238 if (Result.getNode()) {
5239 Ops.push_back(Result);
5243 // Handle standard constraint letters.
5244 TargetLowering::LowerAsmOperandForConstraint(Op, Letter, hasMemory, Ops, DAG);
5247 // isLegalAddressingMode - Return true if the addressing mode represented
5248 // by AM is legal for this target, for a load/store of the specified type.
5249 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
5250 const Type *Ty) const {
5251 // FIXME: PPC does not allow r+i addressing modes for vectors!
5253 // PPC allows a sign-extended 16-bit immediate field.
5254 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
5257 // No global is ever allowed as a base.
5261 // PPC only support r+r,
5263 case 0: // "r+i" or just "i", depending on HasBaseReg.
5266 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
5268 // Otherwise we have r+r or r+i.
5271 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
5273 // Allow 2*r as r+r.
5276 // No other scales are supported.
5283 /// isLegalAddressImmediate - Return true if the integer value can be used
5284 /// as the offset of the target addressing mode for load / store of the
5286 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
5287 // PPC allows a sign-extended 16-bit immediate field.
5288 return (V > -(1 << 16) && V < (1 << 16)-1);
5291 bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) const {
5295 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5296 DebugLoc dl = Op.getDebugLoc();
5297 // Depths > 0 not supported yet!
5298 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5301 MachineFunction &MF = DAG.getMachineFunction();
5302 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
5304 // Just load the return address off the stack.
5305 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
5307 // Make sure the function really does not optimize away the store of the RA
5309 FuncInfo->setLRStoreRequired();
5310 return DAG.getLoad(getPointerTy(), dl,
5311 DAG.getEntryNode(), RetAddrFI, NULL, 0);
5314 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5315 DebugLoc dl = Op.getDebugLoc();
5316 // Depths > 0 not supported yet!
5317 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5320 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5321 bool isPPC64 = PtrVT == MVT::i64;
5323 MachineFunction &MF = DAG.getMachineFunction();
5324 MachineFrameInfo *MFI = MF.getFrameInfo();
5325 bool is31 = (NoFramePointerElim || MFI->hasVarSizedObjects())
5326 && MFI->getStackSize();
5329 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, is31 ? PPC::X31 : PPC::X1,
5332 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, is31 ? PPC::R31 : PPC::R1,
5337 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5338 // The PowerPC target isn't yet aware of offsets.
5342 MVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
5343 bool isSrcConst, bool isSrcStr,
5344 SelectionDAG &DAG) const {
5345 if (this->PPCSubTarget.isPPC64()) {