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 "PPCPerfectShuffle.h"
17 #include "PPCTargetMachine.h"
18 #include "MCTargetDesc/PPCPredicates.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
39 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
40 CCValAssign::LocInfo &LocInfo,
41 ISD::ArgFlagsTy &ArgFlags,
43 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
45 CCValAssign::LocInfo &LocInfo,
46 ISD::ArgFlagsTy &ArgFlags,
48 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
50 CCValAssign::LocInfo &LocInfo,
51 ISD::ArgFlagsTy &ArgFlags,
54 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
55 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
57 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
58 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
60 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
61 if (TM.getSubtargetImpl()->isDarwin())
62 return new TargetLoweringObjectFileMachO();
64 return new TargetLoweringObjectFileELF();
67 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
68 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
69 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
73 // Use _setjmp/_longjmp instead of setjmp/longjmp.
74 setUseUnderscoreSetJmp(true);
75 setUseUnderscoreLongJmp(true);
77 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
78 // arguments are at least 4/8 bytes aligned.
79 bool isPPC64 = Subtarget->isPPC64();
80 setMinStackArgumentAlignment(isPPC64 ? 8:4);
82 // Set up the register classes.
83 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
84 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
85 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
87 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
88 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
91 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
93 // PowerPC has pre-inc load and store's.
94 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
101 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
102 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
103 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
105 // This is used in the ppcf128->int sequence. Note it has different semantics
106 // from FP_ROUND: that rounds to nearest, this rounds to zero.
107 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
109 // We do not currently implement these libm ops for PowerPC.
110 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
111 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
112 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
113 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
114 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
116 // PowerPC has no SREM/UREM instructions
117 setOperationAction(ISD::SREM, MVT::i32, Expand);
118 setOperationAction(ISD::UREM, MVT::i32, Expand);
119 setOperationAction(ISD::SREM, MVT::i64, Expand);
120 setOperationAction(ISD::UREM, MVT::i64, Expand);
122 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
123 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
124 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
125 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
126 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
127 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
128 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
129 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
130 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
132 // We don't support sin/cos/sqrt/fmod/pow
133 setOperationAction(ISD::FSIN , MVT::f64, Expand);
134 setOperationAction(ISD::FCOS , MVT::f64, Expand);
135 setOperationAction(ISD::FREM , MVT::f64, Expand);
136 setOperationAction(ISD::FPOW , MVT::f64, Expand);
137 setOperationAction(ISD::FMA , MVT::f64, Legal);
138 setOperationAction(ISD::FSIN , MVT::f32, Expand);
139 setOperationAction(ISD::FCOS , MVT::f32, Expand);
140 setOperationAction(ISD::FREM , MVT::f32, Expand);
141 setOperationAction(ISD::FPOW , MVT::f32, Expand);
142 setOperationAction(ISD::FMA , MVT::f32, Legal);
144 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
146 // If we're enabling GP optimizations, use hardware square root
147 if (!Subtarget->hasFSQRT()) {
148 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
149 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
152 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
153 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
155 // PowerPC does not have BSWAP, CTPOP or CTTZ
156 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
157 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
158 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
159 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
160 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
161 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
162 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
163 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
164 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
165 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
167 // PowerPC does not have ROTR
168 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
169 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
171 // PowerPC does not have Select
172 setOperationAction(ISD::SELECT, MVT::i32, Expand);
173 setOperationAction(ISD::SELECT, MVT::i64, Expand);
174 setOperationAction(ISD::SELECT, MVT::f32, Expand);
175 setOperationAction(ISD::SELECT, MVT::f64, Expand);
177 // PowerPC wants to turn select_cc of FP into fsel when possible.
178 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
179 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
181 // PowerPC wants to optimize integer setcc a bit
182 setOperationAction(ISD::SETCC, MVT::i32, Custom);
184 // PowerPC does not have BRCOND which requires SetCC
185 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
187 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
189 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
190 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
192 // PowerPC does not have [U|S]INT_TO_FP
193 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
194 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
196 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
197 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
198 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
199 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
201 // We cannot sextinreg(i1). Expand to shifts.
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
204 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
205 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
206 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
207 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
210 // We want to legalize GlobalAddress and ConstantPool nodes into the
211 // appropriate instructions to materialize the address.
212 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
213 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
214 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
215 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
216 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
217 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
218 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
219 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
220 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
221 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
224 setOperationAction(ISD::TRAP, MVT::Other, Legal);
226 // TRAMPOLINE is custom lowered.
227 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
228 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
230 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
231 setOperationAction(ISD::VASTART , MVT::Other, Custom);
233 if (Subtarget->isSVR4ABI()) {
235 // VAARG always uses double-word chunks, so promote anything smaller.
236 setOperationAction(ISD::VAARG, MVT::i1, Promote);
237 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
238 setOperationAction(ISD::VAARG, MVT::i8, Promote);
239 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
240 setOperationAction(ISD::VAARG, MVT::i16, Promote);
241 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
242 setOperationAction(ISD::VAARG, MVT::i32, Promote);
243 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
244 setOperationAction(ISD::VAARG, MVT::Other, Expand);
246 // VAARG is custom lowered with the 32-bit SVR4 ABI.
247 setOperationAction(ISD::VAARG, MVT::Other, Custom);
248 setOperationAction(ISD::VAARG, MVT::i64, Custom);
251 setOperationAction(ISD::VAARG, MVT::Other, Expand);
253 // Use the default implementation.
254 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
255 setOperationAction(ISD::VAEND , MVT::Other, Expand);
256 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
258 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
259 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
261 // We want to custom lower some of our intrinsics.
262 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
264 // Comparisons that require checking two conditions.
265 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
266 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
267 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
268 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
269 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
270 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
271 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
272 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
273 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
274 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
275 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
276 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
278 if (Subtarget->has64BitSupport()) {
279 // They also have instructions for converting between i64 and fp.
280 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
281 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
282 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
283 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
284 // This is just the low 32 bits of a (signed) fp->i64 conversion.
285 // We cannot do this with Promote because i64 is not a legal type.
286 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
288 // FIXME: disable this lowered code. This generates 64-bit register values,
289 // and we don't model the fact that the top part is clobbered by calls. We
290 // need to flag these together so that the value isn't live across a call.
291 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
293 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
294 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
297 if (Subtarget->use64BitRegs()) {
298 // 64-bit PowerPC implementations can support i64 types directly
299 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
300 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
301 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
302 // 64-bit PowerPC wants to expand i128 shifts itself.
303 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
304 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
305 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
307 // 32-bit PowerPC wants to expand i64 shifts itself.
308 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
310 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
313 if (Subtarget->hasAltivec()) {
314 // First set operation action for all vector types to expand. Then we
315 // will selectively turn on ones that can be effectively codegen'd.
316 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
317 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
318 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
320 // add/sub are legal for all supported vector VT's.
321 setOperationAction(ISD::ADD , VT, Legal);
322 setOperationAction(ISD::SUB , VT, Legal);
324 // We promote all shuffles to v16i8.
325 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
326 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
328 // We promote all non-typed operations to v4i32.
329 setOperationAction(ISD::AND , VT, Promote);
330 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
331 setOperationAction(ISD::OR , VT, Promote);
332 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
333 setOperationAction(ISD::XOR , VT, Promote);
334 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
335 setOperationAction(ISD::LOAD , VT, Promote);
336 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
337 setOperationAction(ISD::SELECT, VT, Promote);
338 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
339 setOperationAction(ISD::STORE, VT, Promote);
340 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
342 // No other operations are legal.
343 setOperationAction(ISD::MUL , VT, Expand);
344 setOperationAction(ISD::SDIV, VT, Expand);
345 setOperationAction(ISD::SREM, VT, Expand);
346 setOperationAction(ISD::UDIV, VT, Expand);
347 setOperationAction(ISD::UREM, VT, Expand);
348 setOperationAction(ISD::FDIV, VT, Expand);
349 setOperationAction(ISD::FNEG, VT, Expand);
350 setOperationAction(ISD::FSQRT, VT, Expand);
351 setOperationAction(ISD::FLOG, VT, Expand);
352 setOperationAction(ISD::FLOG10, VT, Expand);
353 setOperationAction(ISD::FLOG2, VT, Expand);
354 setOperationAction(ISD::FEXP, VT, Expand);
355 setOperationAction(ISD::FEXP2, VT, Expand);
356 setOperationAction(ISD::FSIN, VT, Expand);
357 setOperationAction(ISD::FCOS, VT, Expand);
358 setOperationAction(ISD::FABS, VT, Expand);
359 setOperationAction(ISD::FPOWI, VT, Expand);
360 setOperationAction(ISD::FFLOOR, VT, Expand);
361 setOperationAction(ISD::FCEIL, VT, Expand);
362 setOperationAction(ISD::FTRUNC, VT, Expand);
363 setOperationAction(ISD::FRINT, VT, Expand);
364 setOperationAction(ISD::FNEARBYINT, VT, Expand);
365 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
366 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
367 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
368 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
369 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
370 setOperationAction(ISD::UDIVREM, VT, Expand);
371 setOperationAction(ISD::SDIVREM, VT, Expand);
372 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
373 setOperationAction(ISD::FPOW, VT, Expand);
374 setOperationAction(ISD::CTPOP, VT, Expand);
375 setOperationAction(ISD::CTLZ, VT, Expand);
376 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
377 setOperationAction(ISD::CTTZ, VT, Expand);
378 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
379 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
381 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
382 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
383 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
384 setTruncStoreAction(VT, InnerVT, Expand);
386 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
387 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
388 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
391 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
392 // with merges, splats, etc.
393 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
395 setOperationAction(ISD::AND , MVT::v4i32, Legal);
396 setOperationAction(ISD::OR , MVT::v4i32, Legal);
397 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
398 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
399 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
400 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
401 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
402 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
403 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
404 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
405 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
406 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
407 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
408 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
410 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
411 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
412 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
413 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
415 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
416 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
417 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
418 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
419 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
421 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
422 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
424 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
425 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
426 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
427 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
429 // Altivec does not contain unordered floating-point compare instructions
430 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
431 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
432 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
433 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
434 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
435 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
438 if (Subtarget->has64BitSupport()) {
439 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
440 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
443 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
444 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
446 setBooleanContents(ZeroOrOneBooleanContent);
447 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
450 setStackPointerRegisterToSaveRestore(PPC::X1);
451 setExceptionPointerRegister(PPC::X3);
452 setExceptionSelectorRegister(PPC::X4);
454 setStackPointerRegisterToSaveRestore(PPC::R1);
455 setExceptionPointerRegister(PPC::R3);
456 setExceptionSelectorRegister(PPC::R4);
459 // We have target-specific dag combine patterns for the following nodes:
460 setTargetDAGCombine(ISD::SINT_TO_FP);
461 setTargetDAGCombine(ISD::STORE);
462 setTargetDAGCombine(ISD::BR_CC);
463 setTargetDAGCombine(ISD::BSWAP);
465 // Darwin long double math library functions have $LDBL128 appended.
466 if (Subtarget->isDarwin()) {
467 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
468 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
469 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
470 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
471 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
472 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
473 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
474 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
475 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
476 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
479 setMinFunctionAlignment(2);
480 if (PPCSubTarget.isDarwin())
481 setPrefFunctionAlignment(4);
483 if (isPPC64 && Subtarget->isJITCodeModel())
484 // Temporary workaround for the inability of PPC64 JIT to handle jump
486 setSupportJumpTables(false);
488 setInsertFencesForAtomic(true);
490 setSchedulingPreference(Sched::Hybrid);
492 computeRegisterProperties();
494 // The Freescale cores does better with aggressive inlining of memcpy and
495 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
496 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
497 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
498 maxStoresPerMemset = 32;
499 maxStoresPerMemsetOptSize = 16;
500 maxStoresPerMemcpy = 32;
501 maxStoresPerMemcpyOptSize = 8;
502 maxStoresPerMemmove = 32;
503 maxStoresPerMemmoveOptSize = 8;
505 setPrefFunctionAlignment(4);
506 benefitFromCodePlacementOpt = true;
510 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
511 /// function arguments in the caller parameter area.
512 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
513 const TargetMachine &TM = getTargetMachine();
514 // Darwin passes everything on 4 byte boundary.
515 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
518 // 16byte and wider vectors are passed on 16byte boundary.
519 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
520 if (VTy->getBitWidth() >= 128)
523 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
524 if (PPCSubTarget.isPPC64())
530 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
533 case PPCISD::FSEL: return "PPCISD::FSEL";
534 case PPCISD::FCFID: return "PPCISD::FCFID";
535 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
536 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
537 case PPCISD::STFIWX: return "PPCISD::STFIWX";
538 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
539 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
540 case PPCISD::VPERM: return "PPCISD::VPERM";
541 case PPCISD::Hi: return "PPCISD::Hi";
542 case PPCISD::Lo: return "PPCISD::Lo";
543 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
544 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
545 case PPCISD::LOAD: return "PPCISD::LOAD";
546 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
547 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
548 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
549 case PPCISD::SRL: return "PPCISD::SRL";
550 case PPCISD::SRA: return "PPCISD::SRA";
551 case PPCISD::SHL: return "PPCISD::SHL";
552 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
553 case PPCISD::STD_32: return "PPCISD::STD_32";
554 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4";
555 case PPCISD::CALL_NOP_SVR4: return "PPCISD::CALL_NOP_SVR4";
556 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin";
557 case PPCISD::NOP: return "PPCISD::NOP";
558 case PPCISD::MTCTR: return "PPCISD::MTCTR";
559 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin";
560 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4";
561 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
562 case PPCISD::MFCR: return "PPCISD::MFCR";
563 case PPCISD::VCMP: return "PPCISD::VCMP";
564 case PPCISD::VCMPo: return "PPCISD::VCMPo";
565 case PPCISD::LBRX: return "PPCISD::LBRX";
566 case PPCISD::STBRX: return "PPCISD::STBRX";
567 case PPCISD::LARX: return "PPCISD::LARX";
568 case PPCISD::STCX: return "PPCISD::STCX";
569 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
570 case PPCISD::MFFS: return "PPCISD::MFFS";
571 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
572 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
573 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
574 case PPCISD::MTFSF: return "PPCISD::MTFSF";
575 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
576 case PPCISD::CR6SET: return "PPCISD::CR6SET";
577 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
581 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
584 return VT.changeVectorElementTypeToInteger();
587 //===----------------------------------------------------------------------===//
588 // Node matching predicates, for use by the tblgen matching code.
589 //===----------------------------------------------------------------------===//
591 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
592 static bool isFloatingPointZero(SDValue Op) {
593 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
594 return CFP->getValueAPF().isZero();
595 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
596 // Maybe this has already been legalized into the constant pool?
597 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
598 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
599 return CFP->getValueAPF().isZero();
604 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
605 /// true if Op is undef or if it matches the specified value.
606 static bool isConstantOrUndef(int Op, int Val) {
607 return Op < 0 || Op == Val;
610 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
611 /// VPKUHUM instruction.
612 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
614 for (unsigned i = 0; i != 16; ++i)
615 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
618 for (unsigned i = 0; i != 8; ++i)
619 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
620 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
626 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
627 /// VPKUWUM instruction.
628 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
630 for (unsigned i = 0; i != 16; i += 2)
631 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
632 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
635 for (unsigned i = 0; i != 8; i += 2)
636 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
637 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
638 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
639 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
645 /// isVMerge - Common function, used to match vmrg* shuffles.
647 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
648 unsigned LHSStart, unsigned RHSStart) {
649 assert(N->getValueType(0) == MVT::v16i8 &&
650 "PPC only supports shuffles by bytes!");
651 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
652 "Unsupported merge size!");
654 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
655 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
656 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
657 LHSStart+j+i*UnitSize) ||
658 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
659 RHSStart+j+i*UnitSize))
665 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
666 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
667 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
670 return isVMerge(N, UnitSize, 8, 24);
671 return isVMerge(N, UnitSize, 8, 8);
674 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
675 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
676 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
679 return isVMerge(N, UnitSize, 0, 16);
680 return isVMerge(N, UnitSize, 0, 0);
684 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
685 /// amount, otherwise return -1.
686 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
687 assert(N->getValueType(0) == MVT::v16i8 &&
688 "PPC only supports shuffles by bytes!");
690 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
692 // Find the first non-undef value in the shuffle mask.
694 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
697 if (i == 16) return -1; // all undef.
699 // Otherwise, check to see if the rest of the elements are consecutively
700 // numbered from this value.
701 unsigned ShiftAmt = SVOp->getMaskElt(i);
702 if (ShiftAmt < i) return -1;
706 // Check the rest of the elements to see if they are consecutive.
707 for (++i; i != 16; ++i)
708 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
711 // Check the rest of the elements to see if they are consecutive.
712 for (++i; i != 16; ++i)
713 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
719 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
720 /// specifies a splat of a single element that is suitable for input to
721 /// VSPLTB/VSPLTH/VSPLTW.
722 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
723 assert(N->getValueType(0) == MVT::v16i8 &&
724 (EltSize == 1 || EltSize == 2 || EltSize == 4));
726 // This is a splat operation if each element of the permute is the same, and
727 // if the value doesn't reference the second vector.
728 unsigned ElementBase = N->getMaskElt(0);
730 // FIXME: Handle UNDEF elements too!
731 if (ElementBase >= 16)
734 // Check that the indices are consecutive, in the case of a multi-byte element
735 // splatted with a v16i8 mask.
736 for (unsigned i = 1; i != EltSize; ++i)
737 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
740 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
741 if (N->getMaskElt(i) < 0) continue;
742 for (unsigned j = 0; j != EltSize; ++j)
743 if (N->getMaskElt(i+j) != N->getMaskElt(j))
749 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
751 bool PPC::isAllNegativeZeroVector(SDNode *N) {
752 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
754 APInt APVal, APUndef;
758 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
759 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
760 return CFP->getValueAPF().isNegZero();
765 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
766 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
767 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
768 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
769 assert(isSplatShuffleMask(SVOp, EltSize));
770 return SVOp->getMaskElt(0) / EltSize;
773 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
774 /// by using a vspltis[bhw] instruction of the specified element size, return
775 /// the constant being splatted. The ByteSize field indicates the number of
776 /// bytes of each element [124] -> [bhw].
777 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
780 // If ByteSize of the splat is bigger than the element size of the
781 // build_vector, then we have a case where we are checking for a splat where
782 // multiple elements of the buildvector are folded together into a single
783 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
784 unsigned EltSize = 16/N->getNumOperands();
785 if (EltSize < ByteSize) {
786 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
787 SDValue UniquedVals[4];
788 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
790 // See if all of the elements in the buildvector agree across.
791 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
792 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
793 // If the element isn't a constant, bail fully out.
794 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
797 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
798 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
799 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
800 return SDValue(); // no match.
803 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
804 // either constant or undef values that are identical for each chunk. See
805 // if these chunks can form into a larger vspltis*.
807 // Check to see if all of the leading entries are either 0 or -1. If
808 // neither, then this won't fit into the immediate field.
809 bool LeadingZero = true;
810 bool LeadingOnes = true;
811 for (unsigned i = 0; i != Multiple-1; ++i) {
812 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
814 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
815 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
817 // Finally, check the least significant entry.
819 if (UniquedVals[Multiple-1].getNode() == 0)
820 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
821 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
823 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
826 if (UniquedVals[Multiple-1].getNode() == 0)
827 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
828 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
829 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
830 return DAG.getTargetConstant(Val, MVT::i32);
836 // Check to see if this buildvec has a single non-undef value in its elements.
837 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
838 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
839 if (OpVal.getNode() == 0)
840 OpVal = N->getOperand(i);
841 else if (OpVal != N->getOperand(i))
845 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
847 unsigned ValSizeInBytes = EltSize;
849 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
850 Value = CN->getZExtValue();
851 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
852 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
853 Value = FloatToBits(CN->getValueAPF().convertToFloat());
856 // If the splat value is larger than the element value, then we can never do
857 // this splat. The only case that we could fit the replicated bits into our
858 // immediate field for would be zero, and we prefer to use vxor for it.
859 if (ValSizeInBytes < ByteSize) return SDValue();
861 // If the element value is larger than the splat value, cut it in half and
862 // check to see if the two halves are equal. Continue doing this until we
863 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
864 while (ValSizeInBytes > ByteSize) {
865 ValSizeInBytes >>= 1;
867 // If the top half equals the bottom half, we're still ok.
868 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
869 (Value & ((1 << (8*ValSizeInBytes))-1)))
873 // Properly sign extend the value.
874 int MaskVal = SignExtend32(Value, ByteSize * 8);
876 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
877 if (MaskVal == 0) return SDValue();
879 // Finally, if this value fits in a 5 bit sext field, return it
880 if (SignExtend32<5>(MaskVal) == MaskVal)
881 return DAG.getTargetConstant(MaskVal, MVT::i32);
885 //===----------------------------------------------------------------------===//
886 // Addressing Mode Selection
887 //===----------------------------------------------------------------------===//
889 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
890 /// or 64-bit immediate, and if the value can be accurately represented as a
891 /// sign extension from a 16-bit value. If so, this returns true and the
893 static bool isIntS16Immediate(SDNode *N, short &Imm) {
894 if (N->getOpcode() != ISD::Constant)
897 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
898 if (N->getValueType(0) == MVT::i32)
899 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
901 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
903 static bool isIntS16Immediate(SDValue Op, short &Imm) {
904 return isIntS16Immediate(Op.getNode(), Imm);
908 /// SelectAddressRegReg - Given the specified addressed, check to see if it
909 /// can be represented as an indexed [r+r] operation. Returns false if it
910 /// can be more efficiently represented with [r+imm].
911 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
913 SelectionDAG &DAG) const {
915 if (N.getOpcode() == ISD::ADD) {
916 if (isIntS16Immediate(N.getOperand(1), imm))
918 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
921 Base = N.getOperand(0);
922 Index = N.getOperand(1);
924 } else if (N.getOpcode() == ISD::OR) {
925 if (isIntS16Immediate(N.getOperand(1), imm))
926 return false; // r+i can fold it if we can.
928 // If this is an or of disjoint bitfields, we can codegen this as an add
929 // (for better address arithmetic) if the LHS and RHS of the OR are provably
931 APInt LHSKnownZero, LHSKnownOne;
932 APInt RHSKnownZero, RHSKnownOne;
933 DAG.ComputeMaskedBits(N.getOperand(0),
934 LHSKnownZero, LHSKnownOne);
936 if (LHSKnownZero.getBoolValue()) {
937 DAG.ComputeMaskedBits(N.getOperand(1),
938 RHSKnownZero, RHSKnownOne);
939 // If all of the bits are known zero on the LHS or RHS, the add won't
941 if (~(LHSKnownZero | RHSKnownZero) == 0) {
942 Base = N.getOperand(0);
943 Index = N.getOperand(1);
952 /// Returns true if the address N can be represented by a base register plus
953 /// a signed 16-bit displacement [r+imm], and if it is not better
954 /// represented as reg+reg.
955 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
957 SelectionDAG &DAG) const {
958 // FIXME dl should come from parent load or store, not from 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)) {
967 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, 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::TargetGlobalTLSAddress ||
981 Disp.getOpcode() == ISD::TargetConstantPool ||
982 Disp.getOpcode() == ISD::TargetJumpTable);
983 Base = N.getOperand(0);
984 return true; // [&g+r]
986 } else if (N.getOpcode() == ISD::OR) {
988 if (isIntS16Immediate(N.getOperand(1), imm)) {
989 // If this is an or of disjoint bitfields, we can codegen this as an add
990 // (for better address arithmetic) if the LHS and RHS of the OR are
991 // provably disjoint.
992 APInt LHSKnownZero, LHSKnownOne;
993 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
995 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
996 // If all of the bits are known zero on the LHS or RHS, the add won't
998 Base = N.getOperand(0);
999 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1003 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1004 // Loading from a constant address.
1006 // If this address fits entirely in a 16-bit sext immediate field, codegen
1009 if (isIntS16Immediate(CN, Imm)) {
1010 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1011 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1012 CN->getValueType(0));
1016 // Handle 32-bit sext immediates with LIS + 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, MVT::i32);
1024 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1025 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1026 Base = SDValue(DAG.getMachineNode(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]
1039 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1040 /// represented as an indexed [r+r] operation.
1041 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1043 SelectionDAG &DAG) const {
1044 // Check to see if we can easily represent this as an [r+r] address. This
1045 // will fail if it thinks that the address is more profitably represented as
1046 // reg+imm, e.g. where imm = 0.
1047 if (SelectAddressRegReg(N, Base, Index, DAG))
1050 // If the operand is an addition, always emit this as [r+r], since this is
1051 // better (for code size, and execution, as the memop does the add for free)
1052 // than emitting an explicit add.
1053 if (N.getOpcode() == ISD::ADD) {
1054 Base = N.getOperand(0);
1055 Index = N.getOperand(1);
1059 // Otherwise, do it the hard way, using R0 as the base register.
1060 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1066 /// SelectAddressRegImmShift - Returns true if the address N can be
1067 /// represented by a base register plus a signed 14-bit displacement
1068 /// [r+imm*4]. Suitable for use by STD and friends.
1069 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1071 SelectionDAG &DAG) const {
1072 // FIXME dl should come from the parent load or store, not the address
1073 DebugLoc dl = N.getDebugLoc();
1074 // If this can be more profitably realized as r+r, fail.
1075 if (SelectAddressRegReg(N, Disp, Base, DAG))
1078 if (N.getOpcode() == ISD::ADD) {
1080 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1081 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1082 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1083 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1085 Base = N.getOperand(0);
1087 return true; // [r+i]
1088 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1089 // Match LOAD (ADD (X, Lo(G))).
1090 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1091 && "Cannot handle constant offsets yet!");
1092 Disp = N.getOperand(1).getOperand(0); // The global address.
1093 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1094 Disp.getOpcode() == ISD::TargetConstantPool ||
1095 Disp.getOpcode() == ISD::TargetJumpTable);
1096 Base = N.getOperand(0);
1097 return true; // [&g+r]
1099 } else if (N.getOpcode() == ISD::OR) {
1101 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1102 // If this is an or of disjoint bitfields, we can codegen this as an add
1103 // (for better address arithmetic) if the LHS and RHS of the OR are
1104 // provably disjoint.
1105 APInt LHSKnownZero, LHSKnownOne;
1106 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1107 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1108 // If all of the bits are known zero on the LHS or RHS, the add won't
1110 Base = N.getOperand(0);
1111 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1115 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1116 // Loading from a constant address. Verify low two bits are clear.
1117 if ((CN->getZExtValue() & 3) == 0) {
1118 // If this address fits entirely in a 14-bit sext immediate field, codegen
1121 if (isIntS16Immediate(CN, Imm)) {
1122 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1123 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1124 CN->getValueType(0));
1128 // Fold the low-part of 32-bit absolute addresses into addr mode.
1129 if (CN->getValueType(0) == MVT::i32 ||
1130 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1131 int Addr = (int)CN->getZExtValue();
1133 // Otherwise, break this down into an LIS + disp.
1134 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1135 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1136 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1137 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1143 Disp = DAG.getTargetConstant(0, getPointerTy());
1144 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1145 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1148 return true; // [r+0]
1152 /// getPreIndexedAddressParts - returns true by value, base pointer and
1153 /// offset pointer and addressing mode by reference if the node's address
1154 /// can be legally represented as pre-indexed load / store address.
1155 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1157 ISD::MemIndexedMode &AM,
1158 SelectionDAG &DAG) const {
1159 if (DisablePPCPreinc) return false;
1163 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1164 Ptr = LD->getBasePtr();
1165 VT = LD->getMemoryVT();
1167 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1168 Ptr = ST->getBasePtr();
1169 VT = ST->getMemoryVT();
1173 // PowerPC doesn't have preinc load/store instructions for vectors.
1177 if (SelectAddressRegReg(Ptr, Offset, Base, DAG)) {
1182 // LDU/STU use reg+imm*4, others use reg+imm.
1183 if (VT != MVT::i64) {
1185 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1189 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1193 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1194 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1195 // sext i32 to i64 when addr mode is r+i.
1196 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1197 LD->getExtensionType() == ISD::SEXTLOAD &&
1198 isa<ConstantSDNode>(Offset))
1206 //===----------------------------------------------------------------------===//
1207 // LowerOperation implementation
1208 //===----------------------------------------------------------------------===//
1210 /// GetLabelAccessInfo - Return true if we should reference labels using a
1211 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1212 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1213 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1214 HiOpFlags = PPCII::MO_HA16;
1215 LoOpFlags = PPCII::MO_LO16;
1217 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1218 // non-darwin platform. We don't support PIC on other platforms yet.
1219 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1220 TM.getSubtarget<PPCSubtarget>().isDarwin();
1222 HiOpFlags |= PPCII::MO_PIC_FLAG;
1223 LoOpFlags |= PPCII::MO_PIC_FLAG;
1226 // If this is a reference to a global value that requires a non-lazy-ptr, make
1227 // sure that instruction lowering adds it.
1228 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1229 HiOpFlags |= PPCII::MO_NLP_FLAG;
1230 LoOpFlags |= PPCII::MO_NLP_FLAG;
1232 if (GV->hasHiddenVisibility()) {
1233 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1234 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1241 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1242 SelectionDAG &DAG) {
1243 EVT PtrVT = HiPart.getValueType();
1244 SDValue Zero = DAG.getConstant(0, PtrVT);
1245 DebugLoc DL = HiPart.getDebugLoc();
1247 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1248 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1250 // With PIC, the first instruction is actually "GR+hi(&G)".
1252 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1253 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1255 // Generate non-pic code that has direct accesses to the constant pool.
1256 // The address of the global is just (hi(&g)+lo(&g)).
1257 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1260 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1261 SelectionDAG &DAG) const {
1262 EVT PtrVT = Op.getValueType();
1263 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1264 const Constant *C = CP->getConstVal();
1266 // 64-bit SVR4 ABI code is always position-independent.
1267 // The actual address of the GlobalValue is stored in the TOC.
1268 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1269 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1270 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1271 DAG.getRegister(PPC::X2, MVT::i64));
1274 unsigned MOHiFlag, MOLoFlag;
1275 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1277 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1279 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1280 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1283 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1284 EVT PtrVT = Op.getValueType();
1285 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1287 // 64-bit SVR4 ABI code is always position-independent.
1288 // The actual address of the GlobalValue is stored in the TOC.
1289 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1290 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1291 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1292 DAG.getRegister(PPC::X2, MVT::i64));
1295 unsigned MOHiFlag, MOLoFlag;
1296 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1297 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1298 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1299 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1302 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1303 SelectionDAG &DAG) const {
1304 EVT PtrVT = Op.getValueType();
1306 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1308 unsigned MOHiFlag, MOLoFlag;
1309 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1310 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1311 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1312 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1315 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1316 SelectionDAG &DAG) const {
1318 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1319 DebugLoc dl = GA->getDebugLoc();
1320 const GlobalValue *GV = GA->getGlobal();
1321 EVT PtrVT = getPointerTy();
1322 bool is64bit = PPCSubTarget.isPPC64();
1324 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1326 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1327 PPCII::MO_TPREL16_HA);
1328 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1329 PPCII::MO_TPREL16_LO);
1331 if (model != TLSModel::LocalExec)
1332 llvm_unreachable("only local-exec TLS mode supported");
1333 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1334 is64bit ? MVT::i64 : MVT::i32);
1335 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1336 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1339 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1340 SelectionDAG &DAG) const {
1341 EVT PtrVT = Op.getValueType();
1342 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1343 DebugLoc DL = GSDN->getDebugLoc();
1344 const GlobalValue *GV = GSDN->getGlobal();
1346 // 64-bit SVR4 ABI code is always position-independent.
1347 // The actual address of the GlobalValue is stored in the TOC.
1348 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1349 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1350 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1351 DAG.getRegister(PPC::X2, MVT::i64));
1354 unsigned MOHiFlag, MOLoFlag;
1355 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1358 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1360 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1362 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1364 // If the global reference is actually to a non-lazy-pointer, we have to do an
1365 // extra load to get the address of the global.
1366 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1367 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1368 false, false, false, 0);
1372 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1373 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1374 DebugLoc dl = Op.getDebugLoc();
1376 // If we're comparing for equality to zero, expose the fact that this is
1377 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1378 // fold the new nodes.
1379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1380 if (C->isNullValue() && CC == ISD::SETEQ) {
1381 EVT VT = Op.getOperand(0).getValueType();
1382 SDValue Zext = Op.getOperand(0);
1383 if (VT.bitsLT(MVT::i32)) {
1385 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1387 unsigned Log2b = Log2_32(VT.getSizeInBits());
1388 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1389 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1390 DAG.getConstant(Log2b, MVT::i32));
1391 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1393 // Leave comparisons against 0 and -1 alone for now, since they're usually
1394 // optimized. FIXME: revisit this when we can custom lower all setcc
1396 if (C->isAllOnesValue() || C->isNullValue())
1400 // If we have an integer seteq/setne, turn it into a compare against zero
1401 // by xor'ing the rhs with the lhs, which is faster than setting a
1402 // condition register, reading it back out, and masking the correct bit. The
1403 // normal approach here uses sub to do this instead of xor. Using xor exposes
1404 // the result to other bit-twiddling opportunities.
1405 EVT LHSVT = Op.getOperand(0).getValueType();
1406 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1407 EVT VT = Op.getValueType();
1408 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1410 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1415 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1416 const PPCSubtarget &Subtarget) const {
1417 SDNode *Node = Op.getNode();
1418 EVT VT = Node->getValueType(0);
1419 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1420 SDValue InChain = Node->getOperand(0);
1421 SDValue VAListPtr = Node->getOperand(1);
1422 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1423 DebugLoc dl = Node->getDebugLoc();
1425 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1428 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1429 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1431 InChain = GprIndex.getValue(1);
1433 if (VT == MVT::i64) {
1434 // Check if GprIndex is even
1435 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1436 DAG.getConstant(1, MVT::i32));
1437 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1438 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1439 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1440 DAG.getConstant(1, MVT::i32));
1441 // Align GprIndex to be even if it isn't
1442 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1446 // fpr index is 1 byte after gpr
1447 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1448 DAG.getConstant(1, MVT::i32));
1451 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1452 FprPtr, MachinePointerInfo(SV), MVT::i8,
1454 InChain = FprIndex.getValue(1);
1456 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1457 DAG.getConstant(8, MVT::i32));
1459 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1460 DAG.getConstant(4, MVT::i32));
1463 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1464 MachinePointerInfo(), false, false,
1466 InChain = OverflowArea.getValue(1);
1468 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1469 MachinePointerInfo(), false, false,
1471 InChain = RegSaveArea.getValue(1);
1473 // select overflow_area if index > 8
1474 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1475 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1477 // adjustment constant gpr_index * 4/8
1478 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1479 VT.isInteger() ? GprIndex : FprIndex,
1480 DAG.getConstant(VT.isInteger() ? 4 : 8,
1483 // OurReg = RegSaveArea + RegConstant
1484 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1487 // Floating types are 32 bytes into RegSaveArea
1488 if (VT.isFloatingPoint())
1489 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1490 DAG.getConstant(32, MVT::i32));
1492 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1493 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1494 VT.isInteger() ? GprIndex : FprIndex,
1495 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1498 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1499 VT.isInteger() ? VAListPtr : FprPtr,
1500 MachinePointerInfo(SV),
1501 MVT::i8, false, false, 0);
1503 // determine if we should load from reg_save_area or overflow_area
1504 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1506 // increase overflow_area by 4/8 if gpr/fpr > 8
1507 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1508 DAG.getConstant(VT.isInteger() ? 4 : 8,
1511 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1514 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1516 MachinePointerInfo(),
1517 MVT::i32, false, false, 0);
1519 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1520 false, false, false, 0);
1523 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1524 SelectionDAG &DAG) const {
1525 return Op.getOperand(0);
1528 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1529 SelectionDAG &DAG) const {
1530 SDValue Chain = Op.getOperand(0);
1531 SDValue Trmp = Op.getOperand(1); // trampoline
1532 SDValue FPtr = Op.getOperand(2); // nested function
1533 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1534 DebugLoc dl = Op.getDebugLoc();
1536 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1537 bool isPPC64 = (PtrVT == MVT::i64);
1539 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1542 TargetLowering::ArgListTy Args;
1543 TargetLowering::ArgListEntry Entry;
1545 Entry.Ty = IntPtrTy;
1546 Entry.Node = Trmp; Args.push_back(Entry);
1548 // TrampSize == (isPPC64 ? 48 : 40);
1549 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1550 isPPC64 ? MVT::i64 : MVT::i32);
1551 Args.push_back(Entry);
1553 Entry.Node = FPtr; Args.push_back(Entry);
1554 Entry.Node = Nest; Args.push_back(Entry);
1556 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1557 TargetLowering::CallLoweringInfo CLI(Chain,
1558 Type::getVoidTy(*DAG.getContext()),
1559 false, false, false, false, 0,
1561 /*isTailCall=*/false,
1562 /*doesNotRet=*/false,
1563 /*isReturnValueUsed=*/true,
1564 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1566 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1568 return CallResult.second;
1571 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1572 const PPCSubtarget &Subtarget) const {
1573 MachineFunction &MF = DAG.getMachineFunction();
1574 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1576 DebugLoc dl = Op.getDebugLoc();
1578 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1579 // vastart just stores the address of the VarArgsFrameIndex slot into the
1580 // memory location argument.
1581 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1582 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1583 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1584 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1585 MachinePointerInfo(SV),
1589 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1590 // We suppose the given va_list is already allocated.
1593 // char gpr; /* index into the array of 8 GPRs
1594 // * stored in the register save area
1595 // * gpr=0 corresponds to r3,
1596 // * gpr=1 to r4, etc.
1598 // char fpr; /* index into the array of 8 FPRs
1599 // * stored in the register save area
1600 // * fpr=0 corresponds to f1,
1601 // * fpr=1 to f2, etc.
1603 // char *overflow_arg_area;
1604 // /* location on stack that holds
1605 // * the next overflow argument
1607 // char *reg_save_area;
1608 // /* where r3:r10 and f1:f8 (if saved)
1614 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1615 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1618 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1620 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1622 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1625 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1626 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1628 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1629 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1631 uint64_t FPROffset = 1;
1632 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1634 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1636 // Store first byte : number of int regs
1637 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1639 MachinePointerInfo(SV),
1640 MVT::i8, false, false, 0);
1641 uint64_t nextOffset = FPROffset;
1642 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1645 // Store second byte : number of float regs
1646 SDValue secondStore =
1647 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1648 MachinePointerInfo(SV, nextOffset), MVT::i8,
1650 nextOffset += StackOffset;
1651 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1653 // Store second word : arguments given on stack
1654 SDValue thirdStore =
1655 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1656 MachinePointerInfo(SV, nextOffset),
1658 nextOffset += FrameOffset;
1659 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1661 // Store third word : arguments given in registers
1662 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1663 MachinePointerInfo(SV, nextOffset),
1668 #include "PPCGenCallingConv.inc"
1670 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1671 CCValAssign::LocInfo &LocInfo,
1672 ISD::ArgFlagsTy &ArgFlags,
1677 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1679 CCValAssign::LocInfo &LocInfo,
1680 ISD::ArgFlagsTy &ArgFlags,
1682 static const uint16_t ArgRegs[] = {
1683 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1684 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1686 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1688 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1690 // Skip one register if the first unallocated register has an even register
1691 // number and there are still argument registers available which have not been
1692 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1693 // need to skip a register if RegNum is odd.
1694 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1695 State.AllocateReg(ArgRegs[RegNum]);
1698 // Always return false here, as this function only makes sure that the first
1699 // unallocated register has an odd register number and does not actually
1700 // allocate a register for the current argument.
1704 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1706 CCValAssign::LocInfo &LocInfo,
1707 ISD::ArgFlagsTy &ArgFlags,
1709 static const uint16_t ArgRegs[] = {
1710 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1714 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1716 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1718 // If there is only one Floating-point register left we need to put both f64
1719 // values of a split ppc_fp128 value on the stack.
1720 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1721 State.AllocateReg(ArgRegs[RegNum]);
1724 // Always return false here, as this function only makes sure that the two f64
1725 // values a ppc_fp128 value is split into are both passed in registers or both
1726 // passed on the stack and does not actually allocate a register for the
1727 // current argument.
1731 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1733 static const uint16_t *GetFPR() {
1734 static const uint16_t FPR[] = {
1735 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1736 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1742 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1744 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1745 unsigned PtrByteSize) {
1746 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1747 if (Flags.isByVal())
1748 ArgSize = Flags.getByValSize();
1749 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1755 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1756 CallingConv::ID CallConv, bool isVarArg,
1757 const SmallVectorImpl<ISD::InputArg>
1759 DebugLoc dl, SelectionDAG &DAG,
1760 SmallVectorImpl<SDValue> &InVals)
1762 if (PPCSubTarget.isSVR4ABI()) {
1763 if (PPCSubTarget.isPPC64())
1764 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1767 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1770 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1776 PPCTargetLowering::LowerFormalArguments_32SVR4(
1778 CallingConv::ID CallConv, bool isVarArg,
1779 const SmallVectorImpl<ISD::InputArg>
1781 DebugLoc dl, SelectionDAG &DAG,
1782 SmallVectorImpl<SDValue> &InVals) const {
1784 // 32-bit SVR4 ABI Stack Frame Layout:
1785 // +-----------------------------------+
1786 // +--> | Back chain |
1787 // | +-----------------------------------+
1788 // | | Floating-point register save area |
1789 // | +-----------------------------------+
1790 // | | General register save area |
1791 // | +-----------------------------------+
1792 // | | CR save word |
1793 // | +-----------------------------------+
1794 // | | VRSAVE save word |
1795 // | +-----------------------------------+
1796 // | | Alignment padding |
1797 // | +-----------------------------------+
1798 // | | Vector register save area |
1799 // | +-----------------------------------+
1800 // | | Local variable space |
1801 // | +-----------------------------------+
1802 // | | Parameter list area |
1803 // | +-----------------------------------+
1804 // | | LR save word |
1805 // | +-----------------------------------+
1806 // SP--> +--- | Back chain |
1807 // +-----------------------------------+
1810 // System V Application Binary Interface PowerPC Processor Supplement
1811 // AltiVec Technology Programming Interface Manual
1813 MachineFunction &MF = DAG.getMachineFunction();
1814 MachineFrameInfo *MFI = MF.getFrameInfo();
1815 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1817 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1818 // Potential tail calls could cause overwriting of argument stack slots.
1819 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1820 (CallConv == CallingConv::Fast));
1821 unsigned PtrByteSize = 4;
1823 // Assign locations to all of the incoming arguments.
1824 SmallVector<CCValAssign, 16> ArgLocs;
1825 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1826 getTargetMachine(), ArgLocs, *DAG.getContext());
1828 // Reserve space for the linkage area on the stack.
1829 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1831 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4);
1833 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1834 CCValAssign &VA = ArgLocs[i];
1836 // Arguments stored in registers.
1837 if (VA.isRegLoc()) {
1838 const TargetRegisterClass *RC;
1839 EVT ValVT = VA.getValVT();
1841 switch (ValVT.getSimpleVT().SimpleTy) {
1843 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1845 RC = &PPC::GPRCRegClass;
1848 RC = &PPC::F4RCRegClass;
1851 RC = &PPC::F8RCRegClass;
1857 RC = &PPC::VRRCRegClass;
1861 // Transform the arguments stored in physical registers into virtual ones.
1862 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1863 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1865 InVals.push_back(ArgValue);
1867 // Argument stored in memory.
1868 assert(VA.isMemLoc());
1870 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1871 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1874 // Create load nodes to retrieve arguments from the stack.
1875 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1876 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1877 MachinePointerInfo(),
1878 false, false, false, 0));
1882 // Assign locations to all of the incoming aggregate by value arguments.
1883 // Aggregates passed by value are stored in the local variable space of the
1884 // caller's stack frame, right above the parameter list area.
1885 SmallVector<CCValAssign, 16> ByValArgLocs;
1886 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1887 getTargetMachine(), ByValArgLocs, *DAG.getContext());
1889 // Reserve stack space for the allocations in CCInfo.
1890 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1892 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4_ByVal);
1894 // Area that is at least reserved in the caller of this function.
1895 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1897 // Set the size that is at least reserved in caller of this function. Tail
1898 // call optimized function's reserved stack space needs to be aligned so that
1899 // taking the difference between two stack areas will result in an aligned
1901 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1904 std::max(MinReservedArea,
1905 PPCFrameLowering::getMinCallFrameSize(false, false));
1907 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
1908 getStackAlignment();
1909 unsigned AlignMask = TargetAlign-1;
1910 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1912 FI->setMinReservedArea(MinReservedArea);
1914 SmallVector<SDValue, 8> MemOps;
1916 // If the function takes variable number of arguments, make a frame index for
1917 // the start of the first vararg value... for expansion of llvm.va_start.
1919 static const uint16_t GPArgRegs[] = {
1920 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1921 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1923 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
1925 static const uint16_t FPArgRegs[] = {
1926 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1929 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
1931 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
1933 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
1936 // Make room for NumGPArgRegs and NumFPArgRegs.
1937 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
1938 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
1940 FuncInfo->setVarArgsStackOffset(
1941 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1942 CCInfo.getNextStackOffset(), true));
1944 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
1945 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1947 // The fixed integer arguments of a variadic function are stored to the
1948 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
1949 // the result of va_next.
1950 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
1951 // Get an existing live-in vreg, or add a new one.
1952 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
1954 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
1956 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
1957 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1958 MachinePointerInfo(), false, false, 0);
1959 MemOps.push_back(Store);
1960 // Increment the address by four for the next argument to store
1961 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1962 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1965 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
1967 // The double arguments are stored to the VarArgsFrameIndex
1969 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
1970 // Get an existing live-in vreg, or add a new one.
1971 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
1973 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
1975 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
1976 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1977 MachinePointerInfo(), false, false, 0);
1978 MemOps.push_back(Store);
1979 // Increment the address by eight for the next argument to store
1980 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
1982 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1986 if (!MemOps.empty())
1987 Chain = DAG.getNode(ISD::TokenFactor, dl,
1988 MVT::Other, &MemOps[0], MemOps.size());
1993 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
1994 // value to MVT::i64 and then truncate to the correct register size.
1996 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
1997 SelectionDAG &DAG, SDValue ArgVal,
1998 DebugLoc dl) const {
2000 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2001 DAG.getValueType(ObjectVT));
2002 else if (Flags.isZExt())
2003 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2004 DAG.getValueType(ObjectVT));
2006 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2009 // Set the size that is at least reserved in caller of this function. Tail
2010 // call optimized functions' reserved stack space needs to be aligned so that
2011 // taking the difference between two stack areas will result in an aligned
2014 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2015 unsigned nAltivecParamsAtEnd,
2016 unsigned MinReservedArea,
2017 bool isPPC64) const {
2018 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2019 // Add the Altivec parameters at the end, if needed.
2020 if (nAltivecParamsAtEnd) {
2021 MinReservedArea = ((MinReservedArea+15)/16)*16;
2022 MinReservedArea += 16*nAltivecParamsAtEnd;
2025 std::max(MinReservedArea,
2026 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2027 unsigned TargetAlign
2028 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2029 getStackAlignment();
2030 unsigned AlignMask = TargetAlign-1;
2031 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2032 FI->setMinReservedArea(MinReservedArea);
2036 PPCTargetLowering::LowerFormalArguments_64SVR4(
2038 CallingConv::ID CallConv, bool isVarArg,
2039 const SmallVectorImpl<ISD::InputArg>
2041 DebugLoc dl, SelectionDAG &DAG,
2042 SmallVectorImpl<SDValue> &InVals) const {
2043 // TODO: add description of PPC stack frame format, or at least some docs.
2045 MachineFunction &MF = DAG.getMachineFunction();
2046 MachineFrameInfo *MFI = MF.getFrameInfo();
2047 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2049 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2050 // Potential tail calls could cause overwriting of argument stack slots.
2051 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2052 (CallConv == CallingConv::Fast));
2053 unsigned PtrByteSize = 8;
2055 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2056 // Area that is at least reserved in caller of this function.
2057 unsigned MinReservedArea = ArgOffset;
2059 static const uint16_t GPR[] = {
2060 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2061 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2064 static const uint16_t *FPR = GetFPR();
2066 static const uint16_t VR[] = {
2067 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2068 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2071 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2072 const unsigned Num_FPR_Regs = 13;
2073 const unsigned Num_VR_Regs = array_lengthof(VR);
2075 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2077 // Add DAG nodes to load the arguments or copy them out of registers. On
2078 // entry to a function on PPC, the arguments start after the linkage area,
2079 // although the first ones are often in registers.
2081 SmallVector<SDValue, 8> MemOps;
2082 unsigned nAltivecParamsAtEnd = 0;
2083 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2084 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2086 bool needsLoad = false;
2087 EVT ObjectVT = Ins[ArgNo].VT;
2088 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2089 unsigned ArgSize = ObjSize;
2090 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2092 unsigned CurArgOffset = ArgOffset;
2094 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2095 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2096 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2098 MinReservedArea = ((MinReservedArea+15)/16)*16;
2099 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2103 nAltivecParamsAtEnd++;
2105 // Calculate min reserved area.
2106 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2110 // FIXME the codegen can be much improved in some cases.
2111 // We do not have to keep everything in memory.
2112 if (Flags.isByVal()) {
2113 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2114 ObjSize = Flags.getByValSize();
2115 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2116 // Empty aggregate parameters do not take up registers. Examples:
2120 // etc. However, we have to provide a place-holder in InVals, so
2121 // pretend we have an 8-byte item at the current address for that
2124 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2125 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2126 InVals.push_back(FIN);
2129 // All aggregates smaller than 8 bytes must be passed right-justified.
2130 if (ObjSize < PtrByteSize)
2131 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2132 // The value of the object is its address.
2133 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2134 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2135 InVals.push_back(FIN);
2138 if (GPR_idx != Num_GPR_Regs) {
2139 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2140 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2143 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2144 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2145 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2146 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2147 MachinePointerInfo(FuncArg, CurArgOffset),
2148 ObjType, false, false, 0);
2150 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2151 // store the whole register as-is to the parameter save area
2152 // slot. The address of the parameter was already calculated
2153 // above (InVals.push_back(FIN)) to be the right-justified
2154 // offset within the slot. For this store, we need a new
2155 // frame index that points at the beginning of the slot.
2156 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2157 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2158 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2159 MachinePointerInfo(FuncArg, ArgOffset),
2163 MemOps.push_back(Store);
2166 // Whether we copied from a register or not, advance the offset
2167 // into the parameter save area by a full doubleword.
2168 ArgOffset += PtrByteSize;
2172 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2173 // Store whatever pieces of the object are in registers
2174 // to memory. ArgOffset will be the address of the beginning
2176 if (GPR_idx != Num_GPR_Regs) {
2178 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2179 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2180 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2181 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2182 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2183 MachinePointerInfo(FuncArg, ArgOffset),
2185 MemOps.push_back(Store);
2187 ArgOffset += PtrByteSize;
2189 ArgOffset += ArgSize - j;
2196 switch (ObjectVT.getSimpleVT().SimpleTy) {
2197 default: llvm_unreachable("Unhandled argument type!");
2200 if (GPR_idx != Num_GPR_Regs) {
2201 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2202 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2204 if (ObjectVT == MVT::i32)
2205 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2206 // value to MVT::i64 and then truncate to the correct register size.
2207 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2212 ArgSize = PtrByteSize;
2219 // Every 8 bytes of argument space consumes one of the GPRs available for
2220 // argument passing.
2221 if (GPR_idx != Num_GPR_Regs) {
2224 if (FPR_idx != Num_FPR_Regs) {
2227 if (ObjectVT == MVT::f32)
2228 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2230 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2232 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2236 ArgSize = PtrByteSize;
2245 // Note that vector arguments in registers don't reserve stack space,
2246 // except in varargs functions.
2247 if (VR_idx != Num_VR_Regs) {
2248 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2249 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2251 while ((ArgOffset % 16) != 0) {
2252 ArgOffset += PtrByteSize;
2253 if (GPR_idx != Num_GPR_Regs)
2257 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2261 // Vectors are aligned.
2262 ArgOffset = ((ArgOffset+15)/16)*16;
2263 CurArgOffset = ArgOffset;
2270 // We need to load the argument to a virtual register if we determined
2271 // above that we ran out of physical registers of the appropriate type.
2273 int FI = MFI->CreateFixedObject(ObjSize,
2274 CurArgOffset + (ArgSize - ObjSize),
2276 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2277 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2278 false, false, false, 0);
2281 InVals.push_back(ArgVal);
2284 // Set the size that is at least reserved in caller of this function. Tail
2285 // call optimized functions' reserved stack space needs to be aligned so that
2286 // taking the difference between two stack areas will result in an aligned
2288 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2290 // If the function takes variable number of arguments, make a frame index for
2291 // the start of the first vararg value... for expansion of llvm.va_start.
2293 int Depth = ArgOffset;
2295 FuncInfo->setVarArgsFrameIndex(
2296 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2297 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2299 // If this function is vararg, store any remaining integer argument regs
2300 // to their spots on the stack so that they may be loaded by deferencing the
2301 // result of va_next.
2302 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2303 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2304 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2305 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2306 MachinePointerInfo(), false, false, 0);
2307 MemOps.push_back(Store);
2308 // Increment the address by four for the next argument to store
2309 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2310 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2314 if (!MemOps.empty())
2315 Chain = DAG.getNode(ISD::TokenFactor, dl,
2316 MVT::Other, &MemOps[0], MemOps.size());
2322 PPCTargetLowering::LowerFormalArguments_Darwin(
2324 CallingConv::ID CallConv, bool isVarArg,
2325 const SmallVectorImpl<ISD::InputArg>
2327 DebugLoc dl, SelectionDAG &DAG,
2328 SmallVectorImpl<SDValue> &InVals) const {
2329 // TODO: add description of PPC stack frame format, or at least some docs.
2331 MachineFunction &MF = DAG.getMachineFunction();
2332 MachineFrameInfo *MFI = MF.getFrameInfo();
2333 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2335 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2336 bool isPPC64 = PtrVT == MVT::i64;
2337 // Potential tail calls could cause overwriting of argument stack slots.
2338 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2339 (CallConv == CallingConv::Fast));
2340 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2342 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2343 // Area that is at least reserved in caller of this function.
2344 unsigned MinReservedArea = ArgOffset;
2346 static const uint16_t GPR_32[] = { // 32-bit registers.
2347 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2348 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2350 static const uint16_t GPR_64[] = { // 64-bit registers.
2351 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2352 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2355 static const uint16_t *FPR = GetFPR();
2357 static const uint16_t VR[] = {
2358 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2359 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2362 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2363 const unsigned Num_FPR_Regs = 13;
2364 const unsigned Num_VR_Regs = array_lengthof( VR);
2366 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2368 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2370 // In 32-bit non-varargs functions, the stack space for vectors is after the
2371 // stack space for non-vectors. We do not use this space unless we have
2372 // too many vectors to fit in registers, something that only occurs in
2373 // constructed examples:), but we have to walk the arglist to figure
2374 // that out...for the pathological case, compute VecArgOffset as the
2375 // start of the vector parameter area. Computing VecArgOffset is the
2376 // entire point of the following loop.
2377 unsigned VecArgOffset = ArgOffset;
2378 if (!isVarArg && !isPPC64) {
2379 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2381 EVT ObjectVT = Ins[ArgNo].VT;
2382 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2384 if (Flags.isByVal()) {
2385 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2386 unsigned ObjSize = Flags.getByValSize();
2388 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2389 VecArgOffset += ArgSize;
2393 switch(ObjectVT.getSimpleVT().SimpleTy) {
2394 default: llvm_unreachable("Unhandled argument type!");
2399 case MVT::i64: // PPC64
2401 // FIXME: We are guaranteed to be !isPPC64 at this point.
2402 // Does MVT::i64 apply?
2409 // Nothing to do, we're only looking at Nonvector args here.
2414 // We've found where the vector parameter area in memory is. Skip the
2415 // first 12 parameters; these don't use that memory.
2416 VecArgOffset = ((VecArgOffset+15)/16)*16;
2417 VecArgOffset += 12*16;
2419 // Add DAG nodes to load the arguments or copy them out of registers. On
2420 // entry to a function on PPC, the arguments start after the linkage area,
2421 // although the first ones are often in registers.
2423 SmallVector<SDValue, 8> MemOps;
2424 unsigned nAltivecParamsAtEnd = 0;
2425 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2426 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2428 bool needsLoad = false;
2429 EVT ObjectVT = Ins[ArgNo].VT;
2430 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2431 unsigned ArgSize = ObjSize;
2432 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2434 unsigned CurArgOffset = ArgOffset;
2436 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2437 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2438 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2439 if (isVarArg || isPPC64) {
2440 MinReservedArea = ((MinReservedArea+15)/16)*16;
2441 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2444 } else nAltivecParamsAtEnd++;
2446 // Calculate min reserved area.
2447 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2451 // FIXME the codegen can be much improved in some cases.
2452 // We do not have to keep everything in memory.
2453 if (Flags.isByVal()) {
2454 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2455 ObjSize = Flags.getByValSize();
2456 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2457 // Objects of size 1 and 2 are right justified, everything else is
2458 // left justified. This means the memory address is adjusted forwards.
2459 if (ObjSize==1 || ObjSize==2) {
2460 CurArgOffset = CurArgOffset + (4 - ObjSize);
2462 // The value of the object is its address.
2463 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2464 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2465 InVals.push_back(FIN);
2466 if (ObjSize==1 || ObjSize==2) {
2467 if (GPR_idx != Num_GPR_Regs) {
2470 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2472 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2473 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2474 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2475 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2476 MachinePointerInfo(FuncArg,
2478 ObjType, false, false, 0);
2479 MemOps.push_back(Store);
2483 ArgOffset += PtrByteSize;
2487 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2488 // Store whatever pieces of the object are in registers
2489 // to memory. ArgOffset will be the address of the beginning
2491 if (GPR_idx != Num_GPR_Regs) {
2494 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2496 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2497 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2498 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2499 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2500 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2501 MachinePointerInfo(FuncArg, ArgOffset),
2503 MemOps.push_back(Store);
2505 ArgOffset += PtrByteSize;
2507 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2514 switch (ObjectVT.getSimpleVT().SimpleTy) {
2515 default: llvm_unreachable("Unhandled argument type!");
2518 if (GPR_idx != Num_GPR_Regs) {
2519 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2520 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2524 ArgSize = PtrByteSize;
2526 // All int arguments reserve stack space in the Darwin ABI.
2527 ArgOffset += PtrByteSize;
2531 case MVT::i64: // PPC64
2532 if (GPR_idx != Num_GPR_Regs) {
2533 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2534 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2536 if (ObjectVT == MVT::i32)
2537 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2538 // value to MVT::i64 and then truncate to the correct register size.
2539 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2544 ArgSize = PtrByteSize;
2546 // All int arguments reserve stack space in the Darwin ABI.
2552 // Every 4 bytes of argument space consumes one of the GPRs available for
2553 // argument passing.
2554 if (GPR_idx != Num_GPR_Regs) {
2556 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2559 if (FPR_idx != Num_FPR_Regs) {
2562 if (ObjectVT == MVT::f32)
2563 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2565 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2567 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2573 // All FP arguments reserve stack space in the Darwin ABI.
2574 ArgOffset += isPPC64 ? 8 : ObjSize;
2580 // Note that vector arguments in registers don't reserve stack space,
2581 // except in varargs functions.
2582 if (VR_idx != Num_VR_Regs) {
2583 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2584 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2586 while ((ArgOffset % 16) != 0) {
2587 ArgOffset += PtrByteSize;
2588 if (GPR_idx != Num_GPR_Regs)
2592 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2596 if (!isVarArg && !isPPC64) {
2597 // Vectors go after all the nonvectors.
2598 CurArgOffset = VecArgOffset;
2601 // Vectors are aligned.
2602 ArgOffset = ((ArgOffset+15)/16)*16;
2603 CurArgOffset = ArgOffset;
2611 // We need to load the argument to a virtual register if we determined above
2612 // that we ran out of physical registers of the appropriate type.
2614 int FI = MFI->CreateFixedObject(ObjSize,
2615 CurArgOffset + (ArgSize - ObjSize),
2617 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2618 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2619 false, false, false, 0);
2622 InVals.push_back(ArgVal);
2625 // Set the size that is at least reserved in caller of this function. Tail
2626 // call optimized functions' reserved stack space needs to be aligned so that
2627 // taking the difference between two stack areas will result in an aligned
2629 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2631 // If the function takes variable number of arguments, make a frame index for
2632 // the start of the first vararg value... for expansion of llvm.va_start.
2634 int Depth = ArgOffset;
2636 FuncInfo->setVarArgsFrameIndex(
2637 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2639 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2641 // If this function is vararg, store any remaining integer argument regs
2642 // to their spots on the stack so that they may be loaded by deferencing the
2643 // result of va_next.
2644 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2648 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2650 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2652 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2653 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2654 MachinePointerInfo(), false, false, 0);
2655 MemOps.push_back(Store);
2656 // Increment the address by four for the next argument to store
2657 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2658 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2662 if (!MemOps.empty())
2663 Chain = DAG.getNode(ISD::TokenFactor, dl,
2664 MVT::Other, &MemOps[0], MemOps.size());
2669 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2670 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2672 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2676 const SmallVectorImpl<ISD::OutputArg>
2678 const SmallVectorImpl<SDValue> &OutVals,
2679 unsigned &nAltivecParamsAtEnd) {
2680 // Count how many bytes are to be pushed on the stack, including the linkage
2681 // area, and parameter passing area. We start with 24/48 bytes, which is
2682 // prereserved space for [SP][CR][LR][3 x unused].
2683 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2684 unsigned NumOps = Outs.size();
2685 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2687 // Add up all the space actually used.
2688 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2689 // they all go in registers, but we must reserve stack space for them for
2690 // possible use by the caller. In varargs or 64-bit calls, parameters are
2691 // assigned stack space in order, with padding so Altivec parameters are
2693 nAltivecParamsAtEnd = 0;
2694 for (unsigned i = 0; i != NumOps; ++i) {
2695 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2696 EVT ArgVT = Outs[i].VT;
2697 // Varargs Altivec parameters are padded to a 16 byte boundary.
2698 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2699 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2700 if (!isVarArg && !isPPC64) {
2701 // Non-varargs Altivec parameters go after all the non-Altivec
2702 // parameters; handle those later so we know how much padding we need.
2703 nAltivecParamsAtEnd++;
2706 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2707 NumBytes = ((NumBytes+15)/16)*16;
2709 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2712 // Allow for Altivec parameters at the end, if needed.
2713 if (nAltivecParamsAtEnd) {
2714 NumBytes = ((NumBytes+15)/16)*16;
2715 NumBytes += 16*nAltivecParamsAtEnd;
2718 // The prolog code of the callee may store up to 8 GPR argument registers to
2719 // the stack, allowing va_start to index over them in memory if its varargs.
2720 // Because we cannot tell if this is needed on the caller side, we have to
2721 // conservatively assume that it is needed. As such, make sure we have at
2722 // least enough stack space for the caller to store the 8 GPRs.
2723 NumBytes = std::max(NumBytes,
2724 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2726 // Tail call needs the stack to be aligned.
2727 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2728 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2729 getFrameLowering()->getStackAlignment();
2730 unsigned AlignMask = TargetAlign-1;
2731 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2737 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2738 /// adjusted to accommodate the arguments for the tailcall.
2739 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2740 unsigned ParamSize) {
2742 if (!isTailCall) return 0;
2744 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2745 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2746 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2747 // Remember only if the new adjustement is bigger.
2748 if (SPDiff < FI->getTailCallSPDelta())
2749 FI->setTailCallSPDelta(SPDiff);
2754 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2755 /// for tail call optimization. Targets which want to do tail call
2756 /// optimization should implement this function.
2758 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2759 CallingConv::ID CalleeCC,
2761 const SmallVectorImpl<ISD::InputArg> &Ins,
2762 SelectionDAG& DAG) const {
2763 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2766 // Variable argument functions are not supported.
2770 MachineFunction &MF = DAG.getMachineFunction();
2771 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2772 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2773 // Functions containing by val parameters are not supported.
2774 for (unsigned i = 0; i != Ins.size(); i++) {
2775 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2776 if (Flags.isByVal()) return false;
2779 // Non PIC/GOT tail calls are supported.
2780 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2783 // At the moment we can only do local tail calls (in same module, hidden
2784 // or protected) if we are generating PIC.
2785 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2786 return G->getGlobal()->hasHiddenVisibility()
2787 || G->getGlobal()->hasProtectedVisibility();
2793 /// isCallCompatibleAddress - Return the immediate to use if the specified
2794 /// 32-bit value is representable in the immediate field of a BxA instruction.
2795 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2799 int Addr = C->getZExtValue();
2800 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2801 SignExtend32<26>(Addr) != Addr)
2802 return 0; // Top 6 bits have to be sext of immediate.
2804 return DAG.getConstant((int)C->getZExtValue() >> 2,
2805 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2810 struct TailCallArgumentInfo {
2815 TailCallArgumentInfo() : FrameIdx(0) {}
2820 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2822 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2824 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2825 SmallVector<SDValue, 8> &MemOpChains,
2827 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2828 SDValue Arg = TailCallArgs[i].Arg;
2829 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2830 int FI = TailCallArgs[i].FrameIdx;
2831 // Store relative to framepointer.
2832 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2833 MachinePointerInfo::getFixedStack(FI),
2838 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2839 /// the appropriate stack slot for the tail call optimized function call.
2840 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2841 MachineFunction &MF,
2850 // Calculate the new stack slot for the return address.
2851 int SlotSize = isPPC64 ? 8 : 4;
2852 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2854 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2855 NewRetAddrLoc, true);
2856 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2857 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2858 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2859 MachinePointerInfo::getFixedStack(NewRetAddr),
2862 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2863 // slot as the FP is never overwritten.
2866 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2867 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2869 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2870 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2871 MachinePointerInfo::getFixedStack(NewFPIdx),
2878 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2879 /// the position of the argument.
2881 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2882 SDValue Arg, int SPDiff, unsigned ArgOffset,
2883 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2884 int Offset = ArgOffset + SPDiff;
2885 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2886 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2887 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2888 SDValue FIN = DAG.getFrameIndex(FI, VT);
2889 TailCallArgumentInfo Info;
2891 Info.FrameIdxOp = FIN;
2893 TailCallArguments.push_back(Info);
2896 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2897 /// stack slot. Returns the chain as result and the loaded frame pointers in
2898 /// LROpOut/FPOpout. Used when tail calling.
2899 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2905 DebugLoc dl) const {
2907 // Load the LR and FP stack slot for later adjusting.
2908 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2909 LROpOut = getReturnAddrFrameIndex(DAG);
2910 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
2911 false, false, false, 0);
2912 Chain = SDValue(LROpOut.getNode(), 1);
2914 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
2915 // slot as the FP is never overwritten.
2917 FPOpOut = getFramePointerFrameIndex(DAG);
2918 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
2919 false, false, false, 0);
2920 Chain = SDValue(FPOpOut.getNode(), 1);
2926 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2927 /// by "Src" to address "Dst" of size "Size". Alignment information is
2928 /// specified by the specific parameter attribute. The copy will be passed as
2929 /// a byval function parameter.
2930 /// Sometimes what we are copying is the end of a larger object, the part that
2931 /// does not fit in registers.
2933 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2934 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2936 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2937 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2938 false, false, MachinePointerInfo(0),
2939 MachinePointerInfo(0));
2942 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
2945 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
2946 SDValue Arg, SDValue PtrOff, int SPDiff,
2947 unsigned ArgOffset, bool isPPC64, bool isTailCall,
2948 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
2949 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
2951 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2956 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2958 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2959 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2960 DAG.getConstant(ArgOffset, PtrVT));
2962 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2963 MachinePointerInfo(), false, false, 0));
2964 // Calculate and remember argument location.
2965 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
2970 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
2971 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
2972 SDValue LROp, SDValue FPOp, bool isDarwinABI,
2973 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
2974 MachineFunction &MF = DAG.getMachineFunction();
2976 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
2977 // might overwrite each other in case of tail call optimization.
2978 SmallVector<SDValue, 8> MemOpChains2;
2979 // Do not flag preceding copytoreg stuff together with the following stuff.
2981 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
2983 if (!MemOpChains2.empty())
2984 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2985 &MemOpChains2[0], MemOpChains2.size());
2987 // Store the return address to the appropriate stack slot.
2988 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
2989 isPPC64, isDarwinABI, dl);
2991 // Emit callseq_end just before tailcall node.
2992 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2993 DAG.getIntPtrConstant(0, true), InFlag);
2994 InFlag = Chain.getValue(1);
2998 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
2999 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3000 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3001 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3002 const PPCSubtarget &PPCSubTarget) {
3004 bool isPPC64 = PPCSubTarget.isPPC64();
3005 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3007 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3008 NodeTys.push_back(MVT::Other); // Returns a chain
3009 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3011 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin;
3013 bool needIndirectCall = true;
3014 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3015 // If this is an absolute destination address, use the munged value.
3016 Callee = SDValue(Dest, 0);
3017 needIndirectCall = false;
3020 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3021 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3022 // Use indirect calls for ALL functions calls in JIT mode, since the
3023 // far-call stubs may be outside relocation limits for a BL instruction.
3024 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3025 unsigned OpFlags = 0;
3026 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3027 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3028 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3029 (G->getGlobal()->isDeclaration() ||
3030 G->getGlobal()->isWeakForLinker())) {
3031 // PC-relative references to external symbols should go through $stub,
3032 // unless we're building with the leopard linker or later, which
3033 // automatically synthesizes these stubs.
3034 OpFlags = PPCII::MO_DARWIN_STUB;
3037 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3038 // every direct call is) turn it into a TargetGlobalAddress /
3039 // TargetExternalSymbol node so that legalize doesn't hack it.
3040 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3041 Callee.getValueType(),
3043 needIndirectCall = false;
3047 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3048 unsigned char OpFlags = 0;
3050 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3051 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3052 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3053 // PC-relative references to external symbols should go through $stub,
3054 // unless we're building with the leopard linker or later, which
3055 // automatically synthesizes these stubs.
3056 OpFlags = PPCII::MO_DARWIN_STUB;
3059 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3061 needIndirectCall = false;
3064 if (needIndirectCall) {
3065 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3066 // to do the call, we can't use PPCISD::CALL.
3067 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3069 if (isSVR4ABI && isPPC64) {
3070 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3071 // entry point, but to the function descriptor (the function entry point
3072 // address is part of the function descriptor though).
3073 // The function descriptor is a three doubleword structure with the
3074 // following fields: function entry point, TOC base address and
3075 // environment pointer.
3076 // Thus for a call through a function pointer, the following actions need
3078 // 1. Save the TOC of the caller in the TOC save area of its stack
3079 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3080 // 2. Load the address of the function entry point from the function
3082 // 3. Load the TOC of the callee from the function descriptor into r2.
3083 // 4. Load the environment pointer from the function descriptor into
3085 // 5. Branch to the function entry point address.
3086 // 6. On return of the callee, the TOC of the caller needs to be
3087 // restored (this is done in FinishCall()).
3089 // All those operations are flagged together to ensure that no other
3090 // operations can be scheduled in between. E.g. without flagging the
3091 // operations together, a TOC access in the caller could be scheduled
3092 // between the load of the callee TOC and the branch to the callee, which
3093 // results in the TOC access going through the TOC of the callee instead
3094 // of going through the TOC of the caller, which leads to incorrect code.
3096 // Load the address of the function entry point from the function
3098 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3099 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3100 InFlag.getNode() ? 3 : 2);
3101 Chain = LoadFuncPtr.getValue(1);
3102 InFlag = LoadFuncPtr.getValue(2);
3104 // Load environment pointer into r11.
3105 // Offset of the environment pointer within the function descriptor.
3106 SDValue PtrOff = DAG.getIntPtrConstant(16);
3108 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3109 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3111 Chain = LoadEnvPtr.getValue(1);
3112 InFlag = LoadEnvPtr.getValue(2);
3114 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3116 Chain = EnvVal.getValue(0);
3117 InFlag = EnvVal.getValue(1);
3119 // Load TOC of the callee into r2. We are using a target-specific load
3120 // with r2 hard coded, because the result of a target-independent load
3121 // would never go directly into r2, since r2 is a reserved register (which
3122 // prevents the register allocator from allocating it), resulting in an
3123 // additional register being allocated and an unnecessary move instruction
3125 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3126 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3128 Chain = LoadTOCPtr.getValue(0);
3129 InFlag = LoadTOCPtr.getValue(1);
3131 MTCTROps[0] = Chain;
3132 MTCTROps[1] = LoadFuncPtr;
3133 MTCTROps[2] = InFlag;
3136 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3137 2 + (InFlag.getNode() != 0));
3138 InFlag = Chain.getValue(1);
3141 NodeTys.push_back(MVT::Other);
3142 NodeTys.push_back(MVT::Glue);
3143 Ops.push_back(Chain);
3144 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin;
3146 // Add CTR register as callee so a bctr can be emitted later.
3148 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3151 // If this is a direct call, pass the chain and the callee.
3152 if (Callee.getNode()) {
3153 Ops.push_back(Chain);
3154 Ops.push_back(Callee);
3156 // If this is a tail call add stack pointer delta.
3158 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3160 // Add argument registers to the end of the list so that they are known live
3162 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3163 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3164 RegsToPass[i].second.getValueType()));
3170 bool isLocalCall(const SDValue &Callee)
3172 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3173 return !G->getGlobal()->isDeclaration() &&
3174 !G->getGlobal()->isWeakForLinker();
3179 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3180 CallingConv::ID CallConv, bool isVarArg,
3181 const SmallVectorImpl<ISD::InputArg> &Ins,
3182 DebugLoc dl, SelectionDAG &DAG,
3183 SmallVectorImpl<SDValue> &InVals) const {
3185 SmallVector<CCValAssign, 16> RVLocs;
3186 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3187 getTargetMachine(), RVLocs, *DAG.getContext());
3188 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3190 // Copy all of the result registers out of their specified physreg.
3191 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3192 CCValAssign &VA = RVLocs[i];
3193 assert(VA.isRegLoc() && "Can only return in registers!");
3195 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3196 VA.getLocReg(), VA.getLocVT(), InFlag);
3197 Chain = Val.getValue(1);
3198 InFlag = Val.getValue(2);
3200 switch (VA.getLocInfo()) {
3201 default: llvm_unreachable("Unknown loc info!");
3202 case CCValAssign::Full: break;
3203 case CCValAssign::AExt:
3204 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3206 case CCValAssign::ZExt:
3207 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3208 DAG.getValueType(VA.getValVT()));
3209 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3211 case CCValAssign::SExt:
3212 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3213 DAG.getValueType(VA.getValVT()));
3214 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3218 InVals.push_back(Val);
3225 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3226 bool isTailCall, bool isVarArg,
3228 SmallVector<std::pair<unsigned, SDValue>, 8>
3230 SDValue InFlag, SDValue Chain,
3232 int SPDiff, unsigned NumBytes,
3233 const SmallVectorImpl<ISD::InputArg> &Ins,
3234 SmallVectorImpl<SDValue> &InVals) const {
3235 std::vector<EVT> NodeTys;
3236 SmallVector<SDValue, 8> Ops;
3237 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3238 isTailCall, RegsToPass, Ops, NodeTys,
3241 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3242 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3243 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3245 // When performing tail call optimization the callee pops its arguments off
3246 // the stack. Account for this here so these bytes can be pushed back on in
3247 // PPCRegisterInfo::eliminateCallFramePseudoInstr.
3248 int BytesCalleePops =
3249 (CallConv == CallingConv::Fast &&
3250 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3252 // Add a register mask operand representing the call-preserved registers.
3253 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3254 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3255 assert(Mask && "Missing call preserved mask for calling convention");
3256 Ops.push_back(DAG.getRegisterMask(Mask));
3258 if (InFlag.getNode())
3259 Ops.push_back(InFlag);
3263 // If this is the first return lowered for this function, add the regs
3264 // to the liveout set for the function.
3265 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3266 SmallVector<CCValAssign, 16> RVLocs;
3267 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3268 getTargetMachine(), RVLocs, *DAG.getContext());
3269 CCInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3270 for (unsigned i = 0; i != RVLocs.size(); ++i)
3271 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3274 assert(((Callee.getOpcode() == ISD::Register &&
3275 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3276 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3277 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3278 isa<ConstantSDNode>(Callee)) &&
3279 "Expecting an global address, external symbol, absolute value or register");
3281 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3284 // Add a NOP immediately after the branch instruction when using the 64-bit
3285 // SVR4 ABI. At link time, if caller and callee are in a different module and
3286 // thus have a different TOC, the call will be replaced with a call to a stub
3287 // function which saves the current TOC, loads the TOC of the callee and
3288 // branches to the callee. The NOP will be replaced with a load instruction
3289 // which restores the TOC of the caller from the TOC save slot of the current
3290 // stack frame. If caller and callee belong to the same module (and have the
3291 // same TOC), the NOP will remain unchanged.
3293 bool needsTOCRestore = false;
3294 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3295 if (CallOpc == PPCISD::BCTRL_SVR4) {
3296 // This is a call through a function pointer.
3297 // Restore the caller TOC from the save area into R2.
3298 // See PrepareCall() for more information about calls through function
3299 // pointers in the 64-bit SVR4 ABI.
3300 // We are using a target-specific load with r2 hard coded, because the
3301 // result of a target-independent load would never go directly into r2,
3302 // since r2 is a reserved register (which prevents the register allocator
3303 // from allocating it), resulting in an additional register being
3304 // allocated and an unnecessary move instruction being generated.
3305 needsTOCRestore = true;
3306 } else if ((CallOpc == PPCISD::CALL_SVR4) && !isLocalCall(Callee)) {
3307 // Otherwise insert NOP for non-local calls.
3308 CallOpc = PPCISD::CALL_NOP_SVR4;
3312 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3313 InFlag = Chain.getValue(1);
3315 if (needsTOCRestore) {
3316 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3317 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3318 InFlag = Chain.getValue(1);
3321 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3322 DAG.getIntPtrConstant(BytesCalleePops, true),
3325 InFlag = Chain.getValue(1);
3327 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3328 Ins, dl, DAG, InVals);
3332 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3333 SmallVectorImpl<SDValue> &InVals) const {
3334 SelectionDAG &DAG = CLI.DAG;
3335 DebugLoc &dl = CLI.DL;
3336 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3337 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3338 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3339 SDValue Chain = CLI.Chain;
3340 SDValue Callee = CLI.Callee;
3341 bool &isTailCall = CLI.IsTailCall;
3342 CallingConv::ID CallConv = CLI.CallConv;
3343 bool isVarArg = CLI.IsVarArg;
3346 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3349 if (PPCSubTarget.isSVR4ABI()) {
3350 if (PPCSubTarget.isPPC64())
3351 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3352 isTailCall, Outs, OutVals, Ins,
3355 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3356 isTailCall, Outs, OutVals, Ins,
3360 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3361 isTailCall, Outs, OutVals, Ins,
3366 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3367 CallingConv::ID CallConv, bool isVarArg,
3369 const SmallVectorImpl<ISD::OutputArg> &Outs,
3370 const SmallVectorImpl<SDValue> &OutVals,
3371 const SmallVectorImpl<ISD::InputArg> &Ins,
3372 DebugLoc dl, SelectionDAG &DAG,
3373 SmallVectorImpl<SDValue> &InVals) const {
3374 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3375 // of the 32-bit SVR4 ABI stack frame layout.
3377 assert((CallConv == CallingConv::C ||
3378 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3380 unsigned PtrByteSize = 4;
3382 MachineFunction &MF = DAG.getMachineFunction();
3384 // Mark this function as potentially containing a function that contains a
3385 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3386 // and restoring the callers stack pointer in this functions epilog. This is
3387 // done because by tail calling the called function might overwrite the value
3388 // in this function's (MF) stack pointer stack slot 0(SP).
3389 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3390 CallConv == CallingConv::Fast)
3391 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3393 // Count how many bytes are to be pushed on the stack, including the linkage
3394 // area, parameter list area and the part of the local variable space which
3395 // contains copies of aggregates which are passed by value.
3397 // Assign locations to all of the outgoing arguments.
3398 SmallVector<CCValAssign, 16> ArgLocs;
3399 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3400 getTargetMachine(), ArgLocs, *DAG.getContext());
3402 // Reserve space for the linkage area on the stack.
3403 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3406 // Handle fixed and variable vector arguments differently.
3407 // Fixed vector arguments go into registers as long as registers are
3408 // available. Variable vector arguments always go into memory.
3409 unsigned NumArgs = Outs.size();
3411 for (unsigned i = 0; i != NumArgs; ++i) {
3412 MVT ArgVT = Outs[i].VT;
3413 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3416 if (Outs[i].IsFixed) {
3417 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3420 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3426 errs() << "Call operand #" << i << " has unhandled type "
3427 << EVT(ArgVT).getEVTString() << "\n";
3429 llvm_unreachable(0);
3433 // All arguments are treated the same.
3434 CCInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4);
3437 // Assign locations to all of the outgoing aggregate by value arguments.
3438 SmallVector<CCValAssign, 16> ByValArgLocs;
3439 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3440 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3442 // Reserve stack space for the allocations in CCInfo.
3443 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3445 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4_ByVal);
3447 // Size of the linkage area, parameter list area and the part of the local
3448 // space variable where copies of aggregates which are passed by value are
3450 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3452 // Calculate by how many bytes the stack has to be adjusted in case of tail
3453 // call optimization.
3454 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3456 // Adjust the stack pointer for the new arguments...
3457 // These operations are automatically eliminated by the prolog/epilog pass
3458 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3459 SDValue CallSeqStart = Chain;
3461 // Load the return address and frame pointer so it can be moved somewhere else
3464 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3467 // Set up a copy of the stack pointer for use loading and storing any
3468 // arguments that may not fit in the registers available for argument
3470 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3472 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3473 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3474 SmallVector<SDValue, 8> MemOpChains;
3476 bool seenFloatArg = false;
3477 // Walk the register/memloc assignments, inserting copies/loads.
3478 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3481 CCValAssign &VA = ArgLocs[i];
3482 SDValue Arg = OutVals[i];
3483 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3485 if (Flags.isByVal()) {
3486 // Argument is an aggregate which is passed by value, thus we need to
3487 // create a copy of it in the local variable space of the current stack
3488 // frame (which is the stack frame of the caller) and pass the address of
3489 // this copy to the callee.
3490 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3491 CCValAssign &ByValVA = ByValArgLocs[j++];
3492 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3494 // Memory reserved in the local variable space of the callers stack frame.
3495 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3497 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3498 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3500 // Create a copy of the argument in the local area of the current
3502 SDValue MemcpyCall =
3503 CreateCopyOfByValArgument(Arg, PtrOff,
3504 CallSeqStart.getNode()->getOperand(0),
3507 // This must go outside the CALLSEQ_START..END.
3508 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3509 CallSeqStart.getNode()->getOperand(1));
3510 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3511 NewCallSeqStart.getNode());
3512 Chain = CallSeqStart = NewCallSeqStart;
3514 // Pass the address of the aggregate copy on the stack either in a
3515 // physical register or in the parameter list area of the current stack
3516 // frame to the callee.
3520 if (VA.isRegLoc()) {
3521 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3522 // Put argument in a physical register.
3523 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3525 // Put argument in the parameter list area of the current stack frame.
3526 assert(VA.isMemLoc());
3527 unsigned LocMemOffset = VA.getLocMemOffset();
3530 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3531 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3533 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3534 MachinePointerInfo(),
3537 // Calculate and remember argument location.
3538 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3544 if (!MemOpChains.empty())
3545 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3546 &MemOpChains[0], MemOpChains.size());
3548 // Build a sequence of copy-to-reg nodes chained together with token chain
3549 // and flag operands which copy the outgoing args into the appropriate regs.
3551 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3552 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3553 RegsToPass[i].second, InFlag);
3554 InFlag = Chain.getValue(1);
3557 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3560 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3561 SDValue Ops[] = { Chain, InFlag };
3563 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3564 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3566 InFlag = Chain.getValue(1);
3570 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3571 false, TailCallArguments);
3573 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3574 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3578 // Copy an argument into memory, being careful to do this outside the
3579 // call sequence for the call to which the argument belongs.
3581 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3582 SDValue CallSeqStart,
3583 ISD::ArgFlagsTy Flags,
3585 DebugLoc dl) const {
3586 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3587 CallSeqStart.getNode()->getOperand(0),
3589 // The MEMCPY must go outside the CALLSEQ_START..END.
3590 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3591 CallSeqStart.getNode()->getOperand(1));
3592 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3593 NewCallSeqStart.getNode());
3594 return NewCallSeqStart;
3598 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3599 CallingConv::ID CallConv, bool isVarArg,
3601 const SmallVectorImpl<ISD::OutputArg> &Outs,
3602 const SmallVectorImpl<SDValue> &OutVals,
3603 const SmallVectorImpl<ISD::InputArg> &Ins,
3604 DebugLoc dl, SelectionDAG &DAG,
3605 SmallVectorImpl<SDValue> &InVals) const {
3607 unsigned NumOps = Outs.size();
3609 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3610 unsigned PtrByteSize = 8;
3612 MachineFunction &MF = DAG.getMachineFunction();
3614 // Mark this function as potentially containing a function that contains a
3615 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3616 // and restoring the callers stack pointer in this functions epilog. This is
3617 // done because by tail calling the called function might overwrite the value
3618 // in this function's (MF) stack pointer stack slot 0(SP).
3619 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3620 CallConv == CallingConv::Fast)
3621 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3623 unsigned nAltivecParamsAtEnd = 0;
3625 // Count how many bytes are to be pushed on the stack, including the linkage
3626 // area, and parameter passing area. We start with at least 48 bytes, which
3627 // is reserved space for [SP][CR][LR][3 x unused].
3628 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3631 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3632 Outs, OutVals, nAltivecParamsAtEnd);
3634 // Calculate by how many bytes the stack has to be adjusted in case of tail
3635 // call optimization.
3636 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3638 // To protect arguments on the stack from being clobbered in a tail call,
3639 // force all the loads to happen before doing any other lowering.
3641 Chain = DAG.getStackArgumentTokenFactor(Chain);
3643 // Adjust the stack pointer for the new arguments...
3644 // These operations are automatically eliminated by the prolog/epilog pass
3645 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3646 SDValue CallSeqStart = Chain;
3648 // Load the return address and frame pointer so it can be move somewhere else
3651 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3654 // Set up a copy of the stack pointer for use loading and storing any
3655 // arguments that may not fit in the registers available for argument
3657 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3659 // Figure out which arguments are going to go in registers, and which in
3660 // memory. Also, if this is a vararg function, floating point operations
3661 // must be stored to our stack, and loaded into integer regs as well, if
3662 // any integer regs are available for argument passing.
3663 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3664 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3666 static const uint16_t GPR[] = {
3667 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3668 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3670 static const uint16_t *FPR = GetFPR();
3672 static const uint16_t VR[] = {
3673 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3674 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3676 const unsigned NumGPRs = array_lengthof(GPR);
3677 const unsigned NumFPRs = 13;
3678 const unsigned NumVRs = array_lengthof(VR);
3680 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3681 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3683 SmallVector<SDValue, 8> MemOpChains;
3684 for (unsigned i = 0; i != NumOps; ++i) {
3685 SDValue Arg = OutVals[i];
3686 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3688 // PtrOff will be used to store the current argument to the stack if a
3689 // register cannot be found for it.
3692 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3694 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3696 // Promote integers to 64-bit values.
3697 if (Arg.getValueType() == MVT::i32) {
3698 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3699 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3700 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3703 // FIXME memcpy is used way more than necessary. Correctness first.
3704 // Note: "by value" is code for passing a structure by value, not
3706 if (Flags.isByVal()) {
3707 // Note: Size includes alignment padding, so
3708 // struct x { short a; char b; }
3709 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3710 // These are the proper values we need for right-justifying the
3711 // aggregate in a parameter register.
3712 unsigned Size = Flags.getByValSize();
3714 // An empty aggregate parameter takes up no storage and no
3719 // All aggregates smaller than 8 bytes must be passed right-justified.
3720 if (Size==1 || Size==2 || Size==4) {
3721 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3722 if (GPR_idx != NumGPRs) {
3723 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3724 MachinePointerInfo(), VT,
3726 MemOpChains.push_back(Load.getValue(1));
3727 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3729 ArgOffset += PtrByteSize;
3734 if (GPR_idx == NumGPRs && Size < 8) {
3735 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3736 PtrOff.getValueType());
3737 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3738 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3741 ArgOffset += PtrByteSize;
3744 // Copy entire object into memory. There are cases where gcc-generated
3745 // code assumes it is there, even if it could be put entirely into
3746 // registers. (This is not what the doc says.)
3748 // FIXME: The above statement is likely due to a misunderstanding of the
3749 // documents. All arguments must be copied into the parameter area BY
3750 // THE CALLEE in the event that the callee takes the address of any
3751 // formal argument. That has not yet been implemented. However, it is
3752 // reasonable to use the stack area as a staging area for the register
3755 // Skip this for small aggregates, as we will use the same slot for a
3756 // right-justified copy, below.
3758 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3762 // When a register is available, pass a small aggregate right-justified.
3763 if (Size < 8 && GPR_idx != NumGPRs) {
3764 // The easiest way to get this right-justified in a register
3765 // is to copy the structure into the rightmost portion of a
3766 // local variable slot, then load the whole slot into the
3768 // FIXME: The memcpy seems to produce pretty awful code for
3769 // small aggregates, particularly for packed ones.
3770 // FIXME: It would be preferable to use the slot in the
3771 // parameter save area instead of a new local variable.
3772 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3773 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3774 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3778 // Load the slot into the register.
3779 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3780 MachinePointerInfo(),
3781 false, false, false, 0);
3782 MemOpChains.push_back(Load.getValue(1));
3783 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3785 // Done with this argument.
3786 ArgOffset += PtrByteSize;
3790 // For aggregates larger than PtrByteSize, copy the pieces of the
3791 // object that fit into registers from the parameter save area.
3792 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3793 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3794 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3795 if (GPR_idx != NumGPRs) {
3796 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3797 MachinePointerInfo(),
3798 false, false, false, 0);
3799 MemOpChains.push_back(Load.getValue(1));
3800 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3801 ArgOffset += PtrByteSize;
3803 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3810 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3811 default: llvm_unreachable("Unexpected ValueType for argument!");
3814 if (GPR_idx != NumGPRs) {
3815 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3817 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3818 true, isTailCall, false, MemOpChains,
3819 TailCallArguments, dl);
3821 ArgOffset += PtrByteSize;
3825 if (FPR_idx != NumFPRs) {
3826 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3829 // A single float or an aggregate containing only a single float
3830 // must be passed right-justified in the stack doubleword, and
3831 // in the GPR, if one is available.
3833 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3834 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3835 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3839 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3840 MachinePointerInfo(), false, false, 0);
3841 MemOpChains.push_back(Store);
3843 // Float varargs are always shadowed in available integer registers
3844 if (GPR_idx != NumGPRs) {
3845 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3846 MachinePointerInfo(), false, false,
3848 MemOpChains.push_back(Load.getValue(1));
3849 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3851 } else if (GPR_idx != NumGPRs)
3852 // If we have any FPRs remaining, we may also have GPRs remaining.
3855 // Single-precision floating-point values are mapped to the
3856 // second (rightmost) word of the stack doubleword.
3857 if (Arg.getValueType() == MVT::f32) {
3858 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3859 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3862 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3863 true, isTailCall, false, MemOpChains,
3864 TailCallArguments, dl);
3873 // These go aligned on the stack, or in the corresponding R registers
3874 // when within range. The Darwin PPC ABI doc claims they also go in
3875 // V registers; in fact gcc does this only for arguments that are
3876 // prototyped, not for those that match the ... We do it for all
3877 // arguments, seems to work.
3878 while (ArgOffset % 16 !=0) {
3879 ArgOffset += PtrByteSize;
3880 if (GPR_idx != NumGPRs)
3883 // We could elide this store in the case where the object fits
3884 // entirely in R registers. Maybe later.
3885 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3886 DAG.getConstant(ArgOffset, PtrVT));
3887 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3888 MachinePointerInfo(), false, false, 0);
3889 MemOpChains.push_back(Store);
3890 if (VR_idx != NumVRs) {
3891 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
3892 MachinePointerInfo(),
3893 false, false, false, 0);
3894 MemOpChains.push_back(Load.getValue(1));
3895 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
3898 for (unsigned i=0; i<16; i+=PtrByteSize) {
3899 if (GPR_idx == NumGPRs)
3901 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3902 DAG.getConstant(i, PtrVT));
3903 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
3904 false, false, false, 0);
3905 MemOpChains.push_back(Load.getValue(1));
3906 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3911 // Non-varargs Altivec params generally go in registers, but have
3912 // stack space allocated at the end.
3913 if (VR_idx != NumVRs) {
3914 // Doesn't have GPR space allocated.
3915 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
3917 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3918 true, isTailCall, true, MemOpChains,
3919 TailCallArguments, dl);
3926 if (!MemOpChains.empty())
3927 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3928 &MemOpChains[0], MemOpChains.size());
3930 // Check if this is an indirect call (MTCTR/BCTRL).
3931 // See PrepareCall() for more information about calls through function
3932 // pointers in the 64-bit SVR4 ABI.
3934 !dyn_cast<GlobalAddressSDNode>(Callee) &&
3935 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
3936 !isBLACompatibleAddress(Callee, DAG)) {
3937 // Load r2 into a virtual register and store it to the TOC save area.
3938 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
3939 // TOC save area offset.
3940 SDValue PtrOff = DAG.getIntPtrConstant(40);
3941 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3942 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
3944 // R12 must contain the address of an indirect callee. This does not
3945 // mean the MTCTR instruction must use R12; it's easier to model this
3946 // as an extra parameter, so do that.
3947 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
3950 // Build a sequence of copy-to-reg nodes chained together with token chain
3951 // and flag operands which copy the outgoing args into the appropriate regs.
3953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3954 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3955 RegsToPass[i].second, InFlag);
3956 InFlag = Chain.getValue(1);
3960 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
3961 FPOp, true, TailCallArguments);
3963 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3964 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3969 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
3970 CallingConv::ID CallConv, bool isVarArg,
3972 const SmallVectorImpl<ISD::OutputArg> &Outs,
3973 const SmallVectorImpl<SDValue> &OutVals,
3974 const SmallVectorImpl<ISD::InputArg> &Ins,
3975 DebugLoc dl, SelectionDAG &DAG,
3976 SmallVectorImpl<SDValue> &InVals) const {
3978 unsigned NumOps = Outs.size();
3980 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3981 bool isPPC64 = PtrVT == MVT::i64;
3982 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3984 MachineFunction &MF = DAG.getMachineFunction();
3986 // Mark this function as potentially containing a function that contains a
3987 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3988 // and restoring the callers stack pointer in this functions epilog. This is
3989 // done because by tail calling the called function might overwrite the value
3990 // in this function's (MF) stack pointer stack slot 0(SP).
3991 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3992 CallConv == CallingConv::Fast)
3993 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3995 unsigned nAltivecParamsAtEnd = 0;
3997 // Count how many bytes are to be pushed on the stack, including the linkage
3998 // area, and parameter passing area. We start with 24/48 bytes, which is
3999 // prereserved space for [SP][CR][LR][3 x unused].
4001 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4003 nAltivecParamsAtEnd);
4005 // Calculate by how many bytes the stack has to be adjusted in case of tail
4006 // call optimization.
4007 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4009 // To protect arguments on the stack from being clobbered in a tail call,
4010 // force all the loads to happen before doing any other lowering.
4012 Chain = DAG.getStackArgumentTokenFactor(Chain);
4014 // Adjust the stack pointer for the new arguments...
4015 // These operations are automatically eliminated by the prolog/epilog pass
4016 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4017 SDValue CallSeqStart = Chain;
4019 // Load the return address and frame pointer so it can be move somewhere else
4022 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4025 // Set up a copy of the stack pointer for use loading and storing any
4026 // arguments that may not fit in the registers available for argument
4030 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4032 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4034 // Figure out which arguments are going to go in registers, and which in
4035 // memory. Also, if this is a vararg function, floating point operations
4036 // must be stored to our stack, and loaded into integer regs as well, if
4037 // any integer regs are available for argument passing.
4038 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4039 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4041 static const uint16_t GPR_32[] = { // 32-bit registers.
4042 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4043 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4045 static const uint16_t GPR_64[] = { // 64-bit registers.
4046 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4047 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4049 static const uint16_t *FPR = GetFPR();
4051 static const uint16_t VR[] = {
4052 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4053 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4055 const unsigned NumGPRs = array_lengthof(GPR_32);
4056 const unsigned NumFPRs = 13;
4057 const unsigned NumVRs = array_lengthof(VR);
4059 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4061 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4062 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4064 SmallVector<SDValue, 8> MemOpChains;
4065 for (unsigned i = 0; i != NumOps; ++i) {
4066 SDValue Arg = OutVals[i];
4067 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4069 // PtrOff will be used to store the current argument to the stack if a
4070 // register cannot be found for it.
4073 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4075 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4077 // On PPC64, promote integers to 64-bit values.
4078 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4079 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4080 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4081 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4084 // FIXME memcpy is used way more than necessary. Correctness first.
4085 // Note: "by value" is code for passing a structure by value, not
4087 if (Flags.isByVal()) {
4088 unsigned Size = Flags.getByValSize();
4089 // Very small objects are passed right-justified. Everything else is
4090 // passed left-justified.
4091 if (Size==1 || Size==2) {
4092 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4093 if (GPR_idx != NumGPRs) {
4094 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4095 MachinePointerInfo(), VT,
4097 MemOpChains.push_back(Load.getValue(1));
4098 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4100 ArgOffset += PtrByteSize;
4102 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4103 PtrOff.getValueType());
4104 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4105 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4108 ArgOffset += PtrByteSize;
4112 // Copy entire object into memory. There are cases where gcc-generated
4113 // code assumes it is there, even if it could be put entirely into
4114 // registers. (This is not what the doc says.)
4115 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4119 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4120 // copy the pieces of the object that fit into registers from the
4121 // parameter save area.
4122 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4123 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4124 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4125 if (GPR_idx != NumGPRs) {
4126 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4127 MachinePointerInfo(),
4128 false, false, false, 0);
4129 MemOpChains.push_back(Load.getValue(1));
4130 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4131 ArgOffset += PtrByteSize;
4133 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4140 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4141 default: llvm_unreachable("Unexpected ValueType for argument!");
4144 if (GPR_idx != NumGPRs) {
4145 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4147 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4148 isPPC64, isTailCall, false, MemOpChains,
4149 TailCallArguments, dl);
4151 ArgOffset += PtrByteSize;
4155 if (FPR_idx != NumFPRs) {
4156 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4159 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4160 MachinePointerInfo(), false, false, 0);
4161 MemOpChains.push_back(Store);
4163 // Float varargs are always shadowed in available integer registers
4164 if (GPR_idx != NumGPRs) {
4165 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4166 MachinePointerInfo(), false, false,
4168 MemOpChains.push_back(Load.getValue(1));
4169 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4171 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4172 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4173 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4174 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4175 MachinePointerInfo(),
4176 false, false, false, 0);
4177 MemOpChains.push_back(Load.getValue(1));
4178 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4181 // If we have any FPRs remaining, we may also have GPRs remaining.
4182 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4184 if (GPR_idx != NumGPRs)
4186 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4187 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4191 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4192 isPPC64, isTailCall, false, MemOpChains,
4193 TailCallArguments, dl);
4197 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4204 // These go aligned on the stack, or in the corresponding R registers
4205 // when within range. The Darwin PPC ABI doc claims they also go in
4206 // V registers; in fact gcc does this only for arguments that are
4207 // prototyped, not for those that match the ... We do it for all
4208 // arguments, seems to work.
4209 while (ArgOffset % 16 !=0) {
4210 ArgOffset += PtrByteSize;
4211 if (GPR_idx != NumGPRs)
4214 // We could elide this store in the case where the object fits
4215 // entirely in R registers. Maybe later.
4216 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4217 DAG.getConstant(ArgOffset, PtrVT));
4218 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4219 MachinePointerInfo(), false, false, 0);
4220 MemOpChains.push_back(Store);
4221 if (VR_idx != NumVRs) {
4222 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4223 MachinePointerInfo(),
4224 false, false, false, 0);
4225 MemOpChains.push_back(Load.getValue(1));
4226 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4229 for (unsigned i=0; i<16; i+=PtrByteSize) {
4230 if (GPR_idx == NumGPRs)
4232 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4233 DAG.getConstant(i, PtrVT));
4234 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4235 false, false, false, 0);
4236 MemOpChains.push_back(Load.getValue(1));
4237 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4242 // Non-varargs Altivec params generally go in registers, but have
4243 // stack space allocated at the end.
4244 if (VR_idx != NumVRs) {
4245 // Doesn't have GPR space allocated.
4246 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4247 } else if (nAltivecParamsAtEnd==0) {
4248 // We are emitting Altivec params in order.
4249 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4250 isPPC64, isTailCall, true, MemOpChains,
4251 TailCallArguments, dl);
4257 // If all Altivec parameters fit in registers, as they usually do,
4258 // they get stack space following the non-Altivec parameters. We
4259 // don't track this here because nobody below needs it.
4260 // If there are more Altivec parameters than fit in registers emit
4262 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4264 // Offset is aligned; skip 1st 12 params which go in V registers.
4265 ArgOffset = ((ArgOffset+15)/16)*16;
4267 for (unsigned i = 0; i != NumOps; ++i) {
4268 SDValue Arg = OutVals[i];
4269 EVT ArgType = Outs[i].VT;
4270 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4271 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4274 // We are emitting Altivec params in order.
4275 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4276 isPPC64, isTailCall, true, MemOpChains,
4277 TailCallArguments, dl);
4284 if (!MemOpChains.empty())
4285 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4286 &MemOpChains[0], MemOpChains.size());
4288 // On Darwin, R12 must contain the address of an indirect callee. This does
4289 // not mean the MTCTR instruction must use R12; it's easier to model this as
4290 // an extra parameter, so do that.
4292 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4293 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4294 !isBLACompatibleAddress(Callee, DAG))
4295 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4296 PPC::R12), Callee));
4298 // Build a sequence of copy-to-reg nodes chained together with token chain
4299 // and flag operands which copy the outgoing args into the appropriate regs.
4301 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4302 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4303 RegsToPass[i].second, InFlag);
4304 InFlag = Chain.getValue(1);
4308 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4309 FPOp, true, TailCallArguments);
4311 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4312 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4317 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4318 MachineFunction &MF, bool isVarArg,
4319 const SmallVectorImpl<ISD::OutputArg> &Outs,
4320 LLVMContext &Context) const {
4321 SmallVector<CCValAssign, 16> RVLocs;
4322 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4324 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4328 PPCTargetLowering::LowerReturn(SDValue Chain,
4329 CallingConv::ID CallConv, bool isVarArg,
4330 const SmallVectorImpl<ISD::OutputArg> &Outs,
4331 const SmallVectorImpl<SDValue> &OutVals,
4332 DebugLoc dl, SelectionDAG &DAG) const {
4334 SmallVector<CCValAssign, 16> RVLocs;
4335 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4336 getTargetMachine(), RVLocs, *DAG.getContext());
4337 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4339 // If this is the first return lowered for this function, add the regs to the
4340 // liveout set for the function.
4341 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
4342 for (unsigned i = 0; i != RVLocs.size(); ++i)
4343 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
4348 // Copy the result values into the output registers.
4349 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4350 CCValAssign &VA = RVLocs[i];
4351 assert(VA.isRegLoc() && "Can only return in registers!");
4353 SDValue Arg = OutVals[i];
4355 switch (VA.getLocInfo()) {
4356 default: llvm_unreachable("Unknown loc info!");
4357 case CCValAssign::Full: break;
4358 case CCValAssign::AExt:
4359 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4361 case CCValAssign::ZExt:
4362 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4364 case CCValAssign::SExt:
4365 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4369 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4370 Flag = Chain.getValue(1);
4374 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
4376 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
4379 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4380 const PPCSubtarget &Subtarget) const {
4381 // When we pop the dynamic allocation we need to restore the SP link.
4382 DebugLoc dl = Op.getDebugLoc();
4384 // Get the corect type for pointers.
4385 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4387 // Construct the stack pointer operand.
4388 bool isPPC64 = Subtarget.isPPC64();
4389 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4390 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4392 // Get the operands for the STACKRESTORE.
4393 SDValue Chain = Op.getOperand(0);
4394 SDValue SaveSP = Op.getOperand(1);
4396 // Load the old link SP.
4397 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4398 MachinePointerInfo(),
4399 false, false, false, 0);
4401 // Restore the stack pointer.
4402 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4404 // Store the old link SP.
4405 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4412 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4413 MachineFunction &MF = DAG.getMachineFunction();
4414 bool isPPC64 = PPCSubTarget.isPPC64();
4415 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4416 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4418 // Get current frame pointer save index. The users of this index will be
4419 // primarily DYNALLOC instructions.
4420 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4421 int RASI = FI->getReturnAddrSaveIndex();
4423 // If the frame pointer save index hasn't been defined yet.
4425 // Find out what the fix offset of the frame pointer save area.
4426 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4427 // Allocate the frame index for frame pointer save area.
4428 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4430 FI->setReturnAddrSaveIndex(RASI);
4432 return DAG.getFrameIndex(RASI, PtrVT);
4436 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4437 MachineFunction &MF = DAG.getMachineFunction();
4438 bool isPPC64 = PPCSubTarget.isPPC64();
4439 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4440 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4442 // Get current frame pointer save index. The users of this index will be
4443 // primarily DYNALLOC instructions.
4444 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4445 int FPSI = FI->getFramePointerSaveIndex();
4447 // If the frame pointer save index hasn't been defined yet.
4449 // Find out what the fix offset of the frame pointer save area.
4450 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4453 // Allocate the frame index for frame pointer save area.
4454 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4456 FI->setFramePointerSaveIndex(FPSI);
4458 return DAG.getFrameIndex(FPSI, PtrVT);
4461 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4463 const PPCSubtarget &Subtarget) const {
4465 SDValue Chain = Op.getOperand(0);
4466 SDValue Size = Op.getOperand(1);
4467 DebugLoc dl = Op.getDebugLoc();
4469 // Get the corect type for pointers.
4470 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4472 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4473 DAG.getConstant(0, PtrVT), Size);
4474 // Construct a node for the frame pointer save index.
4475 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4476 // Build a DYNALLOC node.
4477 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4478 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4479 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4482 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4484 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4485 // Not FP? Not a fsel.
4486 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4487 !Op.getOperand(2).getValueType().isFloatingPoint())
4490 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4492 // Cannot handle SETEQ/SETNE.
4493 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4495 EVT ResVT = Op.getValueType();
4496 EVT CmpVT = Op.getOperand(0).getValueType();
4497 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4498 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4499 DebugLoc dl = Op.getDebugLoc();
4501 // If the RHS of the comparison is a 0.0, we don't need to do the
4502 // subtraction at all.
4503 if (isFloatingPointZero(RHS))
4505 default: break; // SETUO etc aren't handled by fsel.
4508 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4511 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4512 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4513 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4516 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4519 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4520 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4521 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4522 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4527 default: break; // SETUO etc aren't handled by fsel.
4530 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4531 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4532 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4533 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4536 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4537 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4538 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4539 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4542 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4543 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4544 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4545 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4548 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4549 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4550 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4551 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4556 // FIXME: Split this code up when LegalizeDAGTypes lands.
4557 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4558 DebugLoc dl) const {
4559 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4560 SDValue Src = Op.getOperand(0);
4561 if (Src.getValueType() == MVT::f32)
4562 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4565 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4566 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4568 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4573 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4577 // Convert the FP value to an int value through memory.
4578 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4580 // Emit a store to the stack slot.
4581 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4582 MachinePointerInfo(), false, false, 0);
4584 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4586 if (Op.getValueType() == MVT::i32)
4587 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4588 DAG.getConstant(4, FIPtr.getValueType()));
4589 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4590 false, false, false, 0);
4593 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4594 SelectionDAG &DAG) const {
4595 DebugLoc dl = Op.getDebugLoc();
4596 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4597 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4600 if (Op.getOperand(0).getValueType() == MVT::i64) {
4601 SDValue SINT = Op.getOperand(0);
4602 // When converting to single-precision, we actually need to convert
4603 // to double-precision first and then round to single-precision.
4604 // To avoid double-rounding effects during that operation, we have
4605 // to prepare the input operand. Bits that might be truncated when
4606 // converting to double-precision are replaced by a bit that won't
4607 // be lost at this stage, but is below the single-precision rounding
4610 // However, if -enable-unsafe-fp-math is in effect, accept double
4611 // rounding to avoid the extra overhead.
4612 if (Op.getValueType() == MVT::f32 &&
4613 !DAG.getTarget().Options.UnsafeFPMath) {
4615 // Twiddle input to make sure the low 11 bits are zero. (If this
4616 // is the case, we are guaranteed the value will fit into the 53 bit
4617 // mantissa of an IEEE double-precision value without rounding.)
4618 // If any of those low 11 bits were not zero originally, make sure
4619 // bit 12 (value 2048) is set instead, so that the final rounding
4620 // to single-precision gets the correct result.
4621 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4622 SINT, DAG.getConstant(2047, MVT::i64));
4623 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4624 Round, DAG.getConstant(2047, MVT::i64));
4625 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4626 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4627 Round, DAG.getConstant(-2048, MVT::i64));
4629 // However, we cannot use that value unconditionally: if the magnitude
4630 // of the input value is small, the bit-twiddling we did above might
4631 // end up visibly changing the output. Fortunately, in that case, we
4632 // don't need to twiddle bits since the original input will convert
4633 // exactly to double-precision floating-point already. Therefore,
4634 // construct a conditional to use the original value if the top 11
4635 // bits are all sign-bit copies, and use the rounded value computed
4637 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4638 SINT, DAG.getConstant(53, MVT::i32));
4639 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4640 Cond, DAG.getConstant(1, MVT::i64));
4641 Cond = DAG.getSetCC(dl, MVT::i32,
4642 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4644 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4646 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4647 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4648 if (Op.getValueType() == MVT::f32)
4649 FP = DAG.getNode(ISD::FP_ROUND, dl,
4650 MVT::f32, FP, DAG.getIntPtrConstant(0));
4654 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4655 "Unhandled SINT_TO_FP type in custom expander!");
4656 // Since we only generate this in 64-bit mode, we can take advantage of
4657 // 64-bit registers. In particular, sign extend the input value into the
4658 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4659 // then lfd it and fcfid it.
4660 MachineFunction &MF = DAG.getMachineFunction();
4661 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4662 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4663 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4664 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4666 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4669 // STD the extended value into the stack slot.
4670 MachineMemOperand *MMO =
4671 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4672 MachineMemOperand::MOStore, 8, 8);
4673 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4675 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4676 Ops, 4, MVT::i64, MMO);
4677 // Load the value as a double.
4678 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4679 false, false, false, 0);
4681 // FCFID it and return it.
4682 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4683 if (Op.getValueType() == MVT::f32)
4684 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4688 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4689 SelectionDAG &DAG) const {
4690 DebugLoc dl = Op.getDebugLoc();
4692 The rounding mode is in bits 30:31 of FPSR, and has the following
4699 FLT_ROUNDS, on the other hand, expects the following:
4706 To perform the conversion, we do:
4707 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4710 MachineFunction &MF = DAG.getMachineFunction();
4711 EVT VT = Op.getValueType();
4712 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4713 std::vector<EVT> NodeTys;
4714 SDValue MFFSreg, InFlag;
4716 // Save FP Control Word to register
4717 NodeTys.push_back(MVT::f64); // return register
4718 NodeTys.push_back(MVT::Glue); // unused in this context
4719 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4721 // Save FP register to stack slot
4722 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4723 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4724 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4725 StackSlot, MachinePointerInfo(), false, false,0);
4727 // Load FP Control Word from low 32 bits of stack slot.
4728 SDValue Four = DAG.getConstant(4, PtrVT);
4729 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4730 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4731 false, false, false, 0);
4733 // Transform as necessary
4735 DAG.getNode(ISD::AND, dl, MVT::i32,
4736 CWD, DAG.getConstant(3, MVT::i32));
4738 DAG.getNode(ISD::SRL, dl, MVT::i32,
4739 DAG.getNode(ISD::AND, dl, MVT::i32,
4740 DAG.getNode(ISD::XOR, dl, MVT::i32,
4741 CWD, DAG.getConstant(3, MVT::i32)),
4742 DAG.getConstant(3, MVT::i32)),
4743 DAG.getConstant(1, MVT::i32));
4746 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4748 return DAG.getNode((VT.getSizeInBits() < 16 ?
4749 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4752 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4753 EVT VT = Op.getValueType();
4754 unsigned BitWidth = VT.getSizeInBits();
4755 DebugLoc dl = Op.getDebugLoc();
4756 assert(Op.getNumOperands() == 3 &&
4757 VT == Op.getOperand(1).getValueType() &&
4760 // Expand into a bunch of logical ops. Note that these ops
4761 // depend on the PPC behavior for oversized shift amounts.
4762 SDValue Lo = Op.getOperand(0);
4763 SDValue Hi = Op.getOperand(1);
4764 SDValue Amt = Op.getOperand(2);
4765 EVT AmtVT = Amt.getValueType();
4767 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4768 DAG.getConstant(BitWidth, AmtVT), Amt);
4769 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4770 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4771 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4772 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4773 DAG.getConstant(-BitWidth, AmtVT));
4774 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4775 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4776 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4777 SDValue OutOps[] = { OutLo, OutHi };
4778 return DAG.getMergeValues(OutOps, 2, dl);
4781 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4782 EVT VT = Op.getValueType();
4783 DebugLoc dl = Op.getDebugLoc();
4784 unsigned BitWidth = VT.getSizeInBits();
4785 assert(Op.getNumOperands() == 3 &&
4786 VT == Op.getOperand(1).getValueType() &&
4789 // Expand into a bunch of logical ops. Note that these ops
4790 // depend on the PPC behavior for oversized shift amounts.
4791 SDValue Lo = Op.getOperand(0);
4792 SDValue Hi = Op.getOperand(1);
4793 SDValue Amt = Op.getOperand(2);
4794 EVT AmtVT = Amt.getValueType();
4796 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4797 DAG.getConstant(BitWidth, AmtVT), Amt);
4798 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4799 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4800 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4801 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4802 DAG.getConstant(-BitWidth, AmtVT));
4803 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4804 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4805 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4806 SDValue OutOps[] = { OutLo, OutHi };
4807 return DAG.getMergeValues(OutOps, 2, dl);
4810 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4811 DebugLoc dl = Op.getDebugLoc();
4812 EVT VT = Op.getValueType();
4813 unsigned BitWidth = VT.getSizeInBits();
4814 assert(Op.getNumOperands() == 3 &&
4815 VT == Op.getOperand(1).getValueType() &&
4818 // Expand into a bunch of logical ops, followed by a select_cc.
4819 SDValue Lo = Op.getOperand(0);
4820 SDValue Hi = Op.getOperand(1);
4821 SDValue Amt = Op.getOperand(2);
4822 EVT AmtVT = Amt.getValueType();
4824 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4825 DAG.getConstant(BitWidth, AmtVT), Amt);
4826 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4827 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4828 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4829 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4830 DAG.getConstant(-BitWidth, AmtVT));
4831 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4832 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4833 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4834 Tmp4, Tmp6, ISD::SETLE);
4835 SDValue OutOps[] = { OutLo, OutHi };
4836 return DAG.getMergeValues(OutOps, 2, dl);
4839 //===----------------------------------------------------------------------===//
4840 // Vector related lowering.
4843 /// BuildSplatI - Build a canonical splati of Val with an element size of
4844 /// SplatSize. Cast the result to VT.
4845 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4846 SelectionDAG &DAG, DebugLoc dl) {
4847 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4849 static const EVT VTys[] = { // canonical VT to use for each size.
4850 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4853 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4855 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4859 EVT CanonicalVT = VTys[SplatSize-1];
4861 // Build a canonical splat for this value.
4862 SDValue Elt = DAG.getConstant(Val, MVT::i32);
4863 SmallVector<SDValue, 8> Ops;
4864 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4865 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4866 &Ops[0], Ops.size());
4867 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
4870 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
4871 /// specified intrinsic ID.
4872 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
4873 SelectionDAG &DAG, DebugLoc dl,
4874 EVT DestVT = MVT::Other) {
4875 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
4876 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4877 DAG.getConstant(IID, MVT::i32), LHS, RHS);
4880 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
4881 /// specified intrinsic ID.
4882 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
4883 SDValue Op2, SelectionDAG &DAG,
4884 DebugLoc dl, EVT DestVT = MVT::Other) {
4885 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
4886 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4887 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
4891 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
4892 /// amount. The result has the specified value type.
4893 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
4894 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4895 // Force LHS/RHS to be the right type.
4896 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
4897 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
4900 for (unsigned i = 0; i != 16; ++i)
4902 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
4903 return DAG.getNode(ISD::BITCAST, dl, VT, T);
4906 // If this is a case we can't handle, return null and let the default
4907 // expansion code take care of it. If we CAN select this case, and if it
4908 // selects to a single instruction, return Op. Otherwise, if we can codegen
4909 // this case more efficiently than a constant pool load, lower it to the
4910 // sequence of ops that should be used.
4911 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
4912 SelectionDAG &DAG) const {
4913 DebugLoc dl = Op.getDebugLoc();
4914 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
4915 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
4917 // Check if this is a splat of a constant value.
4918 APInt APSplatBits, APSplatUndef;
4919 unsigned SplatBitSize;
4921 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
4922 HasAnyUndefs, 0, true) || SplatBitSize > 32)
4925 unsigned SplatBits = APSplatBits.getZExtValue();
4926 unsigned SplatUndef = APSplatUndef.getZExtValue();
4927 unsigned SplatSize = SplatBitSize / 8;
4929 // First, handle single instruction cases.
4932 if (SplatBits == 0) {
4933 // Canonicalize all zero vectors to be v4i32.
4934 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
4935 SDValue Z = DAG.getConstant(0, MVT::i32);
4936 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
4937 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
4942 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
4943 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
4945 if (SextVal >= -16 && SextVal <= 15)
4946 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
4949 // Two instruction sequences.
4951 // If this value is in the range [-32,30] and is even, use:
4952 // tmp = VSPLTI[bhw], result = add tmp, tmp
4953 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
4954 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
4955 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
4956 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4959 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
4960 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
4962 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
4963 // Make -1 and vspltisw -1:
4964 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
4966 // Make the VSLW intrinsic, computing 0x8000_0000.
4967 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
4970 // xor by OnesV to invert it.
4971 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
4972 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4975 // Check to see if this is a wide variety of vsplti*, binop self cases.
4976 static const signed char SplatCsts[] = {
4977 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
4978 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
4981 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
4982 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
4983 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
4984 int i = SplatCsts[idx];
4986 // Figure out what shift amount will be used by altivec if shifted by i in
4988 unsigned TypeShiftAmt = i & (SplatBitSize-1);
4990 // vsplti + shl self.
4991 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
4992 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4993 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4994 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
4995 Intrinsic::ppc_altivec_vslw
4997 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4998 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5001 // vsplti + srl self.
5002 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5003 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5004 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5005 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5006 Intrinsic::ppc_altivec_vsrw
5008 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5009 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5012 // vsplti + sra self.
5013 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5014 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5015 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5016 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5017 Intrinsic::ppc_altivec_vsraw
5019 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5020 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5023 // vsplti + rol self.
5024 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5025 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5026 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5027 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5028 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5029 Intrinsic::ppc_altivec_vrlw
5031 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5032 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5035 // t = vsplti c, result = vsldoi t, t, 1
5036 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5037 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5038 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5040 // t = vsplti c, result = vsldoi t, t, 2
5041 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5042 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5043 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5045 // t = vsplti c, result = vsldoi t, t, 3
5046 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5047 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5048 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5052 // Three instruction sequences.
5054 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
5055 if (SextVal >= 0 && SextVal <= 31) {
5056 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
5057 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5058 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
5059 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5061 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
5062 if (SextVal >= -31 && SextVal <= 0) {
5063 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
5064 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5065 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
5066 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5072 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5073 /// the specified operations to build the shuffle.
5074 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5075 SDValue RHS, SelectionDAG &DAG,
5077 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5078 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5079 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5082 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5094 if (OpNum == OP_COPY) {
5095 if (LHSID == (1*9+2)*9+3) return LHS;
5096 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5100 SDValue OpLHS, OpRHS;
5101 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5102 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5106 default: llvm_unreachable("Unknown i32 permute!");
5108 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5109 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5110 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5111 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5114 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5115 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5116 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5117 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5120 for (unsigned i = 0; i != 16; ++i)
5121 ShufIdxs[i] = (i&3)+0;
5124 for (unsigned i = 0; i != 16; ++i)
5125 ShufIdxs[i] = (i&3)+4;
5128 for (unsigned i = 0; i != 16; ++i)
5129 ShufIdxs[i] = (i&3)+8;
5132 for (unsigned i = 0; i != 16; ++i)
5133 ShufIdxs[i] = (i&3)+12;
5136 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5138 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5140 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5142 EVT VT = OpLHS.getValueType();
5143 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5144 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5145 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5146 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5149 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5150 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5151 /// return the code it can be lowered into. Worst case, it can always be
5152 /// lowered into a vperm.
5153 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5154 SelectionDAG &DAG) const {
5155 DebugLoc dl = Op.getDebugLoc();
5156 SDValue V1 = Op.getOperand(0);
5157 SDValue V2 = Op.getOperand(1);
5158 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5159 EVT VT = Op.getValueType();
5161 // Cases that are handled by instructions that take permute immediates
5162 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5163 // selected by the instruction selector.
5164 if (V2.getOpcode() == ISD::UNDEF) {
5165 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5166 PPC::isSplatShuffleMask(SVOp, 2) ||
5167 PPC::isSplatShuffleMask(SVOp, 4) ||
5168 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5169 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5170 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5171 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5172 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5173 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5174 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5175 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5176 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5181 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5182 // and produce a fixed permutation. If any of these match, do not lower to
5184 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5185 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5186 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5187 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5188 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5189 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5190 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5191 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5192 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5195 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5196 // perfect shuffle table to emit an optimal matching sequence.
5197 ArrayRef<int> PermMask = SVOp->getMask();
5199 unsigned PFIndexes[4];
5200 bool isFourElementShuffle = true;
5201 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5202 unsigned EltNo = 8; // Start out undef.
5203 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5204 if (PermMask[i*4+j] < 0)
5205 continue; // Undef, ignore it.
5207 unsigned ByteSource = PermMask[i*4+j];
5208 if ((ByteSource & 3) != j) {
5209 isFourElementShuffle = false;
5214 EltNo = ByteSource/4;
5215 } else if (EltNo != ByteSource/4) {
5216 isFourElementShuffle = false;
5220 PFIndexes[i] = EltNo;
5223 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5224 // perfect shuffle vector to determine if it is cost effective to do this as
5225 // discrete instructions, or whether we should use a vperm.
5226 if (isFourElementShuffle) {
5227 // Compute the index in the perfect shuffle table.
5228 unsigned PFTableIndex =
5229 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5231 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5232 unsigned Cost = (PFEntry >> 30);
5234 // Determining when to avoid vperm is tricky. Many things affect the cost
5235 // of vperm, particularly how many times the perm mask needs to be computed.
5236 // For example, if the perm mask can be hoisted out of a loop or is already
5237 // used (perhaps because there are multiple permutes with the same shuffle
5238 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5239 // the loop requires an extra register.
5241 // As a compromise, we only emit discrete instructions if the shuffle can be
5242 // generated in 3 or fewer operations. When we have loop information
5243 // available, if this block is within a loop, we should avoid using vperm
5244 // for 3-operation perms and use a constant pool load instead.
5246 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5249 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5250 // vector that will get spilled to the constant pool.
5251 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5253 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5254 // that it is in input element units, not in bytes. Convert now.
5255 EVT EltVT = V1.getValueType().getVectorElementType();
5256 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5258 SmallVector<SDValue, 16> ResultMask;
5259 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5260 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5262 for (unsigned j = 0; j != BytesPerElement; ++j)
5263 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5267 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5268 &ResultMask[0], ResultMask.size());
5269 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5272 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5273 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5274 /// information about the intrinsic.
5275 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5277 unsigned IntrinsicID =
5278 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5281 switch (IntrinsicID) {
5282 default: return false;
5283 // Comparison predicates.
5284 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5285 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5286 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5287 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5288 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5289 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5290 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5291 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5292 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5293 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5294 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5295 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5296 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5298 // Normal Comparisons.
5299 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5300 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5301 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5302 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5303 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5304 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5305 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5306 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5307 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5308 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5309 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5310 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5311 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5316 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5317 /// lower, do it, otherwise return null.
5318 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5319 SelectionDAG &DAG) const {
5320 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5321 // opcode number of the comparison.
5322 DebugLoc dl = Op.getDebugLoc();
5325 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5326 return SDValue(); // Don't custom lower most intrinsics.
5328 // If this is a non-dot comparison, make the VCMP node and we are done.
5330 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5331 Op.getOperand(1), Op.getOperand(2),
5332 DAG.getConstant(CompareOpc, MVT::i32));
5333 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5336 // Create the PPCISD altivec 'dot' comparison node.
5338 Op.getOperand(2), // LHS
5339 Op.getOperand(3), // RHS
5340 DAG.getConstant(CompareOpc, MVT::i32)
5342 std::vector<EVT> VTs;
5343 VTs.push_back(Op.getOperand(2).getValueType());
5344 VTs.push_back(MVT::Glue);
5345 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5347 // Now that we have the comparison, emit a copy from the CR to a GPR.
5348 // This is flagged to the above dot comparison.
5349 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5350 DAG.getRegister(PPC::CR6, MVT::i32),
5351 CompNode.getValue(1));
5353 // Unpack the result based on how the target uses it.
5354 unsigned BitNo; // Bit # of CR6.
5355 bool InvertBit; // Invert result?
5356 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5357 default: // Can't happen, don't crash on invalid number though.
5358 case 0: // Return the value of the EQ bit of CR6.
5359 BitNo = 0; InvertBit = false;
5361 case 1: // Return the inverted value of the EQ bit of CR6.
5362 BitNo = 0; InvertBit = true;
5364 case 2: // Return the value of the LT bit of CR6.
5365 BitNo = 2; InvertBit = false;
5367 case 3: // Return the inverted value of the LT bit of CR6.
5368 BitNo = 2; InvertBit = true;
5372 // Shift the bit into the low position.
5373 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5374 DAG.getConstant(8-(3-BitNo), MVT::i32));
5376 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5377 DAG.getConstant(1, MVT::i32));
5379 // If we are supposed to, toggle the bit.
5381 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5382 DAG.getConstant(1, MVT::i32));
5386 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5387 SelectionDAG &DAG) const {
5388 DebugLoc dl = Op.getDebugLoc();
5389 // Create a stack slot that is 16-byte aligned.
5390 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5391 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5392 EVT PtrVT = getPointerTy();
5393 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5395 // Store the input value into Value#0 of the stack slot.
5396 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5397 Op.getOperand(0), FIdx, MachinePointerInfo(),
5400 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5401 false, false, false, 0);
5404 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5405 DebugLoc dl = Op.getDebugLoc();
5406 if (Op.getValueType() == MVT::v4i32) {
5407 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5409 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5410 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5412 SDValue RHSSwap = // = vrlw RHS, 16
5413 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5415 // Shrinkify inputs to v8i16.
5416 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5417 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5418 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5420 // Low parts multiplied together, generating 32-bit results (we ignore the
5422 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5423 LHS, RHS, DAG, dl, MVT::v4i32);
5425 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5426 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5427 // Shift the high parts up 16 bits.
5428 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5430 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5431 } else if (Op.getValueType() == MVT::v8i16) {
5432 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5434 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5436 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5437 LHS, RHS, Zero, DAG, dl);
5438 } else if (Op.getValueType() == MVT::v16i8) {
5439 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5441 // Multiply the even 8-bit parts, producing 16-bit sums.
5442 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5443 LHS, RHS, DAG, dl, MVT::v8i16);
5444 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5446 // Multiply the odd 8-bit parts, producing 16-bit sums.
5447 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5448 LHS, RHS, DAG, dl, MVT::v8i16);
5449 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5451 // Merge the results together.
5453 for (unsigned i = 0; i != 8; ++i) {
5455 Ops[i*2+1] = 2*i+1+16;
5457 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5459 llvm_unreachable("Unknown mul to lower!");
5463 /// LowerOperation - Provide custom lowering hooks for some operations.
5465 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5466 switch (Op.getOpcode()) {
5467 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5468 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5469 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5470 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5471 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5472 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5473 case ISD::SETCC: return LowerSETCC(Op, DAG);
5474 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5475 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5477 return LowerVASTART(Op, DAG, PPCSubTarget);
5480 return LowerVAARG(Op, DAG, PPCSubTarget);
5482 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5483 case ISD::DYNAMIC_STACKALLOC:
5484 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5486 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5487 case ISD::FP_TO_UINT:
5488 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5490 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5491 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5493 // Lower 64-bit shifts.
5494 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5495 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5496 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5498 // Vector-related lowering.
5499 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5500 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5501 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5502 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5503 case ISD::MUL: return LowerMUL(Op, DAG);
5505 // Frame & Return address.
5506 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5507 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5511 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5512 SmallVectorImpl<SDValue>&Results,
5513 SelectionDAG &DAG) const {
5514 const TargetMachine &TM = getTargetMachine();
5515 DebugLoc dl = N->getDebugLoc();
5516 switch (N->getOpcode()) {
5518 llvm_unreachable("Do not know how to custom type legalize this operation!");
5520 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5521 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5524 EVT VT = N->getValueType(0);
5526 if (VT == MVT::i64) {
5527 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5529 Results.push_back(NewNode);
5530 Results.push_back(NewNode.getValue(1));
5534 case ISD::FP_ROUND_INREG: {
5535 assert(N->getValueType(0) == MVT::ppcf128);
5536 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5537 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5538 MVT::f64, N->getOperand(0),
5539 DAG.getIntPtrConstant(0));
5540 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5541 MVT::f64, N->getOperand(0),
5542 DAG.getIntPtrConstant(1));
5544 // This sequence changes FPSCR to do round-to-zero, adds the two halves
5545 // of the long double, and puts FPSCR back the way it was. We do not
5546 // actually model FPSCR.
5547 std::vector<EVT> NodeTys;
5548 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
5550 NodeTys.push_back(MVT::f64); // Return register
5551 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns
5552 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5553 MFFSreg = Result.getValue(0);
5554 InFlag = Result.getValue(1);
5557 NodeTys.push_back(MVT::Glue); // Returns a flag
5558 Ops[0] = DAG.getConstant(31, MVT::i32);
5560 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
5561 InFlag = Result.getValue(0);
5564 NodeTys.push_back(MVT::Glue); // Returns a flag
5565 Ops[0] = DAG.getConstant(30, MVT::i32);
5567 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
5568 InFlag = Result.getValue(0);
5571 NodeTys.push_back(MVT::f64); // result of add
5572 NodeTys.push_back(MVT::Glue); // Returns a flag
5576 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
5577 FPreg = Result.getValue(0);
5578 InFlag = Result.getValue(1);
5581 NodeTys.push_back(MVT::f64);
5582 Ops[0] = DAG.getConstant(1, MVT::i32);
5586 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
5587 FPreg = Result.getValue(0);
5589 // We know the low half is about to be thrown away, so just use something
5591 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5595 case ISD::FP_TO_SINT:
5596 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5602 //===----------------------------------------------------------------------===//
5603 // Other Lowering Code
5604 //===----------------------------------------------------------------------===//
5607 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5608 bool is64bit, unsigned BinOpcode) const {
5609 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5610 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5612 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5613 MachineFunction *F = BB->getParent();
5614 MachineFunction::iterator It = BB;
5617 unsigned dest = MI->getOperand(0).getReg();
5618 unsigned ptrA = MI->getOperand(1).getReg();
5619 unsigned ptrB = MI->getOperand(2).getReg();
5620 unsigned incr = MI->getOperand(3).getReg();
5621 DebugLoc dl = MI->getDebugLoc();
5623 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5624 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5625 F->insert(It, loopMBB);
5626 F->insert(It, exitMBB);
5627 exitMBB->splice(exitMBB->begin(), BB,
5628 llvm::next(MachineBasicBlock::iterator(MI)),
5630 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5632 MachineRegisterInfo &RegInfo = F->getRegInfo();
5633 unsigned TmpReg = (!BinOpcode) ? incr :
5634 RegInfo.createVirtualRegister(
5635 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5636 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5640 // fallthrough --> loopMBB
5641 BB->addSuccessor(loopMBB);
5644 // l[wd]arx dest, ptr
5645 // add r0, dest, incr
5646 // st[wd]cx. r0, ptr
5648 // fallthrough --> exitMBB
5650 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5651 .addReg(ptrA).addReg(ptrB);
5653 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5654 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5655 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5656 BuildMI(BB, dl, TII->get(PPC::BCC))
5657 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5658 BB->addSuccessor(loopMBB);
5659 BB->addSuccessor(exitMBB);
5668 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5669 MachineBasicBlock *BB,
5670 bool is8bit, // operation
5671 unsigned BinOpcode) const {
5672 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5673 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5674 // In 64 bit mode we have to use 64 bits for addresses, even though the
5675 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5676 // registers without caring whether they're 32 or 64, but here we're
5677 // doing actual arithmetic on the addresses.
5678 bool is64bit = PPCSubTarget.isPPC64();
5679 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
5681 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5682 MachineFunction *F = BB->getParent();
5683 MachineFunction::iterator It = BB;
5686 unsigned dest = MI->getOperand(0).getReg();
5687 unsigned ptrA = MI->getOperand(1).getReg();
5688 unsigned ptrB = MI->getOperand(2).getReg();
5689 unsigned incr = MI->getOperand(3).getReg();
5690 DebugLoc dl = MI->getDebugLoc();
5692 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5693 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5694 F->insert(It, loopMBB);
5695 F->insert(It, exitMBB);
5696 exitMBB->splice(exitMBB->begin(), BB,
5697 llvm::next(MachineBasicBlock::iterator(MI)),
5699 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5701 MachineRegisterInfo &RegInfo = F->getRegInfo();
5702 const TargetRegisterClass *RC =
5703 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5704 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5705 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5706 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5707 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5708 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5709 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5710 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5711 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5712 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5713 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5714 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5715 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5717 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5721 // fallthrough --> loopMBB
5722 BB->addSuccessor(loopMBB);
5724 // The 4-byte load must be aligned, while a char or short may be
5725 // anywhere in the word. Hence all this nasty bookkeeping code.
5726 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5727 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5728 // xori shift, shift1, 24 [16]
5729 // rlwinm ptr, ptr1, 0, 0, 29
5730 // slw incr2, incr, shift
5731 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5732 // slw mask, mask2, shift
5734 // lwarx tmpDest, ptr
5735 // add tmp, tmpDest, incr2
5736 // andc tmp2, tmpDest, mask
5737 // and tmp3, tmp, mask
5738 // or tmp4, tmp3, tmp2
5741 // fallthrough --> exitMBB
5742 // srw dest, tmpDest, shift
5743 if (ptrA != ZeroReg) {
5744 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5745 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5746 .addReg(ptrA).addReg(ptrB);
5750 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5751 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5752 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5753 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5755 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5756 .addReg(Ptr1Reg).addImm(0).addImm(61);
5758 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5759 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5760 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5761 .addReg(incr).addReg(ShiftReg);
5763 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5765 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5766 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5768 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5769 .addReg(Mask2Reg).addReg(ShiftReg);
5772 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5773 .addReg(ZeroReg).addReg(PtrReg);
5775 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5776 .addReg(Incr2Reg).addReg(TmpDestReg);
5777 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5778 .addReg(TmpDestReg).addReg(MaskReg);
5779 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5780 .addReg(TmpReg).addReg(MaskReg);
5781 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5782 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5783 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5784 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5785 BuildMI(BB, dl, TII->get(PPC::BCC))
5786 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5787 BB->addSuccessor(loopMBB);
5788 BB->addSuccessor(exitMBB);
5793 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5799 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5800 MachineBasicBlock *BB) const {
5801 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5803 // To "insert" these instructions we actually have to insert their
5804 // control-flow patterns.
5805 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5806 MachineFunction::iterator It = BB;
5809 MachineFunction *F = BB->getParent();
5811 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5812 MI->getOpcode() == PPC::SELECT_CC_I8)) {
5813 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
5814 PPC::ISEL8 : PPC::ISEL;
5815 unsigned SelectPred = MI->getOperand(4).getImm();
5816 DebugLoc dl = MI->getDebugLoc();
5818 // The SelectPred is ((BI << 5) | BO) for a BCC
5819 unsigned BO = SelectPred & 0xF;
5820 assert((BO == 12 || BO == 4) && "invalid predicate BO field for isel");
5822 unsigned TrueOpNo, FalseOpNo;
5829 SelectPred = PPC::InvertPredicate((PPC::Predicate)SelectPred);
5832 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
5833 .addReg(MI->getOperand(TrueOpNo).getReg())
5834 .addReg(MI->getOperand(FalseOpNo).getReg())
5835 .addImm(SelectPred).addReg(MI->getOperand(1).getReg());
5836 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5837 MI->getOpcode() == PPC::SELECT_CC_I8 ||
5838 MI->getOpcode() == PPC::SELECT_CC_F4 ||
5839 MI->getOpcode() == PPC::SELECT_CC_F8 ||
5840 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
5843 // The incoming instruction knows the destination vreg to set, the
5844 // condition code register to branch on, the true/false values to
5845 // select between, and a branch opcode to use.
5850 // cmpTY ccX, r1, r2
5852 // fallthrough --> copy0MBB
5853 MachineBasicBlock *thisMBB = BB;
5854 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5855 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
5856 unsigned SelectPred = MI->getOperand(4).getImm();
5857 DebugLoc dl = MI->getDebugLoc();
5858 F->insert(It, copy0MBB);
5859 F->insert(It, sinkMBB);
5861 // Transfer the remainder of BB and its successor edges to sinkMBB.
5862 sinkMBB->splice(sinkMBB->begin(), BB,
5863 llvm::next(MachineBasicBlock::iterator(MI)),
5865 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5867 // Next, add the true and fallthrough blocks as its successors.
5868 BB->addSuccessor(copy0MBB);
5869 BB->addSuccessor(sinkMBB);
5871 BuildMI(BB, dl, TII->get(PPC::BCC))
5872 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
5875 // %FalseValue = ...
5876 // # fallthrough to sinkMBB
5879 // Update machine-CFG edges
5880 BB->addSuccessor(sinkMBB);
5883 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5886 BuildMI(*BB, BB->begin(), dl,
5887 TII->get(PPC::PHI), MI->getOperand(0).getReg())
5888 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
5889 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5891 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
5892 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
5893 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
5894 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
5895 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
5896 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
5897 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
5898 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
5900 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
5901 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
5902 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
5903 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
5904 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
5905 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
5906 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
5907 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
5909 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
5910 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
5911 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
5912 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
5913 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
5914 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
5915 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
5916 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
5918 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
5919 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
5920 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
5921 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
5922 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
5923 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
5924 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
5925 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
5927 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
5928 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
5929 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
5930 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
5931 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
5932 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
5933 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
5934 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
5936 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
5937 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
5938 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
5939 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
5940 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
5941 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
5942 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
5943 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
5945 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
5946 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
5947 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
5948 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
5949 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
5950 BB = EmitAtomicBinary(MI, BB, false, 0);
5951 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
5952 BB = EmitAtomicBinary(MI, BB, true, 0);
5954 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
5955 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
5956 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
5958 unsigned dest = MI->getOperand(0).getReg();
5959 unsigned ptrA = MI->getOperand(1).getReg();
5960 unsigned ptrB = MI->getOperand(2).getReg();
5961 unsigned oldval = MI->getOperand(3).getReg();
5962 unsigned newval = MI->getOperand(4).getReg();
5963 DebugLoc dl = MI->getDebugLoc();
5965 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
5966 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
5967 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
5968 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5969 F->insert(It, loop1MBB);
5970 F->insert(It, loop2MBB);
5971 F->insert(It, midMBB);
5972 F->insert(It, exitMBB);
5973 exitMBB->splice(exitMBB->begin(), BB,
5974 llvm::next(MachineBasicBlock::iterator(MI)),
5976 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5980 // fallthrough --> loopMBB
5981 BB->addSuccessor(loop1MBB);
5984 // l[wd]arx dest, ptr
5985 // cmp[wd] dest, oldval
5988 // st[wd]cx. newval, ptr
5992 // st[wd]cx. dest, ptr
5995 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5996 .addReg(ptrA).addReg(ptrB);
5997 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
5998 .addReg(oldval).addReg(dest);
5999 BuildMI(BB, dl, TII->get(PPC::BCC))
6000 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6001 BB->addSuccessor(loop2MBB);
6002 BB->addSuccessor(midMBB);
6005 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6006 .addReg(newval).addReg(ptrA).addReg(ptrB);
6007 BuildMI(BB, dl, TII->get(PPC::BCC))
6008 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6009 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6010 BB->addSuccessor(loop1MBB);
6011 BB->addSuccessor(exitMBB);
6014 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6015 .addReg(dest).addReg(ptrA).addReg(ptrB);
6016 BB->addSuccessor(exitMBB);
6021 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6022 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6023 // We must use 64-bit registers for addresses when targeting 64-bit,
6024 // since we're actually doing arithmetic on them. Other registers
6026 bool is64bit = PPCSubTarget.isPPC64();
6027 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6029 unsigned dest = MI->getOperand(0).getReg();
6030 unsigned ptrA = MI->getOperand(1).getReg();
6031 unsigned ptrB = MI->getOperand(2).getReg();
6032 unsigned oldval = MI->getOperand(3).getReg();
6033 unsigned newval = MI->getOperand(4).getReg();
6034 DebugLoc dl = MI->getDebugLoc();
6036 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6037 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6038 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6039 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6040 F->insert(It, loop1MBB);
6041 F->insert(It, loop2MBB);
6042 F->insert(It, midMBB);
6043 F->insert(It, exitMBB);
6044 exitMBB->splice(exitMBB->begin(), BB,
6045 llvm::next(MachineBasicBlock::iterator(MI)),
6047 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6049 MachineRegisterInfo &RegInfo = F->getRegInfo();
6050 const TargetRegisterClass *RC =
6051 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6052 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6053 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6054 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6055 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6056 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6057 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6058 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6059 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6060 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6061 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6062 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6063 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6064 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6065 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6067 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6068 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
6071 // fallthrough --> loopMBB
6072 BB->addSuccessor(loop1MBB);
6074 // The 4-byte load must be aligned, while a char or short may be
6075 // anywhere in the word. Hence all this nasty bookkeeping code.
6076 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6077 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6078 // xori shift, shift1, 24 [16]
6079 // rlwinm ptr, ptr1, 0, 0, 29
6080 // slw newval2, newval, shift
6081 // slw oldval2, oldval,shift
6082 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6083 // slw mask, mask2, shift
6084 // and newval3, newval2, mask
6085 // and oldval3, oldval2, mask
6087 // lwarx tmpDest, ptr
6088 // and tmp, tmpDest, mask
6089 // cmpw tmp, oldval3
6092 // andc tmp2, tmpDest, mask
6093 // or tmp4, tmp2, newval3
6098 // stwcx. tmpDest, ptr
6100 // srw dest, tmpDest, shift
6101 if (ptrA != ZeroReg) {
6102 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6103 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6104 .addReg(ptrA).addReg(ptrB);
6108 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6109 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6110 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6111 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6113 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6114 .addReg(Ptr1Reg).addImm(0).addImm(61);
6116 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6117 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6118 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6119 .addReg(newval).addReg(ShiftReg);
6120 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6121 .addReg(oldval).addReg(ShiftReg);
6123 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6125 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6126 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6127 .addReg(Mask3Reg).addImm(65535);
6129 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6130 .addReg(Mask2Reg).addReg(ShiftReg);
6131 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6132 .addReg(NewVal2Reg).addReg(MaskReg);
6133 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6134 .addReg(OldVal2Reg).addReg(MaskReg);
6137 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6138 .addReg(ZeroReg).addReg(PtrReg);
6139 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6140 .addReg(TmpDestReg).addReg(MaskReg);
6141 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6142 .addReg(TmpReg).addReg(OldVal3Reg);
6143 BuildMI(BB, dl, TII->get(PPC::BCC))
6144 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6145 BB->addSuccessor(loop2MBB);
6146 BB->addSuccessor(midMBB);
6149 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6150 .addReg(TmpDestReg).addReg(MaskReg);
6151 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6152 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6153 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6154 .addReg(ZeroReg).addReg(PtrReg);
6155 BuildMI(BB, dl, TII->get(PPC::BCC))
6156 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6157 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6158 BB->addSuccessor(loop1MBB);
6159 BB->addSuccessor(exitMBB);
6162 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6163 .addReg(ZeroReg).addReg(PtrReg);
6164 BB->addSuccessor(exitMBB);
6169 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6172 llvm_unreachable("Unexpected instr type to insert");
6175 MI->eraseFromParent(); // The pseudo instruction is gone now.
6179 //===----------------------------------------------------------------------===//
6180 // Target Optimization Hooks
6181 //===----------------------------------------------------------------------===//
6183 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6184 DAGCombinerInfo &DCI) const {
6185 const TargetMachine &TM = getTargetMachine();
6186 SelectionDAG &DAG = DCI.DAG;
6187 DebugLoc dl = N->getDebugLoc();
6188 switch (N->getOpcode()) {
6191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6192 if (C->isNullValue()) // 0 << V -> 0.
6193 return N->getOperand(0);
6197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6198 if (C->isNullValue()) // 0 >>u V -> 0.
6199 return N->getOperand(0);
6203 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6204 if (C->isNullValue() || // 0 >>s V -> 0.
6205 C->isAllOnesValue()) // -1 >>s V -> -1.
6206 return N->getOperand(0);
6210 case ISD::SINT_TO_FP:
6211 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6212 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6213 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6214 // We allow the src/dst to be either f32/f64, but the intermediate
6215 // type must be i64.
6216 if (N->getOperand(0).getValueType() == MVT::i64 &&
6217 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6218 SDValue Val = N->getOperand(0).getOperand(0);
6219 if (Val.getValueType() == MVT::f32) {
6220 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6221 DCI.AddToWorklist(Val.getNode());
6224 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6225 DCI.AddToWorklist(Val.getNode());
6226 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6227 DCI.AddToWorklist(Val.getNode());
6228 if (N->getValueType(0) == MVT::f32) {
6229 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6230 DAG.getIntPtrConstant(0));
6231 DCI.AddToWorklist(Val.getNode());
6234 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6235 // If the intermediate type is i32, we can avoid the load/store here
6242 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6243 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6244 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6245 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6246 N->getOperand(1).getValueType() == MVT::i32 &&
6247 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6248 SDValue Val = N->getOperand(1).getOperand(0);
6249 if (Val.getValueType() == MVT::f32) {
6250 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6251 DCI.AddToWorklist(Val.getNode());
6253 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6254 DCI.AddToWorklist(Val.getNode());
6256 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6257 N->getOperand(2), N->getOperand(3));
6258 DCI.AddToWorklist(Val.getNode());
6262 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6263 if (cast<StoreSDNode>(N)->isUnindexed() &&
6264 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6265 N->getOperand(1).getNode()->hasOneUse() &&
6266 (N->getOperand(1).getValueType() == MVT::i32 ||
6267 N->getOperand(1).getValueType() == MVT::i16)) {
6268 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6269 // Do an any-extend to 32-bits if this is a half-word input.
6270 if (BSwapOp.getValueType() == MVT::i16)
6271 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6274 N->getOperand(0), BSwapOp, N->getOperand(2),
6275 DAG.getValueType(N->getOperand(1).getValueType())
6278 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6279 Ops, array_lengthof(Ops),
6280 cast<StoreSDNode>(N)->getMemoryVT(),
6281 cast<StoreSDNode>(N)->getMemOperand());
6285 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6286 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6287 N->getOperand(0).hasOneUse() &&
6288 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6289 SDValue Load = N->getOperand(0);
6290 LoadSDNode *LD = cast<LoadSDNode>(Load);
6291 // Create the byte-swapping load.
6293 LD->getChain(), // Chain
6294 LD->getBasePtr(), // Ptr
6295 DAG.getValueType(N->getValueType(0)) // VT
6298 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6299 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6300 LD->getMemoryVT(), LD->getMemOperand());
6302 // If this is an i16 load, insert the truncate.
6303 SDValue ResVal = BSLoad;
6304 if (N->getValueType(0) == MVT::i16)
6305 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6307 // First, combine the bswap away. This makes the value produced by the
6309 DCI.CombineTo(N, ResVal);
6311 // Next, combine the load away, we give it a bogus result value but a real
6312 // chain result. The result value is dead because the bswap is dead.
6313 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6315 // Return N so it doesn't get rechecked!
6316 return SDValue(N, 0);
6320 case PPCISD::VCMP: {
6321 // If a VCMPo node already exists with exactly the same operands as this
6322 // node, use its result instead of this node (VCMPo computes both a CR6 and
6323 // a normal output).
6325 if (!N->getOperand(0).hasOneUse() &&
6326 !N->getOperand(1).hasOneUse() &&
6327 !N->getOperand(2).hasOneUse()) {
6329 // Scan all of the users of the LHS, looking for VCMPo's that match.
6330 SDNode *VCMPoNode = 0;
6332 SDNode *LHSN = N->getOperand(0).getNode();
6333 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6335 if (UI->getOpcode() == PPCISD::VCMPo &&
6336 UI->getOperand(1) == N->getOperand(1) &&
6337 UI->getOperand(2) == N->getOperand(2) &&
6338 UI->getOperand(0) == N->getOperand(0)) {
6343 // If there is no VCMPo node, or if the flag value has a single use, don't
6345 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6348 // Look at the (necessarily single) use of the flag value. If it has a
6349 // chain, this transformation is more complex. Note that multiple things
6350 // could use the value result, which we should ignore.
6351 SDNode *FlagUser = 0;
6352 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6353 FlagUser == 0; ++UI) {
6354 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6356 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6357 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6364 // If the user is a MFCR instruction, we know this is safe. Otherwise we
6365 // give up for right now.
6366 if (FlagUser->getOpcode() == PPCISD::MFCR)
6367 return SDValue(VCMPoNode, 0);
6372 // If this is a branch on an altivec predicate comparison, lower this so
6373 // that we don't have to do a MFCR: instead, branch directly on CR6. This
6374 // lowering is done pre-legalize, because the legalizer lowers the predicate
6375 // compare down to code that is difficult to reassemble.
6376 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6377 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6381 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6382 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6383 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6384 assert(isDot && "Can't compare against a vector result!");
6386 // If this is a comparison against something other than 0/1, then we know
6387 // that the condition is never/always true.
6388 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6389 if (Val != 0 && Val != 1) {
6390 if (CC == ISD::SETEQ) // Cond never true, remove branch.
6391 return N->getOperand(0);
6392 // Always !=, turn it into an unconditional branch.
6393 return DAG.getNode(ISD::BR, dl, MVT::Other,
6394 N->getOperand(0), N->getOperand(4));
6397 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6399 // Create the PPCISD altivec 'dot' comparison node.
6400 std::vector<EVT> VTs;
6402 LHS.getOperand(2), // LHS of compare
6403 LHS.getOperand(3), // RHS of compare
6404 DAG.getConstant(CompareOpc, MVT::i32)
6406 VTs.push_back(LHS.getOperand(2).getValueType());
6407 VTs.push_back(MVT::Glue);
6408 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6410 // Unpack the result based on how the target uses it.
6411 PPC::Predicate CompOpc;
6412 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6413 default: // Can't happen, don't crash on invalid number though.
6414 case 0: // Branch on the value of the EQ bit of CR6.
6415 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6417 case 1: // Branch on the inverted value of the EQ bit of CR6.
6418 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6420 case 2: // Branch on the value of the LT bit of CR6.
6421 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6423 case 3: // Branch on the inverted value of the LT bit of CR6.
6424 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6428 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6429 DAG.getConstant(CompOpc, MVT::i32),
6430 DAG.getRegister(PPC::CR6, MVT::i32),
6431 N->getOperand(4), CompNode.getValue(1));
6440 //===----------------------------------------------------------------------===//
6441 // Inline Assembly Support
6442 //===----------------------------------------------------------------------===//
6444 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6447 const SelectionDAG &DAG,
6448 unsigned Depth) const {
6449 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6450 switch (Op.getOpcode()) {
6452 case PPCISD::LBRX: {
6453 // lhbrx is known to have the top bits cleared out.
6454 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6455 KnownZero = 0xFFFF0000;
6458 case ISD::INTRINSIC_WO_CHAIN: {
6459 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6461 case Intrinsic::ppc_altivec_vcmpbfp_p:
6462 case Intrinsic::ppc_altivec_vcmpeqfp_p:
6463 case Intrinsic::ppc_altivec_vcmpequb_p:
6464 case Intrinsic::ppc_altivec_vcmpequh_p:
6465 case Intrinsic::ppc_altivec_vcmpequw_p:
6466 case Intrinsic::ppc_altivec_vcmpgefp_p:
6467 case Intrinsic::ppc_altivec_vcmpgtfp_p:
6468 case Intrinsic::ppc_altivec_vcmpgtsb_p:
6469 case Intrinsic::ppc_altivec_vcmpgtsh_p:
6470 case Intrinsic::ppc_altivec_vcmpgtsw_p:
6471 case Intrinsic::ppc_altivec_vcmpgtub_p:
6472 case Intrinsic::ppc_altivec_vcmpgtuh_p:
6473 case Intrinsic::ppc_altivec_vcmpgtuw_p:
6474 KnownZero = ~1U; // All bits but the low one are known to be zero.
6482 /// getConstraintType - Given a constraint, return the type of
6483 /// constraint it is for this target.
6484 PPCTargetLowering::ConstraintType
6485 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6486 if (Constraint.size() == 1) {
6487 switch (Constraint[0]) {
6494 return C_RegisterClass;
6496 // FIXME: While Z does indicate a memory constraint, it specifically
6497 // indicates an r+r address (used in conjunction with the 'y' modifier
6498 // in the replacement string). Currently, we're forcing the base
6499 // register to be r0 in the asm printer (which is interpreted as zero)
6500 // and forming the complete address in the second register. This is
6505 return TargetLowering::getConstraintType(Constraint);
6508 /// Examine constraint type and operand type and determine a weight value.
6509 /// This object must already have been set up with the operand type
6510 /// and the current alternative constraint selected.
6511 TargetLowering::ConstraintWeight
6512 PPCTargetLowering::getSingleConstraintMatchWeight(
6513 AsmOperandInfo &info, const char *constraint) const {
6514 ConstraintWeight weight = CW_Invalid;
6515 Value *CallOperandVal = info.CallOperandVal;
6516 // If we don't have a value, we can't do a match,
6517 // but allow it at the lowest weight.
6518 if (CallOperandVal == NULL)
6520 Type *type = CallOperandVal->getType();
6521 // Look at the constraint type.
6522 switch (*constraint) {
6524 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6527 if (type->isIntegerTy())
6528 weight = CW_Register;
6531 if (type->isFloatTy())
6532 weight = CW_Register;
6535 if (type->isDoubleTy())
6536 weight = CW_Register;
6539 if (type->isVectorTy())
6540 weight = CW_Register;
6543 weight = CW_Register;
6552 std::pair<unsigned, const TargetRegisterClass*>
6553 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6555 if (Constraint.size() == 1) {
6556 // GCC RS6000 Constraint Letters
6557 switch (Constraint[0]) {
6560 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6561 return std::make_pair(0U, &PPC::G8RCRegClass);
6562 return std::make_pair(0U, &PPC::GPRCRegClass);
6564 if (VT == MVT::f32 || VT == MVT::i32)
6565 return std::make_pair(0U, &PPC::F4RCRegClass);
6566 if (VT == MVT::f64 || VT == MVT::i64)
6567 return std::make_pair(0U, &PPC::F8RCRegClass);
6570 return std::make_pair(0U, &PPC::VRRCRegClass);
6572 return std::make_pair(0U, &PPC::CRRCRegClass);
6576 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6580 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6581 /// vector. If it is invalid, don't add anything to Ops.
6582 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6583 std::string &Constraint,
6584 std::vector<SDValue>&Ops,
6585 SelectionDAG &DAG) const {
6586 SDValue Result(0,0);
6588 // Only support length 1 constraints.
6589 if (Constraint.length() > 1) return;
6591 char Letter = Constraint[0];
6602 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6603 if (!CST) return; // Must be an immediate to match.
6604 unsigned Value = CST->getZExtValue();
6606 default: llvm_unreachable("Unknown constraint letter!");
6607 case 'I': // "I" is a signed 16-bit constant.
6608 if ((short)Value == (int)Value)
6609 Result = DAG.getTargetConstant(Value, Op.getValueType());
6611 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
6612 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
6613 if ((short)Value == 0)
6614 Result = DAG.getTargetConstant(Value, Op.getValueType());
6616 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
6617 if ((Value >> 16) == 0)
6618 Result = DAG.getTargetConstant(Value, Op.getValueType());
6620 case 'M': // "M" is a constant that is greater than 31.
6622 Result = DAG.getTargetConstant(Value, Op.getValueType());
6624 case 'N': // "N" is a positive constant that is an exact power of two.
6625 if ((int)Value > 0 && isPowerOf2_32(Value))
6626 Result = DAG.getTargetConstant(Value, Op.getValueType());
6628 case 'O': // "O" is the constant zero.
6630 Result = DAG.getTargetConstant(Value, Op.getValueType());
6632 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
6633 if ((short)-Value == (int)-Value)
6634 Result = DAG.getTargetConstant(Value, Op.getValueType());
6641 if (Result.getNode()) {
6642 Ops.push_back(Result);
6646 // Handle standard constraint letters.
6647 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6650 // isLegalAddressingMode - Return true if the addressing mode represented
6651 // by AM is legal for this target, for a load/store of the specified type.
6652 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6654 // FIXME: PPC does not allow r+i addressing modes for vectors!
6656 // PPC allows a sign-extended 16-bit immediate field.
6657 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
6660 // No global is ever allowed as a base.
6664 // PPC only support r+r,
6666 case 0: // "r+i" or just "i", depending on HasBaseReg.
6669 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
6671 // Otherwise we have r+r or r+i.
6674 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
6676 // Allow 2*r as r+r.
6679 // No other scales are supported.
6686 /// isLegalAddressImmediate - Return true if the integer value can be used
6687 /// as the offset of the target addressing mode for load / store of the
6689 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
6690 // PPC allows a sign-extended 16-bit immediate field.
6691 return (V > -(1 << 16) && V < (1 << 16)-1);
6694 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
6698 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
6699 SelectionDAG &DAG) const {
6700 MachineFunction &MF = DAG.getMachineFunction();
6701 MachineFrameInfo *MFI = MF.getFrameInfo();
6702 MFI->setReturnAddressIsTaken(true);
6704 DebugLoc dl = Op.getDebugLoc();
6705 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6707 // Make sure the function does not optimize away the store of the RA to
6709 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6710 FuncInfo->setLRStoreRequired();
6711 bool isPPC64 = PPCSubTarget.isPPC64();
6712 bool isDarwinABI = PPCSubTarget.isDarwinABI();
6715 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6718 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
6719 isPPC64? MVT::i64 : MVT::i32);
6720 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6721 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6723 MachinePointerInfo(), false, false, false, 0);
6726 // Just load the return address off the stack.
6727 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
6728 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6729 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
6732 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
6733 SelectionDAG &DAG) const {
6734 DebugLoc dl = Op.getDebugLoc();
6735 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6737 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6738 bool isPPC64 = PtrVT == MVT::i64;
6740 MachineFunction &MF = DAG.getMachineFunction();
6741 MachineFrameInfo *MFI = MF.getFrameInfo();
6742 MFI->setFrameAddressIsTaken(true);
6743 bool is31 = (getTargetMachine().Options.DisableFramePointerElim(MF) ||
6744 MFI->hasVarSizedObjects()) &&
6745 MFI->getStackSize() &&
6746 !MF.getFunction()->getFnAttributes().
6747 hasAttribute(Attributes::Naked);
6748 unsigned FrameReg = isPPC64 ? (is31 ? PPC::X31 : PPC::X1) :
6749 (is31 ? PPC::R31 : PPC::R1);
6750 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
6753 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
6754 FrameAddr, MachinePointerInfo(), false, false,
6760 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6761 // The PowerPC target isn't yet aware of offsets.
6765 /// getOptimalMemOpType - Returns the target specific optimal type for load
6766 /// and store operations as a result of memset, memcpy, and memmove
6767 /// lowering. If DstAlign is zero that means it's safe to destination
6768 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
6769 /// means there isn't a need to check it against alignment requirement,
6770 /// probably because the source does not need to be loaded. If
6771 /// 'IsZeroVal' is true, that means it's safe to return a
6772 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
6773 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
6774 /// constant so it does not need to be loaded.
6775 /// It returns EVT::Other if the type should be determined using generic
6776 /// target-independent logic.
6777 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
6778 unsigned DstAlign, unsigned SrcAlign,
6781 MachineFunction &MF) const {
6782 if (this->PPCSubTarget.isPPC64()) {
6789 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
6790 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
6791 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
6792 /// is expanded to mul + add.
6793 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
6797 switch (VT.getSimpleVT().SimpleTy) {
6809 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
6811 return TargetLowering::getSchedulingPreference(N);