1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.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_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
40 CCValAssign::LocInfo &LocInfo,
41 ISD::ArgFlagsTy &ArgFlags,
43 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
45 CCValAssign::LocInfo &LocInfo,
46 ISD::ArgFlagsTy &ArgFlags,
48 static bool CC_PPC32_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 cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
61 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
63 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
64 if (TM.getSubtargetImpl()->isDarwin())
65 return new TargetLoweringObjectFileMachO();
67 return new TargetLoweringObjectFileELF();
70 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
71 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
72 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
73 PPCRegInfo = TM.getRegisterInfo();
77 // Use _setjmp/_longjmp instead of setjmp/longjmp.
78 setUseUnderscoreSetJmp(true);
79 setUseUnderscoreLongJmp(true);
81 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
82 // arguments are at least 4/8 bytes aligned.
83 bool isPPC64 = Subtarget->isPPC64();
84 setMinStackArgumentAlignment(isPPC64 ? 8:4);
86 // Set up the register classes.
87 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
88 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
89 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
91 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
95 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
97 // PowerPC has pre-inc load and store's.
98 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
99 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
100 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
101 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
102 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
103 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
104 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
105 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
106 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
107 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109 // This is used in the ppcf128->int sequence. Note it has different semantics
110 // from FP_ROUND: that rounds to nearest, this rounds to zero.
111 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
113 // We do not currently implement these libm ops for PowerPC.
114 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
115 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
116 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
117 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
118 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
120 // PowerPC has no SREM/UREM instructions
121 setOperationAction(ISD::SREM, MVT::i32, Expand);
122 setOperationAction(ISD::UREM, MVT::i32, Expand);
123 setOperationAction(ISD::SREM, MVT::i64, Expand);
124 setOperationAction(ISD::UREM, MVT::i64, Expand);
126 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
127 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
128 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
129 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
130 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
131 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
132 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
133 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
134 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
136 // We don't support sin/cos/sqrt/fmod/pow
137 setOperationAction(ISD::FSIN , MVT::f64, Expand);
138 setOperationAction(ISD::FCOS , MVT::f64, Expand);
139 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
140 setOperationAction(ISD::FREM , MVT::f64, Expand);
141 setOperationAction(ISD::FPOW , MVT::f64, Expand);
142 setOperationAction(ISD::FMA , MVT::f64, Legal);
143 setOperationAction(ISD::FSIN , MVT::f32, Expand);
144 setOperationAction(ISD::FCOS , MVT::f32, Expand);
145 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
146 setOperationAction(ISD::FREM , MVT::f32, Expand);
147 setOperationAction(ISD::FPOW , MVT::f32, Expand);
148 setOperationAction(ISD::FMA , MVT::f32, Legal);
150 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
152 // If we're enabling GP optimizations, use hardware square root
153 if (!Subtarget->hasFSQRT()) {
154 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
155 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
158 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
159 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
161 // PowerPC does not have BSWAP, CTPOP or CTTZ
162 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
163 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
164 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
165 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
166 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
167 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
168 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
169 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
170 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
171 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
173 // PowerPC does not have ROTR
174 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
175 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
177 // PowerPC does not have Select
178 setOperationAction(ISD::SELECT, MVT::i32, Expand);
179 setOperationAction(ISD::SELECT, MVT::i64, Expand);
180 setOperationAction(ISD::SELECT, MVT::f32, Expand);
181 setOperationAction(ISD::SELECT, MVT::f64, Expand);
183 // PowerPC wants to turn select_cc of FP into fsel when possible.
184 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
187 // PowerPC wants to optimize integer setcc a bit
188 setOperationAction(ISD::SETCC, MVT::i32, Custom);
190 // PowerPC does not have BRCOND which requires SetCC
191 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
193 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
195 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
196 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
198 // PowerPC does not have [U|S]INT_TO_FP
199 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
200 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
202 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
203 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
204 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
205 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
207 // We cannot sextinreg(i1). Expand to shifts.
208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
210 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
211 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
212 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
213 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
215 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
216 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
217 // support continuation, user-level threading, and etc.. As a result, no
218 // other SjLj exception interfaces are implemented and please don't build
219 // your own exception handling based on them.
220 // LLVM/Clang supports zero-cost DWARF exception handling.
221 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
222 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
224 // We want to legalize GlobalAddress and ConstantPool nodes into the
225 // appropriate instructions to materialize the address.
226 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
227 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
228 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
229 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
230 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
231 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
233 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
234 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
235 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
238 setOperationAction(ISD::TRAP, MVT::Other, Legal);
240 // TRAMPOLINE is custom lowered.
241 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
242 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
244 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
245 setOperationAction(ISD::VASTART , MVT::Other, Custom);
247 if (Subtarget->isSVR4ABI()) {
249 // VAARG always uses double-word chunks, so promote anything smaller.
250 setOperationAction(ISD::VAARG, MVT::i1, Promote);
251 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
252 setOperationAction(ISD::VAARG, MVT::i8, Promote);
253 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
254 setOperationAction(ISD::VAARG, MVT::i16, Promote);
255 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
256 setOperationAction(ISD::VAARG, MVT::i32, Promote);
257 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
258 setOperationAction(ISD::VAARG, MVT::Other, Expand);
260 // VAARG is custom lowered with the 32-bit SVR4 ABI.
261 setOperationAction(ISD::VAARG, MVT::Other, Custom);
262 setOperationAction(ISD::VAARG, MVT::i64, Custom);
265 setOperationAction(ISD::VAARG, MVT::Other, Expand);
267 // Use the default implementation.
268 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
269 setOperationAction(ISD::VAEND , MVT::Other, Expand);
270 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
271 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
272 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
273 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
275 // We want to custom lower some of our intrinsics.
276 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
278 // Comparisons that require checking two conditions.
279 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
280 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
281 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
282 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
283 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
284 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
285 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
286 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
287 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
288 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
289 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
290 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
292 if (Subtarget->has64BitSupport()) {
293 // They also have instructions for converting between i64 and fp.
294 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
297 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
298 // This is just the low 32 bits of a (signed) fp->i64 conversion.
299 // We cannot do this with Promote because i64 is not a legal type.
300 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
302 // FIXME: disable this lowered code. This generates 64-bit register values,
303 // and we don't model the fact that the top part is clobbered by calls. We
304 // need to flag these together so that the value isn't live across a call.
305 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
307 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
308 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
311 if (Subtarget->use64BitRegs()) {
312 // 64-bit PowerPC implementations can support i64 types directly
313 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
314 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
315 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
316 // 64-bit PowerPC wants to expand i128 shifts itself.
317 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
318 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
319 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
321 // 32-bit PowerPC wants to expand i64 shifts itself.
322 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
323 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
324 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
327 if (Subtarget->hasAltivec()) {
328 // First set operation action for all vector types to expand. Then we
329 // will selectively turn on ones that can be effectively codegen'd.
330 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
331 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
332 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
334 // add/sub are legal for all supported vector VT's.
335 setOperationAction(ISD::ADD , VT, Legal);
336 setOperationAction(ISD::SUB , VT, Legal);
338 // We promote all shuffles to v16i8.
339 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
340 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
342 // We promote all non-typed operations to v4i32.
343 setOperationAction(ISD::AND , VT, Promote);
344 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
345 setOperationAction(ISD::OR , VT, Promote);
346 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
347 setOperationAction(ISD::XOR , VT, Promote);
348 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
349 setOperationAction(ISD::LOAD , VT, Promote);
350 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
351 setOperationAction(ISD::SELECT, VT, Promote);
352 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
353 setOperationAction(ISD::STORE, VT, Promote);
354 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
356 // No other operations are legal.
357 setOperationAction(ISD::MUL , VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UDIV, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
362 setOperationAction(ISD::FDIV, VT, Expand);
363 setOperationAction(ISD::FNEG, VT, Expand);
364 setOperationAction(ISD::FSQRT, VT, Expand);
365 setOperationAction(ISD::FLOG, VT, Expand);
366 setOperationAction(ISD::FLOG10, VT, Expand);
367 setOperationAction(ISD::FLOG2, VT, Expand);
368 setOperationAction(ISD::FEXP, VT, Expand);
369 setOperationAction(ISD::FEXP2, VT, Expand);
370 setOperationAction(ISD::FSIN, VT, Expand);
371 setOperationAction(ISD::FCOS, VT, Expand);
372 setOperationAction(ISD::FABS, VT, Expand);
373 setOperationAction(ISD::FPOWI, VT, Expand);
374 setOperationAction(ISD::FFLOOR, VT, Expand);
375 setOperationAction(ISD::FCEIL, VT, Expand);
376 setOperationAction(ISD::FTRUNC, VT, Expand);
377 setOperationAction(ISD::FRINT, VT, Expand);
378 setOperationAction(ISD::FNEARBYINT, VT, Expand);
379 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
380 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
381 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
382 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
383 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
384 setOperationAction(ISD::UDIVREM, VT, Expand);
385 setOperationAction(ISD::SDIVREM, VT, Expand);
386 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
387 setOperationAction(ISD::FPOW, VT, Expand);
388 setOperationAction(ISD::CTPOP, VT, Expand);
389 setOperationAction(ISD::CTLZ, VT, Expand);
390 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
391 setOperationAction(ISD::CTTZ, VT, Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
393 setOperationAction(ISD::VSELECT, VT, Expand);
394 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
396 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
397 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
398 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
399 setTruncStoreAction(VT, InnerVT, Expand);
401 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
402 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
403 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
406 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
407 // with merges, splats, etc.
408 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
410 setOperationAction(ISD::AND , MVT::v4i32, Legal);
411 setOperationAction(ISD::OR , MVT::v4i32, Legal);
412 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
413 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
414 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
415 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
416 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
417 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
418 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
419 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
420 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
421 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
422 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
423 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
425 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
426 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
427 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
428 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
430 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
431 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
432 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
433 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
434 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
436 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
437 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
439 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
440 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
441 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
442 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
444 // Altivec does not contain unordered floating-point compare instructions
445 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
446 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
447 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
448 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
449 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
450 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
453 if (Subtarget->has64BitSupport()) {
454 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
455 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
458 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
459 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
460 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
461 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
463 setBooleanContents(ZeroOrOneBooleanContent);
464 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
467 setStackPointerRegisterToSaveRestore(PPC::X1);
468 setExceptionPointerRegister(PPC::X3);
469 setExceptionSelectorRegister(PPC::X4);
471 setStackPointerRegisterToSaveRestore(PPC::R1);
472 setExceptionPointerRegister(PPC::R3);
473 setExceptionSelectorRegister(PPC::R4);
476 // We have target-specific dag combine patterns for the following nodes:
477 setTargetDAGCombine(ISD::SINT_TO_FP);
478 setTargetDAGCombine(ISD::STORE);
479 setTargetDAGCombine(ISD::BR_CC);
480 setTargetDAGCombine(ISD::BSWAP);
482 // Darwin long double math library functions have $LDBL128 appended.
483 if (Subtarget->isDarwin()) {
484 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
485 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
486 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
487 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
488 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
489 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
490 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
491 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
492 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
493 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
496 setMinFunctionAlignment(2);
497 if (PPCSubTarget.isDarwin())
498 setPrefFunctionAlignment(4);
500 if (isPPC64 && Subtarget->isJITCodeModel())
501 // Temporary workaround for the inability of PPC64 JIT to handle jump
503 setSupportJumpTables(false);
505 setInsertFencesForAtomic(true);
507 setSchedulingPreference(Sched::Hybrid);
509 computeRegisterProperties();
511 // The Freescale cores does better with aggressive inlining of memcpy and
512 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
513 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
514 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
515 MaxStoresPerMemset = 32;
516 MaxStoresPerMemsetOptSize = 16;
517 MaxStoresPerMemcpy = 32;
518 MaxStoresPerMemcpyOptSize = 8;
519 MaxStoresPerMemmove = 32;
520 MaxStoresPerMemmoveOptSize = 8;
522 setPrefFunctionAlignment(4);
523 BenefitFromCodePlacementOpt = true;
527 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
528 /// function arguments in the caller parameter area.
529 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
530 const TargetMachine &TM = getTargetMachine();
531 // Darwin passes everything on 4 byte boundary.
532 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
535 // 16byte and wider vectors are passed on 16byte boundary.
536 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
537 if (VTy->getBitWidth() >= 128)
540 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
541 if (PPCSubTarget.isPPC64())
547 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
550 case PPCISD::FSEL: return "PPCISD::FSEL";
551 case PPCISD::FCFID: return "PPCISD::FCFID";
552 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
553 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
554 case PPCISD::STFIWX: return "PPCISD::STFIWX";
555 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
556 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
557 case PPCISD::VPERM: return "PPCISD::VPERM";
558 case PPCISD::Hi: return "PPCISD::Hi";
559 case PPCISD::Lo: return "PPCISD::Lo";
560 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
561 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
562 case PPCISD::LOAD: return "PPCISD::LOAD";
563 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
564 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
565 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
566 case PPCISD::SRL: return "PPCISD::SRL";
567 case PPCISD::SRA: return "PPCISD::SRA";
568 case PPCISD::SHL: return "PPCISD::SHL";
569 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
570 case PPCISD::STD_32: return "PPCISD::STD_32";
571 case PPCISD::CALL: return "PPCISD::CALL";
572 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
573 case PPCISD::MTCTR: return "PPCISD::MTCTR";
574 case PPCISD::BCTRL: return "PPCISD::BCTRL";
575 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
576 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
577 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
578 case PPCISD::MFCR: return "PPCISD::MFCR";
579 case PPCISD::VCMP: return "PPCISD::VCMP";
580 case PPCISD::VCMPo: return "PPCISD::VCMPo";
581 case PPCISD::LBRX: return "PPCISD::LBRX";
582 case PPCISD::STBRX: return "PPCISD::STBRX";
583 case PPCISD::LARX: return "PPCISD::LARX";
584 case PPCISD::STCX: return "PPCISD::STCX";
585 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
586 case PPCISD::MFFS: return "PPCISD::MFFS";
587 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
588 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
589 case PPCISD::CR6SET: return "PPCISD::CR6SET";
590 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
591 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
592 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
593 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
594 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
595 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
596 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
597 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
598 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
599 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
600 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
601 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
602 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
603 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
604 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
605 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
609 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
612 return VT.changeVectorElementTypeToInteger();
615 //===----------------------------------------------------------------------===//
616 // Node matching predicates, for use by the tblgen matching code.
617 //===----------------------------------------------------------------------===//
619 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
620 static bool isFloatingPointZero(SDValue Op) {
621 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
622 return CFP->getValueAPF().isZero();
623 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
624 // Maybe this has already been legalized into the constant pool?
625 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
626 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
627 return CFP->getValueAPF().isZero();
632 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
633 /// true if Op is undef or if it matches the specified value.
634 static bool isConstantOrUndef(int Op, int Val) {
635 return Op < 0 || Op == Val;
638 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
639 /// VPKUHUM instruction.
640 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
642 for (unsigned i = 0; i != 16; ++i)
643 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
646 for (unsigned i = 0; i != 8; ++i)
647 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
648 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
654 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
655 /// VPKUWUM instruction.
656 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
658 for (unsigned i = 0; i != 16; i += 2)
659 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
660 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
663 for (unsigned i = 0; i != 8; i += 2)
664 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
665 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
666 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
667 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
673 /// isVMerge - Common function, used to match vmrg* shuffles.
675 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
676 unsigned LHSStart, unsigned RHSStart) {
677 assert(N->getValueType(0) == MVT::v16i8 &&
678 "PPC only supports shuffles by bytes!");
679 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
680 "Unsupported merge size!");
682 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
683 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
684 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
685 LHSStart+j+i*UnitSize) ||
686 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
687 RHSStart+j+i*UnitSize))
693 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
694 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
695 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
698 return isVMerge(N, UnitSize, 8, 24);
699 return isVMerge(N, UnitSize, 8, 8);
702 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
703 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
704 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
707 return isVMerge(N, UnitSize, 0, 16);
708 return isVMerge(N, UnitSize, 0, 0);
712 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
713 /// amount, otherwise return -1.
714 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
715 assert(N->getValueType(0) == MVT::v16i8 &&
716 "PPC only supports shuffles by bytes!");
718 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
720 // Find the first non-undef value in the shuffle mask.
722 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
725 if (i == 16) return -1; // all undef.
727 // Otherwise, check to see if the rest of the elements are consecutively
728 // numbered from this value.
729 unsigned ShiftAmt = SVOp->getMaskElt(i);
730 if (ShiftAmt < i) return -1;
734 // Check the rest of the elements to see if they are consecutive.
735 for (++i; i != 16; ++i)
736 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
739 // Check the rest of the elements to see if they are consecutive.
740 for (++i; i != 16; ++i)
741 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
747 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
748 /// specifies a splat of a single element that is suitable for input to
749 /// VSPLTB/VSPLTH/VSPLTW.
750 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
751 assert(N->getValueType(0) == MVT::v16i8 &&
752 (EltSize == 1 || EltSize == 2 || EltSize == 4));
754 // This is a splat operation if each element of the permute is the same, and
755 // if the value doesn't reference the second vector.
756 unsigned ElementBase = N->getMaskElt(0);
758 // FIXME: Handle UNDEF elements too!
759 if (ElementBase >= 16)
762 // Check that the indices are consecutive, in the case of a multi-byte element
763 // splatted with a v16i8 mask.
764 for (unsigned i = 1; i != EltSize; ++i)
765 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
768 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
769 if (N->getMaskElt(i) < 0) continue;
770 for (unsigned j = 0; j != EltSize; ++j)
771 if (N->getMaskElt(i+j) != N->getMaskElt(j))
777 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
779 bool PPC::isAllNegativeZeroVector(SDNode *N) {
780 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
782 APInt APVal, APUndef;
786 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
787 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
788 return CFP->getValueAPF().isNegZero();
793 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
794 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
795 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
796 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
797 assert(isSplatShuffleMask(SVOp, EltSize));
798 return SVOp->getMaskElt(0) / EltSize;
801 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
802 /// by using a vspltis[bhw] instruction of the specified element size, return
803 /// the constant being splatted. The ByteSize field indicates the number of
804 /// bytes of each element [124] -> [bhw].
805 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
808 // If ByteSize of the splat is bigger than the element size of the
809 // build_vector, then we have a case where we are checking for a splat where
810 // multiple elements of the buildvector are folded together into a single
811 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
812 unsigned EltSize = 16/N->getNumOperands();
813 if (EltSize < ByteSize) {
814 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
815 SDValue UniquedVals[4];
816 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
818 // See if all of the elements in the buildvector agree across.
819 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
820 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
821 // If the element isn't a constant, bail fully out.
822 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
825 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
826 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
827 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
828 return SDValue(); // no match.
831 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
832 // either constant or undef values that are identical for each chunk. See
833 // if these chunks can form into a larger vspltis*.
835 // Check to see if all of the leading entries are either 0 or -1. If
836 // neither, then this won't fit into the immediate field.
837 bool LeadingZero = true;
838 bool LeadingOnes = true;
839 for (unsigned i = 0; i != Multiple-1; ++i) {
840 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
842 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
843 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
845 // Finally, check the least significant entry.
847 if (UniquedVals[Multiple-1].getNode() == 0)
848 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
849 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
851 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
854 if (UniquedVals[Multiple-1].getNode() == 0)
855 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
856 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
857 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
858 return DAG.getTargetConstant(Val, MVT::i32);
864 // Check to see if this buildvec has a single non-undef value in its elements.
865 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
866 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
867 if (OpVal.getNode() == 0)
868 OpVal = N->getOperand(i);
869 else if (OpVal != N->getOperand(i))
873 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
875 unsigned ValSizeInBytes = EltSize;
877 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
878 Value = CN->getZExtValue();
879 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
880 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
881 Value = FloatToBits(CN->getValueAPF().convertToFloat());
884 // If the splat value is larger than the element value, then we can never do
885 // this splat. The only case that we could fit the replicated bits into our
886 // immediate field for would be zero, and we prefer to use vxor for it.
887 if (ValSizeInBytes < ByteSize) return SDValue();
889 // If the element value is larger than the splat value, cut it in half and
890 // check to see if the two halves are equal. Continue doing this until we
891 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
892 while (ValSizeInBytes > ByteSize) {
893 ValSizeInBytes >>= 1;
895 // If the top half equals the bottom half, we're still ok.
896 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
897 (Value & ((1 << (8*ValSizeInBytes))-1)))
901 // Properly sign extend the value.
902 int MaskVal = SignExtend32(Value, ByteSize * 8);
904 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
905 if (MaskVal == 0) return SDValue();
907 // Finally, if this value fits in a 5 bit sext field, return it
908 if (SignExtend32<5>(MaskVal) == MaskVal)
909 return DAG.getTargetConstant(MaskVal, MVT::i32);
913 //===----------------------------------------------------------------------===//
914 // Addressing Mode Selection
915 //===----------------------------------------------------------------------===//
917 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
918 /// or 64-bit immediate, and if the value can be accurately represented as a
919 /// sign extension from a 16-bit value. If so, this returns true and the
921 static bool isIntS16Immediate(SDNode *N, short &Imm) {
922 if (N->getOpcode() != ISD::Constant)
925 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
926 if (N->getValueType(0) == MVT::i32)
927 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
929 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
931 static bool isIntS16Immediate(SDValue Op, short &Imm) {
932 return isIntS16Immediate(Op.getNode(), Imm);
936 /// SelectAddressRegReg - Given the specified addressed, check to see if it
937 /// can be represented as an indexed [r+r] operation. Returns false if it
938 /// can be more efficiently represented with [r+imm].
939 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
941 SelectionDAG &DAG) const {
943 if (N.getOpcode() == ISD::ADD) {
944 if (isIntS16Immediate(N.getOperand(1), imm))
946 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
949 Base = N.getOperand(0);
950 Index = N.getOperand(1);
952 } else if (N.getOpcode() == ISD::OR) {
953 if (isIntS16Immediate(N.getOperand(1), imm))
954 return false; // r+i can fold it if we can.
956 // If this is an or of disjoint bitfields, we can codegen this as an add
957 // (for better address arithmetic) if the LHS and RHS of the OR are provably
959 APInt LHSKnownZero, LHSKnownOne;
960 APInt RHSKnownZero, RHSKnownOne;
961 DAG.ComputeMaskedBits(N.getOperand(0),
962 LHSKnownZero, LHSKnownOne);
964 if (LHSKnownZero.getBoolValue()) {
965 DAG.ComputeMaskedBits(N.getOperand(1),
966 RHSKnownZero, RHSKnownOne);
967 // If all of the bits are known zero on the LHS or RHS, the add won't
969 if (~(LHSKnownZero | RHSKnownZero) == 0) {
970 Base = N.getOperand(0);
971 Index = N.getOperand(1);
980 /// Returns true if the address N can be represented by a base register plus
981 /// a signed 16-bit displacement [r+imm], and if it is not better
982 /// represented as reg+reg.
983 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
985 SelectionDAG &DAG) const {
986 // FIXME dl should come from parent load or store, not from address
987 DebugLoc dl = N.getDebugLoc();
988 // If this can be more profitably realized as r+r, fail.
989 if (SelectAddressRegReg(N, Disp, Base, DAG))
992 if (N.getOpcode() == ISD::ADD) {
994 if (isIntS16Immediate(N.getOperand(1), imm)) {
995 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
996 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
997 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
999 Base = N.getOperand(0);
1001 return true; // [r+i]
1002 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1003 // Match LOAD (ADD (X, Lo(G))).
1004 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1005 && "Cannot handle constant offsets yet!");
1006 Disp = N.getOperand(1).getOperand(0); // The global address.
1007 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1008 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1009 Disp.getOpcode() == ISD::TargetConstantPool ||
1010 Disp.getOpcode() == ISD::TargetJumpTable);
1011 Base = N.getOperand(0);
1012 return true; // [&g+r]
1014 } else if (N.getOpcode() == ISD::OR) {
1016 if (isIntS16Immediate(N.getOperand(1), imm)) {
1017 // If this is an or of disjoint bitfields, we can codegen this as an add
1018 // (for better address arithmetic) if the LHS and RHS of the OR are
1019 // provably disjoint.
1020 APInt LHSKnownZero, LHSKnownOne;
1021 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1023 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1024 // If all of the bits are known zero on the LHS or RHS, the add won't
1026 Base = N.getOperand(0);
1027 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1031 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1032 // Loading from a constant address.
1034 // If this address fits entirely in a 16-bit sext immediate field, codegen
1037 if (isIntS16Immediate(CN, Imm)) {
1038 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1039 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1040 CN->getValueType(0));
1044 // Handle 32-bit sext immediates with LIS + addr mode.
1045 if (CN->getValueType(0) == MVT::i32 ||
1046 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1047 int Addr = (int)CN->getZExtValue();
1049 // Otherwise, break this down into an LIS + disp.
1050 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1052 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1053 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1054 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1059 Disp = DAG.getTargetConstant(0, getPointerTy());
1060 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1061 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1064 return true; // [r+0]
1067 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1068 /// represented as an indexed [r+r] operation.
1069 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1071 SelectionDAG &DAG) const {
1072 // Check to see if we can easily represent this as an [r+r] address. This
1073 // will fail if it thinks that the address is more profitably represented as
1074 // reg+imm, e.g. where imm = 0.
1075 if (SelectAddressRegReg(N, Base, Index, DAG))
1078 // If the operand is an addition, always emit this as [r+r], since this is
1079 // better (for code size, and execution, as the memop does the add for free)
1080 // than emitting an explicit add.
1081 if (N.getOpcode() == ISD::ADD) {
1082 Base = N.getOperand(0);
1083 Index = N.getOperand(1);
1087 // Otherwise, do it the hard way, using R0 as the base register.
1088 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1094 /// SelectAddressRegImmShift - Returns true if the address N can be
1095 /// represented by a base register plus a signed 14-bit displacement
1096 /// [r+imm*4]. Suitable for use by STD and friends.
1097 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1099 SelectionDAG &DAG) const {
1100 // FIXME dl should come from the parent load or store, not the address
1101 DebugLoc dl = N.getDebugLoc();
1102 // If this can be more profitably realized as r+r, fail.
1103 if (SelectAddressRegReg(N, Disp, Base, DAG))
1106 if (N.getOpcode() == ISD::ADD) {
1108 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1109 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1110 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1111 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1113 Base = N.getOperand(0);
1115 return true; // [r+i]
1116 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1117 // Match LOAD (ADD (X, Lo(G))).
1118 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1119 && "Cannot handle constant offsets yet!");
1120 Disp = N.getOperand(1).getOperand(0); // The global address.
1121 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1122 Disp.getOpcode() == ISD::TargetConstantPool ||
1123 Disp.getOpcode() == ISD::TargetJumpTable);
1124 Base = N.getOperand(0);
1125 return true; // [&g+r]
1127 } else if (N.getOpcode() == ISD::OR) {
1129 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1130 // If this is an or of disjoint bitfields, we can codegen this as an add
1131 // (for better address arithmetic) if the LHS and RHS of the OR are
1132 // provably disjoint.
1133 APInt LHSKnownZero, LHSKnownOne;
1134 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1135 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1136 // If all of the bits are known zero on the LHS or RHS, the add won't
1138 Base = N.getOperand(0);
1139 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1143 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1144 // Loading from a constant address. Verify low two bits are clear.
1145 if ((CN->getZExtValue() & 3) == 0) {
1146 // If this address fits entirely in a 14-bit sext immediate field, codegen
1149 if (isIntS16Immediate(CN, Imm)) {
1150 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1151 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1152 CN->getValueType(0));
1156 // Fold the low-part of 32-bit absolute addresses into addr mode.
1157 if (CN->getValueType(0) == MVT::i32 ||
1158 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1159 int Addr = (int)CN->getZExtValue();
1161 // Otherwise, break this down into an LIS + disp.
1162 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1163 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1164 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1165 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1171 Disp = DAG.getTargetConstant(0, getPointerTy());
1172 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1173 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1176 return true; // [r+0]
1180 /// getPreIndexedAddressParts - returns true by value, base pointer and
1181 /// offset pointer and addressing mode by reference if the node's address
1182 /// can be legally represented as pre-indexed load / store address.
1183 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1185 ISD::MemIndexedMode &AM,
1186 SelectionDAG &DAG) const {
1187 if (DisablePPCPreinc) return false;
1193 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1194 Ptr = LD->getBasePtr();
1195 VT = LD->getMemoryVT();
1196 Alignment = LD->getAlignment();
1197 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1198 Ptr = ST->getBasePtr();
1199 VT = ST->getMemoryVT();
1200 Alignment = ST->getAlignment();
1205 // PowerPC doesn't have preinc load/store instructions for vectors.
1209 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1211 // Common code will reject creating a pre-inc form if the base pointer
1212 // is a frame index, or if N is a store and the base pointer is either
1213 // the same as or a predecessor of the value being stored. Check for
1214 // those situations here, and try with swapped Base/Offset instead.
1217 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1220 SDValue Val = cast<StoreSDNode>(N)->getValue();
1221 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1226 std::swap(Base, Offset);
1232 // LDU/STU use reg+imm*4, others use reg+imm.
1233 if (VT != MVT::i64) {
1235 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1238 // LDU/STU need an address with at least 4-byte alignment.
1243 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1247 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1248 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1249 // sext i32 to i64 when addr mode is r+i.
1250 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1251 LD->getExtensionType() == ISD::SEXTLOAD &&
1252 isa<ConstantSDNode>(Offset))
1260 //===----------------------------------------------------------------------===//
1261 // LowerOperation implementation
1262 //===----------------------------------------------------------------------===//
1264 /// GetLabelAccessInfo - Return true if we should reference labels using a
1265 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1266 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1267 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1268 HiOpFlags = PPCII::MO_HA16;
1269 LoOpFlags = PPCII::MO_LO16;
1271 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1272 // non-darwin platform. We don't support PIC on other platforms yet.
1273 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1274 TM.getSubtarget<PPCSubtarget>().isDarwin();
1276 HiOpFlags |= PPCII::MO_PIC_FLAG;
1277 LoOpFlags |= PPCII::MO_PIC_FLAG;
1280 // If this is a reference to a global value that requires a non-lazy-ptr, make
1281 // sure that instruction lowering adds it.
1282 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1283 HiOpFlags |= PPCII::MO_NLP_FLAG;
1284 LoOpFlags |= PPCII::MO_NLP_FLAG;
1286 if (GV->hasHiddenVisibility()) {
1287 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1288 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1295 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1296 SelectionDAG &DAG) {
1297 EVT PtrVT = HiPart.getValueType();
1298 SDValue Zero = DAG.getConstant(0, PtrVT);
1299 DebugLoc DL = HiPart.getDebugLoc();
1301 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1302 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1304 // With PIC, the first instruction is actually "GR+hi(&G)".
1306 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1307 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1309 // Generate non-pic code that has direct accesses to the constant pool.
1310 // The address of the global is just (hi(&g)+lo(&g)).
1311 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1314 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1315 SelectionDAG &DAG) const {
1316 EVT PtrVT = Op.getValueType();
1317 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1318 const Constant *C = CP->getConstVal();
1320 // 64-bit SVR4 ABI code is always position-independent.
1321 // The actual address of the GlobalValue is stored in the TOC.
1322 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1323 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1324 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1325 DAG.getRegister(PPC::X2, MVT::i64));
1328 unsigned MOHiFlag, MOLoFlag;
1329 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1331 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1333 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1334 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1337 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1338 EVT PtrVT = Op.getValueType();
1339 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1341 // 64-bit SVR4 ABI code is always position-independent.
1342 // The actual address of the GlobalValue is stored in the TOC.
1343 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1344 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1345 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1346 DAG.getRegister(PPC::X2, MVT::i64));
1349 unsigned MOHiFlag, MOLoFlag;
1350 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1351 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1352 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1353 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1356 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1357 SelectionDAG &DAG) const {
1358 EVT PtrVT = Op.getValueType();
1360 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1362 unsigned MOHiFlag, MOLoFlag;
1363 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1364 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1365 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1366 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1369 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1370 SelectionDAG &DAG) const {
1372 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1373 DebugLoc dl = GA->getDebugLoc();
1374 const GlobalValue *GV = GA->getGlobal();
1375 EVT PtrVT = getPointerTy();
1376 bool is64bit = PPCSubTarget.isPPC64();
1378 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1380 if (Model == TLSModel::LocalExec) {
1381 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1382 PPCII::MO_TPREL16_HA);
1383 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1384 PPCII::MO_TPREL16_LO);
1385 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1386 is64bit ? MVT::i64 : MVT::i32);
1387 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1388 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1392 llvm_unreachable("only local-exec is currently supported for ppc32");
1394 if (Model == TLSModel::InitialExec) {
1395 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1396 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1397 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1398 PtrVT, GOTReg, TGA);
1399 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1400 PtrVT, TGA, TPOffsetHi);
1401 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1404 if (Model == TLSModel::GeneralDynamic) {
1405 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1406 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1407 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1409 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1412 // We need a chain node, and don't have one handy. The underlying
1413 // call has no side effects, so using the function entry node
1415 SDValue Chain = DAG.getEntryNode();
1416 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1417 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1418 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1419 PtrVT, ParmReg, TGA);
1420 // The return value from GET_TLS_ADDR really is in X3 already, but
1421 // some hacks are needed here to tie everything together. The extra
1422 // copies dissolve during subsequent transforms.
1423 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1424 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1427 if (Model == TLSModel::LocalDynamic) {
1428 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1429 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1430 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1432 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1435 // We need a chain node, and don't have one handy. The underlying
1436 // call has no side effects, so using the function entry node
1438 SDValue Chain = DAG.getEntryNode();
1439 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1440 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1441 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1442 PtrVT, ParmReg, TGA);
1443 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1444 // some hacks are needed here to tie everything together. The extra
1445 // copies dissolve during subsequent transforms.
1446 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1447 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1448 Chain, ParmReg, TGA);
1449 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1452 llvm_unreachable("Unknown TLS model!");
1455 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1456 SelectionDAG &DAG) const {
1457 EVT PtrVT = Op.getValueType();
1458 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1459 DebugLoc DL = GSDN->getDebugLoc();
1460 const GlobalValue *GV = GSDN->getGlobal();
1462 // 64-bit SVR4 ABI code is always position-independent.
1463 // The actual address of the GlobalValue is stored in the TOC.
1464 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1465 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1466 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1467 DAG.getRegister(PPC::X2, MVT::i64));
1470 unsigned MOHiFlag, MOLoFlag;
1471 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1474 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1476 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1478 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1480 // If the global reference is actually to a non-lazy-pointer, we have to do an
1481 // extra load to get the address of the global.
1482 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1483 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1484 false, false, false, 0);
1488 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1489 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1490 DebugLoc dl = Op.getDebugLoc();
1492 // If we're comparing for equality to zero, expose the fact that this is
1493 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1494 // fold the new nodes.
1495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1496 if (C->isNullValue() && CC == ISD::SETEQ) {
1497 EVT VT = Op.getOperand(0).getValueType();
1498 SDValue Zext = Op.getOperand(0);
1499 if (VT.bitsLT(MVT::i32)) {
1501 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1503 unsigned Log2b = Log2_32(VT.getSizeInBits());
1504 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1505 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1506 DAG.getConstant(Log2b, MVT::i32));
1507 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1509 // Leave comparisons against 0 and -1 alone for now, since they're usually
1510 // optimized. FIXME: revisit this when we can custom lower all setcc
1512 if (C->isAllOnesValue() || C->isNullValue())
1516 // If we have an integer seteq/setne, turn it into a compare against zero
1517 // by xor'ing the rhs with the lhs, which is faster than setting a
1518 // condition register, reading it back out, and masking the correct bit. The
1519 // normal approach here uses sub to do this instead of xor. Using xor exposes
1520 // the result to other bit-twiddling opportunities.
1521 EVT LHSVT = Op.getOperand(0).getValueType();
1522 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1523 EVT VT = Op.getValueType();
1524 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1526 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1531 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1532 const PPCSubtarget &Subtarget) const {
1533 SDNode *Node = Op.getNode();
1534 EVT VT = Node->getValueType(0);
1535 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1536 SDValue InChain = Node->getOperand(0);
1537 SDValue VAListPtr = Node->getOperand(1);
1538 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1539 DebugLoc dl = Node->getDebugLoc();
1541 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1544 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1545 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1547 InChain = GprIndex.getValue(1);
1549 if (VT == MVT::i64) {
1550 // Check if GprIndex is even
1551 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1552 DAG.getConstant(1, MVT::i32));
1553 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1554 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1555 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1556 DAG.getConstant(1, MVT::i32));
1557 // Align GprIndex to be even if it isn't
1558 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1562 // fpr index is 1 byte after gpr
1563 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1564 DAG.getConstant(1, MVT::i32));
1567 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1568 FprPtr, MachinePointerInfo(SV), MVT::i8,
1570 InChain = FprIndex.getValue(1);
1572 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1573 DAG.getConstant(8, MVT::i32));
1575 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1576 DAG.getConstant(4, MVT::i32));
1579 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1580 MachinePointerInfo(), false, false,
1582 InChain = OverflowArea.getValue(1);
1584 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1585 MachinePointerInfo(), false, false,
1587 InChain = RegSaveArea.getValue(1);
1589 // select overflow_area if index > 8
1590 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1591 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1593 // adjustment constant gpr_index * 4/8
1594 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1595 VT.isInteger() ? GprIndex : FprIndex,
1596 DAG.getConstant(VT.isInteger() ? 4 : 8,
1599 // OurReg = RegSaveArea + RegConstant
1600 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1603 // Floating types are 32 bytes into RegSaveArea
1604 if (VT.isFloatingPoint())
1605 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1606 DAG.getConstant(32, MVT::i32));
1608 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1609 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1610 VT.isInteger() ? GprIndex : FprIndex,
1611 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1614 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1615 VT.isInteger() ? VAListPtr : FprPtr,
1616 MachinePointerInfo(SV),
1617 MVT::i8, false, false, 0);
1619 // determine if we should load from reg_save_area or overflow_area
1620 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1622 // increase overflow_area by 4/8 if gpr/fpr > 8
1623 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1624 DAG.getConstant(VT.isInteger() ? 4 : 8,
1627 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1630 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1632 MachinePointerInfo(),
1633 MVT::i32, false, false, 0);
1635 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1636 false, false, false, 0);
1639 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1640 SelectionDAG &DAG) const {
1641 return Op.getOperand(0);
1644 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1645 SelectionDAG &DAG) const {
1646 SDValue Chain = Op.getOperand(0);
1647 SDValue Trmp = Op.getOperand(1); // trampoline
1648 SDValue FPtr = Op.getOperand(2); // nested function
1649 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1650 DebugLoc dl = Op.getDebugLoc();
1652 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1653 bool isPPC64 = (PtrVT == MVT::i64);
1655 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1658 TargetLowering::ArgListTy Args;
1659 TargetLowering::ArgListEntry Entry;
1661 Entry.Ty = IntPtrTy;
1662 Entry.Node = Trmp; Args.push_back(Entry);
1664 // TrampSize == (isPPC64 ? 48 : 40);
1665 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1666 isPPC64 ? MVT::i64 : MVT::i32);
1667 Args.push_back(Entry);
1669 Entry.Node = FPtr; Args.push_back(Entry);
1670 Entry.Node = Nest; Args.push_back(Entry);
1672 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1673 TargetLowering::CallLoweringInfo CLI(Chain,
1674 Type::getVoidTy(*DAG.getContext()),
1675 false, false, false, false, 0,
1677 /*isTailCall=*/false,
1678 /*doesNotRet=*/false,
1679 /*isReturnValueUsed=*/true,
1680 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1682 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1684 return CallResult.second;
1687 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1688 const PPCSubtarget &Subtarget) const {
1689 MachineFunction &MF = DAG.getMachineFunction();
1690 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1692 DebugLoc dl = Op.getDebugLoc();
1694 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1695 // vastart just stores the address of the VarArgsFrameIndex slot into the
1696 // memory location argument.
1697 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1698 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1699 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1700 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1701 MachinePointerInfo(SV),
1705 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1706 // We suppose the given va_list is already allocated.
1709 // char gpr; /* index into the array of 8 GPRs
1710 // * stored in the register save area
1711 // * gpr=0 corresponds to r3,
1712 // * gpr=1 to r4, etc.
1714 // char fpr; /* index into the array of 8 FPRs
1715 // * stored in the register save area
1716 // * fpr=0 corresponds to f1,
1717 // * fpr=1 to f2, etc.
1719 // char *overflow_arg_area;
1720 // /* location on stack that holds
1721 // * the next overflow argument
1723 // char *reg_save_area;
1724 // /* where r3:r10 and f1:f8 (if saved)
1730 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1731 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1734 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1736 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1738 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1741 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1742 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1744 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1745 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1747 uint64_t FPROffset = 1;
1748 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1750 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1752 // Store first byte : number of int regs
1753 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1755 MachinePointerInfo(SV),
1756 MVT::i8, false, false, 0);
1757 uint64_t nextOffset = FPROffset;
1758 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1761 // Store second byte : number of float regs
1762 SDValue secondStore =
1763 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1764 MachinePointerInfo(SV, nextOffset), MVT::i8,
1766 nextOffset += StackOffset;
1767 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1769 // Store second word : arguments given on stack
1770 SDValue thirdStore =
1771 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1772 MachinePointerInfo(SV, nextOffset),
1774 nextOffset += FrameOffset;
1775 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1777 // Store third word : arguments given in registers
1778 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1779 MachinePointerInfo(SV, nextOffset),
1784 #include "PPCGenCallingConv.inc"
1786 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1787 CCValAssign::LocInfo &LocInfo,
1788 ISD::ArgFlagsTy &ArgFlags,
1793 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1795 CCValAssign::LocInfo &LocInfo,
1796 ISD::ArgFlagsTy &ArgFlags,
1798 static const uint16_t ArgRegs[] = {
1799 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1800 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1802 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1804 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1806 // Skip one register if the first unallocated register has an even register
1807 // number and there are still argument registers available which have not been
1808 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1809 // need to skip a register if RegNum is odd.
1810 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1811 State.AllocateReg(ArgRegs[RegNum]);
1814 // Always return false here, as this function only makes sure that the first
1815 // unallocated register has an odd register number and does not actually
1816 // allocate a register for the current argument.
1820 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1822 CCValAssign::LocInfo &LocInfo,
1823 ISD::ArgFlagsTy &ArgFlags,
1825 static const uint16_t ArgRegs[] = {
1826 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1830 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1832 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1834 // If there is only one Floating-point register left we need to put both f64
1835 // values of a split ppc_fp128 value on the stack.
1836 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1837 State.AllocateReg(ArgRegs[RegNum]);
1840 // Always return false here, as this function only makes sure that the two f64
1841 // values a ppc_fp128 value is split into are both passed in registers or both
1842 // passed on the stack and does not actually allocate a register for the
1843 // current argument.
1847 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1849 static const uint16_t *GetFPR() {
1850 static const uint16_t FPR[] = {
1851 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1852 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1858 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1860 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1861 unsigned PtrByteSize) {
1862 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1863 if (Flags.isByVal())
1864 ArgSize = Flags.getByValSize();
1865 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1871 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1872 CallingConv::ID CallConv, bool isVarArg,
1873 const SmallVectorImpl<ISD::InputArg>
1875 DebugLoc dl, SelectionDAG &DAG,
1876 SmallVectorImpl<SDValue> &InVals)
1878 if (PPCSubTarget.isSVR4ABI()) {
1879 if (PPCSubTarget.isPPC64())
1880 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1883 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1886 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1892 PPCTargetLowering::LowerFormalArguments_32SVR4(
1894 CallingConv::ID CallConv, bool isVarArg,
1895 const SmallVectorImpl<ISD::InputArg>
1897 DebugLoc dl, SelectionDAG &DAG,
1898 SmallVectorImpl<SDValue> &InVals) const {
1900 // 32-bit SVR4 ABI Stack Frame Layout:
1901 // +-----------------------------------+
1902 // +--> | Back chain |
1903 // | +-----------------------------------+
1904 // | | Floating-point register save area |
1905 // | +-----------------------------------+
1906 // | | General register save area |
1907 // | +-----------------------------------+
1908 // | | CR save word |
1909 // | +-----------------------------------+
1910 // | | VRSAVE save word |
1911 // | +-----------------------------------+
1912 // | | Alignment padding |
1913 // | +-----------------------------------+
1914 // | | Vector register save area |
1915 // | +-----------------------------------+
1916 // | | Local variable space |
1917 // | +-----------------------------------+
1918 // | | Parameter list area |
1919 // | +-----------------------------------+
1920 // | | LR save word |
1921 // | +-----------------------------------+
1922 // SP--> +--- | Back chain |
1923 // +-----------------------------------+
1926 // System V Application Binary Interface PowerPC Processor Supplement
1927 // AltiVec Technology Programming Interface Manual
1929 MachineFunction &MF = DAG.getMachineFunction();
1930 MachineFrameInfo *MFI = MF.getFrameInfo();
1931 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1933 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1934 // Potential tail calls could cause overwriting of argument stack slots.
1935 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1936 (CallConv == CallingConv::Fast));
1937 unsigned PtrByteSize = 4;
1939 // Assign locations to all of the incoming arguments.
1940 SmallVector<CCValAssign, 16> ArgLocs;
1941 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1942 getTargetMachine(), ArgLocs, *DAG.getContext());
1944 // Reserve space for the linkage area on the stack.
1945 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1947 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
1949 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1950 CCValAssign &VA = ArgLocs[i];
1952 // Arguments stored in registers.
1953 if (VA.isRegLoc()) {
1954 const TargetRegisterClass *RC;
1955 EVT ValVT = VA.getValVT();
1957 switch (ValVT.getSimpleVT().SimpleTy) {
1959 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1961 RC = &PPC::GPRCRegClass;
1964 RC = &PPC::F4RCRegClass;
1967 RC = &PPC::F8RCRegClass;
1973 RC = &PPC::VRRCRegClass;
1977 // Transform the arguments stored in physical registers into virtual ones.
1978 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1979 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1981 InVals.push_back(ArgValue);
1983 // Argument stored in memory.
1984 assert(VA.isMemLoc());
1986 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1987 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1990 // Create load nodes to retrieve arguments from the stack.
1991 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1992 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1993 MachinePointerInfo(),
1994 false, false, false, 0));
1998 // Assign locations to all of the incoming aggregate by value arguments.
1999 // Aggregates passed by value are stored in the local variable space of the
2000 // caller's stack frame, right above the parameter list area.
2001 SmallVector<CCValAssign, 16> ByValArgLocs;
2002 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2003 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2005 // Reserve stack space for the allocations in CCInfo.
2006 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2008 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2010 // Area that is at least reserved in the caller of this function.
2011 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2013 // Set the size that is at least reserved in caller of this function. Tail
2014 // call optimized function's reserved stack space needs to be aligned so that
2015 // taking the difference between two stack areas will result in an aligned
2017 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2020 std::max(MinReservedArea,
2021 PPCFrameLowering::getMinCallFrameSize(false, false));
2023 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2024 getStackAlignment();
2025 unsigned AlignMask = TargetAlign-1;
2026 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2028 FI->setMinReservedArea(MinReservedArea);
2030 SmallVector<SDValue, 8> MemOps;
2032 // If the function takes variable number of arguments, make a frame index for
2033 // the start of the first vararg value... for expansion of llvm.va_start.
2035 static const uint16_t GPArgRegs[] = {
2036 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2037 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2039 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2041 static const uint16_t FPArgRegs[] = {
2042 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2045 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2047 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2049 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2052 // Make room for NumGPArgRegs and NumFPArgRegs.
2053 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2054 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2056 FuncInfo->setVarArgsStackOffset(
2057 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2058 CCInfo.getNextStackOffset(), true));
2060 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2061 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2063 // The fixed integer arguments of a variadic function are stored to the
2064 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2065 // the result of va_next.
2066 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2067 // Get an existing live-in vreg, or add a new one.
2068 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2070 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2072 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2073 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2074 MachinePointerInfo(), false, false, 0);
2075 MemOps.push_back(Store);
2076 // Increment the address by four for the next argument to store
2077 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2078 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2081 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2083 // The double arguments are stored to the VarArgsFrameIndex
2085 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2086 // Get an existing live-in vreg, or add a new one.
2087 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2089 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2091 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2092 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2093 MachinePointerInfo(), false, false, 0);
2094 MemOps.push_back(Store);
2095 // Increment the address by eight for the next argument to store
2096 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2098 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2102 if (!MemOps.empty())
2103 Chain = DAG.getNode(ISD::TokenFactor, dl,
2104 MVT::Other, &MemOps[0], MemOps.size());
2109 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2110 // value to MVT::i64 and then truncate to the correct register size.
2112 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2113 SelectionDAG &DAG, SDValue ArgVal,
2114 DebugLoc dl) const {
2116 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2117 DAG.getValueType(ObjectVT));
2118 else if (Flags.isZExt())
2119 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2120 DAG.getValueType(ObjectVT));
2122 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2125 // Set the size that is at least reserved in caller of this function. Tail
2126 // call optimized functions' reserved stack space needs to be aligned so that
2127 // taking the difference between two stack areas will result in an aligned
2130 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2131 unsigned nAltivecParamsAtEnd,
2132 unsigned MinReservedArea,
2133 bool isPPC64) const {
2134 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2135 // Add the Altivec parameters at the end, if needed.
2136 if (nAltivecParamsAtEnd) {
2137 MinReservedArea = ((MinReservedArea+15)/16)*16;
2138 MinReservedArea += 16*nAltivecParamsAtEnd;
2141 std::max(MinReservedArea,
2142 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2143 unsigned TargetAlign
2144 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2145 getStackAlignment();
2146 unsigned AlignMask = TargetAlign-1;
2147 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2148 FI->setMinReservedArea(MinReservedArea);
2152 PPCTargetLowering::LowerFormalArguments_64SVR4(
2154 CallingConv::ID CallConv, bool isVarArg,
2155 const SmallVectorImpl<ISD::InputArg>
2157 DebugLoc dl, SelectionDAG &DAG,
2158 SmallVectorImpl<SDValue> &InVals) const {
2159 // TODO: add description of PPC stack frame format, or at least some docs.
2161 MachineFunction &MF = DAG.getMachineFunction();
2162 MachineFrameInfo *MFI = MF.getFrameInfo();
2163 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2165 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2166 // Potential tail calls could cause overwriting of argument stack slots.
2167 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2168 (CallConv == CallingConv::Fast));
2169 unsigned PtrByteSize = 8;
2171 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2172 // Area that is at least reserved in caller of this function.
2173 unsigned MinReservedArea = ArgOffset;
2175 static const uint16_t GPR[] = {
2176 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2177 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2180 static const uint16_t *FPR = GetFPR();
2182 static const uint16_t VR[] = {
2183 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2184 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2187 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2188 const unsigned Num_FPR_Regs = 13;
2189 const unsigned Num_VR_Regs = array_lengthof(VR);
2191 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2193 // Add DAG nodes to load the arguments or copy them out of registers. On
2194 // entry to a function on PPC, the arguments start after the linkage area,
2195 // although the first ones are often in registers.
2197 SmallVector<SDValue, 8> MemOps;
2198 unsigned nAltivecParamsAtEnd = 0;
2199 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2200 unsigned CurArgIdx = 0;
2201 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2203 bool needsLoad = false;
2204 EVT ObjectVT = Ins[ArgNo].VT;
2205 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2206 unsigned ArgSize = ObjSize;
2207 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2208 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2209 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2211 unsigned CurArgOffset = ArgOffset;
2213 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2214 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2215 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2217 MinReservedArea = ((MinReservedArea+15)/16)*16;
2218 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2222 nAltivecParamsAtEnd++;
2224 // Calculate min reserved area.
2225 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2229 // FIXME the codegen can be much improved in some cases.
2230 // We do not have to keep everything in memory.
2231 if (Flags.isByVal()) {
2232 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2233 ObjSize = Flags.getByValSize();
2234 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2235 // Empty aggregate parameters do not take up registers. Examples:
2239 // etc. However, we have to provide a place-holder in InVals, so
2240 // pretend we have an 8-byte item at the current address for that
2243 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2244 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2245 InVals.push_back(FIN);
2248 // All aggregates smaller than 8 bytes must be passed right-justified.
2249 if (ObjSize < PtrByteSize)
2250 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2251 // The value of the object is its address.
2252 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2253 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2254 InVals.push_back(FIN);
2257 if (GPR_idx != Num_GPR_Regs) {
2258 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2259 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2262 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2263 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2264 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2265 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2266 MachinePointerInfo(FuncArg, CurArgOffset),
2267 ObjType, false, false, 0);
2269 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2270 // store the whole register as-is to the parameter save area
2271 // slot. The address of the parameter was already calculated
2272 // above (InVals.push_back(FIN)) to be the right-justified
2273 // offset within the slot. For this store, we need a new
2274 // frame index that points at the beginning of the slot.
2275 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2276 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2277 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2278 MachinePointerInfo(FuncArg, ArgOffset),
2282 MemOps.push_back(Store);
2285 // Whether we copied from a register or not, advance the offset
2286 // into the parameter save area by a full doubleword.
2287 ArgOffset += PtrByteSize;
2291 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2292 // Store whatever pieces of the object are in registers
2293 // to memory. ArgOffset will be the address of the beginning
2295 if (GPR_idx != Num_GPR_Regs) {
2297 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2298 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2299 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2300 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2301 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2302 MachinePointerInfo(FuncArg, ArgOffset),
2304 MemOps.push_back(Store);
2306 ArgOffset += PtrByteSize;
2308 ArgOffset += ArgSize - j;
2315 switch (ObjectVT.getSimpleVT().SimpleTy) {
2316 default: llvm_unreachable("Unhandled argument type!");
2319 if (GPR_idx != Num_GPR_Regs) {
2320 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2321 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2323 if (ObjectVT == MVT::i32)
2324 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2325 // value to MVT::i64 and then truncate to the correct register size.
2326 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2331 ArgSize = PtrByteSize;
2338 // Every 8 bytes of argument space consumes one of the GPRs available for
2339 // argument passing.
2340 if (GPR_idx != Num_GPR_Regs) {
2343 if (FPR_idx != Num_FPR_Regs) {
2346 if (ObjectVT == MVT::f32)
2347 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2349 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2351 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2355 ArgSize = PtrByteSize;
2364 // Note that vector arguments in registers don't reserve stack space,
2365 // except in varargs functions.
2366 if (VR_idx != Num_VR_Regs) {
2367 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2368 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2370 while ((ArgOffset % 16) != 0) {
2371 ArgOffset += PtrByteSize;
2372 if (GPR_idx != Num_GPR_Regs)
2376 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2380 // Vectors are aligned.
2381 ArgOffset = ((ArgOffset+15)/16)*16;
2382 CurArgOffset = ArgOffset;
2389 // We need to load the argument to a virtual register if we determined
2390 // above that we ran out of physical registers of the appropriate type.
2392 int FI = MFI->CreateFixedObject(ObjSize,
2393 CurArgOffset + (ArgSize - ObjSize),
2395 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2396 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2397 false, false, false, 0);
2400 InVals.push_back(ArgVal);
2403 // Set the size that is at least reserved in caller of this function. Tail
2404 // call optimized functions' reserved stack space needs to be aligned so that
2405 // taking the difference between two stack areas will result in an aligned
2407 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2409 // If the function takes variable number of arguments, make a frame index for
2410 // the start of the first vararg value... for expansion of llvm.va_start.
2412 int Depth = ArgOffset;
2414 FuncInfo->setVarArgsFrameIndex(
2415 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2416 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2418 // If this function is vararg, store any remaining integer argument regs
2419 // to their spots on the stack so that they may be loaded by deferencing the
2420 // result of va_next.
2421 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2422 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2424 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2425 MachinePointerInfo(), false, false, 0);
2426 MemOps.push_back(Store);
2427 // Increment the address by four for the next argument to store
2428 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2429 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2433 if (!MemOps.empty())
2434 Chain = DAG.getNode(ISD::TokenFactor, dl,
2435 MVT::Other, &MemOps[0], MemOps.size());
2441 PPCTargetLowering::LowerFormalArguments_Darwin(
2443 CallingConv::ID CallConv, bool isVarArg,
2444 const SmallVectorImpl<ISD::InputArg>
2446 DebugLoc dl, SelectionDAG &DAG,
2447 SmallVectorImpl<SDValue> &InVals) const {
2448 // TODO: add description of PPC stack frame format, or at least some docs.
2450 MachineFunction &MF = DAG.getMachineFunction();
2451 MachineFrameInfo *MFI = MF.getFrameInfo();
2452 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2454 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2455 bool isPPC64 = PtrVT == MVT::i64;
2456 // Potential tail calls could cause overwriting of argument stack slots.
2457 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2458 (CallConv == CallingConv::Fast));
2459 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2461 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2462 // Area that is at least reserved in caller of this function.
2463 unsigned MinReservedArea = ArgOffset;
2465 static const uint16_t GPR_32[] = { // 32-bit registers.
2466 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2467 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2469 static const uint16_t GPR_64[] = { // 64-bit registers.
2470 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2471 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2474 static const uint16_t *FPR = GetFPR();
2476 static const uint16_t VR[] = {
2477 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2478 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2481 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2482 const unsigned Num_FPR_Regs = 13;
2483 const unsigned Num_VR_Regs = array_lengthof( VR);
2485 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2487 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2489 // In 32-bit non-varargs functions, the stack space for vectors is after the
2490 // stack space for non-vectors. We do not use this space unless we have
2491 // too many vectors to fit in registers, something that only occurs in
2492 // constructed examples:), but we have to walk the arglist to figure
2493 // that out...for the pathological case, compute VecArgOffset as the
2494 // start of the vector parameter area. Computing VecArgOffset is the
2495 // entire point of the following loop.
2496 unsigned VecArgOffset = ArgOffset;
2497 if (!isVarArg && !isPPC64) {
2498 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2500 EVT ObjectVT = Ins[ArgNo].VT;
2501 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2503 if (Flags.isByVal()) {
2504 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2505 unsigned ObjSize = Flags.getByValSize();
2507 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2508 VecArgOffset += ArgSize;
2512 switch(ObjectVT.getSimpleVT().SimpleTy) {
2513 default: llvm_unreachable("Unhandled argument type!");
2518 case MVT::i64: // PPC64
2520 // FIXME: We are guaranteed to be !isPPC64 at this point.
2521 // Does MVT::i64 apply?
2528 // Nothing to do, we're only looking at Nonvector args here.
2533 // We've found where the vector parameter area in memory is. Skip the
2534 // first 12 parameters; these don't use that memory.
2535 VecArgOffset = ((VecArgOffset+15)/16)*16;
2536 VecArgOffset += 12*16;
2538 // Add DAG nodes to load the arguments or copy them out of registers. On
2539 // entry to a function on PPC, the arguments start after the linkage area,
2540 // although the first ones are often in registers.
2542 SmallVector<SDValue, 8> MemOps;
2543 unsigned nAltivecParamsAtEnd = 0;
2544 // FIXME: FuncArg and Ins[ArgNo] must reference the same argument.
2545 // When passing anonymous aggregates, this is currently not true.
2546 // See LowerFormalArguments_64SVR4 for a fix.
2547 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2548 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2550 bool needsLoad = false;
2551 EVT ObjectVT = Ins[ArgNo].VT;
2552 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2553 unsigned ArgSize = ObjSize;
2554 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2556 unsigned CurArgOffset = ArgOffset;
2558 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2559 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2560 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2561 if (isVarArg || isPPC64) {
2562 MinReservedArea = ((MinReservedArea+15)/16)*16;
2563 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2566 } else nAltivecParamsAtEnd++;
2568 // Calculate min reserved area.
2569 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2573 // FIXME the codegen can be much improved in some cases.
2574 // We do not have to keep everything in memory.
2575 if (Flags.isByVal()) {
2576 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2577 ObjSize = Flags.getByValSize();
2578 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2579 // Objects of size 1 and 2 are right justified, everything else is
2580 // left justified. This means the memory address is adjusted forwards.
2581 if (ObjSize==1 || ObjSize==2) {
2582 CurArgOffset = CurArgOffset + (4 - ObjSize);
2584 // The value of the object is its address.
2585 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2586 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2587 InVals.push_back(FIN);
2588 if (ObjSize==1 || ObjSize==2) {
2589 if (GPR_idx != Num_GPR_Regs) {
2592 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2594 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2595 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2596 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2597 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2598 MachinePointerInfo(FuncArg,
2600 ObjType, false, false, 0);
2601 MemOps.push_back(Store);
2605 ArgOffset += PtrByteSize;
2609 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2610 // Store whatever pieces of the object are in registers
2611 // to memory. ArgOffset will be the address of the beginning
2613 if (GPR_idx != Num_GPR_Regs) {
2616 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2618 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2619 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2620 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2621 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2622 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2623 MachinePointerInfo(FuncArg, ArgOffset),
2625 MemOps.push_back(Store);
2627 ArgOffset += PtrByteSize;
2629 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2636 switch (ObjectVT.getSimpleVT().SimpleTy) {
2637 default: llvm_unreachable("Unhandled argument type!");
2640 if (GPR_idx != Num_GPR_Regs) {
2641 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2642 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2646 ArgSize = PtrByteSize;
2648 // All int arguments reserve stack space in the Darwin ABI.
2649 ArgOffset += PtrByteSize;
2653 case MVT::i64: // PPC64
2654 if (GPR_idx != Num_GPR_Regs) {
2655 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2656 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2658 if (ObjectVT == MVT::i32)
2659 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2660 // value to MVT::i64 and then truncate to the correct register size.
2661 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2666 ArgSize = PtrByteSize;
2668 // All int arguments reserve stack space in the Darwin ABI.
2674 // Every 4 bytes of argument space consumes one of the GPRs available for
2675 // argument passing.
2676 if (GPR_idx != Num_GPR_Regs) {
2678 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2681 if (FPR_idx != Num_FPR_Regs) {
2684 if (ObjectVT == MVT::f32)
2685 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2687 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2689 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2695 // All FP arguments reserve stack space in the Darwin ABI.
2696 ArgOffset += isPPC64 ? 8 : ObjSize;
2702 // Note that vector arguments in registers don't reserve stack space,
2703 // except in varargs functions.
2704 if (VR_idx != Num_VR_Regs) {
2705 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2706 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2708 while ((ArgOffset % 16) != 0) {
2709 ArgOffset += PtrByteSize;
2710 if (GPR_idx != Num_GPR_Regs)
2714 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2718 if (!isVarArg && !isPPC64) {
2719 // Vectors go after all the nonvectors.
2720 CurArgOffset = VecArgOffset;
2723 // Vectors are aligned.
2724 ArgOffset = ((ArgOffset+15)/16)*16;
2725 CurArgOffset = ArgOffset;
2733 // We need to load the argument to a virtual register if we determined above
2734 // that we ran out of physical registers of the appropriate type.
2736 int FI = MFI->CreateFixedObject(ObjSize,
2737 CurArgOffset + (ArgSize - ObjSize),
2739 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2740 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2741 false, false, false, 0);
2744 InVals.push_back(ArgVal);
2747 // Set the size that is at least reserved in caller of this function. Tail
2748 // call optimized functions' reserved stack space needs to be aligned so that
2749 // taking the difference between two stack areas will result in an aligned
2751 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2753 // If the function takes variable number of arguments, make a frame index for
2754 // the start of the first vararg value... for expansion of llvm.va_start.
2756 int Depth = ArgOffset;
2758 FuncInfo->setVarArgsFrameIndex(
2759 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2761 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2763 // If this function is vararg, store any remaining integer argument regs
2764 // to their spots on the stack so that they may be loaded by deferencing the
2765 // result of va_next.
2766 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2770 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2772 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2774 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2775 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2776 MachinePointerInfo(), false, false, 0);
2777 MemOps.push_back(Store);
2778 // Increment the address by four for the next argument to store
2779 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2780 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2784 if (!MemOps.empty())
2785 Chain = DAG.getNode(ISD::TokenFactor, dl,
2786 MVT::Other, &MemOps[0], MemOps.size());
2791 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2792 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2794 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2798 const SmallVectorImpl<ISD::OutputArg>
2800 const SmallVectorImpl<SDValue> &OutVals,
2801 unsigned &nAltivecParamsAtEnd) {
2802 // Count how many bytes are to be pushed on the stack, including the linkage
2803 // area, and parameter passing area. We start with 24/48 bytes, which is
2804 // prereserved space for [SP][CR][LR][3 x unused].
2805 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2806 unsigned NumOps = Outs.size();
2807 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2809 // Add up all the space actually used.
2810 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2811 // they all go in registers, but we must reserve stack space for them for
2812 // possible use by the caller. In varargs or 64-bit calls, parameters are
2813 // assigned stack space in order, with padding so Altivec parameters are
2815 nAltivecParamsAtEnd = 0;
2816 for (unsigned i = 0; i != NumOps; ++i) {
2817 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2818 EVT ArgVT = Outs[i].VT;
2819 // Varargs Altivec parameters are padded to a 16 byte boundary.
2820 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2821 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2822 if (!isVarArg && !isPPC64) {
2823 // Non-varargs Altivec parameters go after all the non-Altivec
2824 // parameters; handle those later so we know how much padding we need.
2825 nAltivecParamsAtEnd++;
2828 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2829 NumBytes = ((NumBytes+15)/16)*16;
2831 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2834 // Allow for Altivec parameters at the end, if needed.
2835 if (nAltivecParamsAtEnd) {
2836 NumBytes = ((NumBytes+15)/16)*16;
2837 NumBytes += 16*nAltivecParamsAtEnd;
2840 // The prolog code of the callee may store up to 8 GPR argument registers to
2841 // the stack, allowing va_start to index over them in memory if its varargs.
2842 // Because we cannot tell if this is needed on the caller side, we have to
2843 // conservatively assume that it is needed. As such, make sure we have at
2844 // least enough stack space for the caller to store the 8 GPRs.
2845 NumBytes = std::max(NumBytes,
2846 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2848 // Tail call needs the stack to be aligned.
2849 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2850 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2851 getFrameLowering()->getStackAlignment();
2852 unsigned AlignMask = TargetAlign-1;
2853 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2859 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2860 /// adjusted to accommodate the arguments for the tailcall.
2861 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2862 unsigned ParamSize) {
2864 if (!isTailCall) return 0;
2866 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2867 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2868 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2869 // Remember only if the new adjustement is bigger.
2870 if (SPDiff < FI->getTailCallSPDelta())
2871 FI->setTailCallSPDelta(SPDiff);
2876 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2877 /// for tail call optimization. Targets which want to do tail call
2878 /// optimization should implement this function.
2880 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2881 CallingConv::ID CalleeCC,
2883 const SmallVectorImpl<ISD::InputArg> &Ins,
2884 SelectionDAG& DAG) const {
2885 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2888 // Variable argument functions are not supported.
2892 MachineFunction &MF = DAG.getMachineFunction();
2893 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2894 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2895 // Functions containing by val parameters are not supported.
2896 for (unsigned i = 0; i != Ins.size(); i++) {
2897 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2898 if (Flags.isByVal()) return false;
2901 // Non PIC/GOT tail calls are supported.
2902 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2905 // At the moment we can only do local tail calls (in same module, hidden
2906 // or protected) if we are generating PIC.
2907 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2908 return G->getGlobal()->hasHiddenVisibility()
2909 || G->getGlobal()->hasProtectedVisibility();
2915 /// isCallCompatibleAddress - Return the immediate to use if the specified
2916 /// 32-bit value is representable in the immediate field of a BxA instruction.
2917 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2918 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2921 int Addr = C->getZExtValue();
2922 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2923 SignExtend32<26>(Addr) != Addr)
2924 return 0; // Top 6 bits have to be sext of immediate.
2926 return DAG.getConstant((int)C->getZExtValue() >> 2,
2927 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2932 struct TailCallArgumentInfo {
2937 TailCallArgumentInfo() : FrameIdx(0) {}
2942 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2944 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2946 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2947 SmallVector<SDValue, 8> &MemOpChains,
2949 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2950 SDValue Arg = TailCallArgs[i].Arg;
2951 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2952 int FI = TailCallArgs[i].FrameIdx;
2953 // Store relative to framepointer.
2954 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2955 MachinePointerInfo::getFixedStack(FI),
2960 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2961 /// the appropriate stack slot for the tail call optimized function call.
2962 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2963 MachineFunction &MF,
2972 // Calculate the new stack slot for the return address.
2973 int SlotSize = isPPC64 ? 8 : 4;
2974 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2976 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2977 NewRetAddrLoc, true);
2978 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2979 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2980 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2981 MachinePointerInfo::getFixedStack(NewRetAddr),
2984 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2985 // slot as the FP is never overwritten.
2988 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2989 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2991 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2992 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2993 MachinePointerInfo::getFixedStack(NewFPIdx),
3000 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3001 /// the position of the argument.
3003 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3004 SDValue Arg, int SPDiff, unsigned ArgOffset,
3005 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
3006 int Offset = ArgOffset + SPDiff;
3007 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3008 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3009 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3010 SDValue FIN = DAG.getFrameIndex(FI, VT);
3011 TailCallArgumentInfo Info;
3013 Info.FrameIdxOp = FIN;
3015 TailCallArguments.push_back(Info);
3018 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3019 /// stack slot. Returns the chain as result and the loaded frame pointers in
3020 /// LROpOut/FPOpout. Used when tail calling.
3021 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3027 DebugLoc dl) const {
3029 // Load the LR and FP stack slot for later adjusting.
3030 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3031 LROpOut = getReturnAddrFrameIndex(DAG);
3032 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3033 false, false, false, 0);
3034 Chain = SDValue(LROpOut.getNode(), 1);
3036 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3037 // slot as the FP is never overwritten.
3039 FPOpOut = getFramePointerFrameIndex(DAG);
3040 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3041 false, false, false, 0);
3042 Chain = SDValue(FPOpOut.getNode(), 1);
3048 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3049 /// by "Src" to address "Dst" of size "Size". Alignment information is
3050 /// specified by the specific parameter attribute. The copy will be passed as
3051 /// a byval function parameter.
3052 /// Sometimes what we are copying is the end of a larger object, the part that
3053 /// does not fit in registers.
3055 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3056 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3058 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3059 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3060 false, false, MachinePointerInfo(0),
3061 MachinePointerInfo(0));
3064 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3067 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3068 SDValue Arg, SDValue PtrOff, int SPDiff,
3069 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3070 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3071 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3073 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3078 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3080 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3081 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3082 DAG.getConstant(ArgOffset, PtrVT));
3084 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3085 MachinePointerInfo(), false, false, 0));
3086 // Calculate and remember argument location.
3087 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3092 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3093 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3094 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3095 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3096 MachineFunction &MF = DAG.getMachineFunction();
3098 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3099 // might overwrite each other in case of tail call optimization.
3100 SmallVector<SDValue, 8> MemOpChains2;
3101 // Do not flag preceding copytoreg stuff together with the following stuff.
3103 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3105 if (!MemOpChains2.empty())
3106 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3107 &MemOpChains2[0], MemOpChains2.size());
3109 // Store the return address to the appropriate stack slot.
3110 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3111 isPPC64, isDarwinABI, dl);
3113 // Emit callseq_end just before tailcall node.
3114 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3115 DAG.getIntPtrConstant(0, true), InFlag);
3116 InFlag = Chain.getValue(1);
3120 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3121 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3122 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3123 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3124 const PPCSubtarget &PPCSubTarget) {
3126 bool isPPC64 = PPCSubTarget.isPPC64();
3127 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3129 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3130 NodeTys.push_back(MVT::Other); // Returns a chain
3131 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3133 unsigned CallOpc = PPCISD::CALL;
3135 bool needIndirectCall = true;
3136 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3137 // If this is an absolute destination address, use the munged value.
3138 Callee = SDValue(Dest, 0);
3139 needIndirectCall = false;
3142 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3143 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3144 // Use indirect calls for ALL functions calls in JIT mode, since the
3145 // far-call stubs may be outside relocation limits for a BL instruction.
3146 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3147 unsigned OpFlags = 0;
3148 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3149 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3150 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3151 (G->getGlobal()->isDeclaration() ||
3152 G->getGlobal()->isWeakForLinker())) {
3153 // PC-relative references to external symbols should go through $stub,
3154 // unless we're building with the leopard linker or later, which
3155 // automatically synthesizes these stubs.
3156 OpFlags = PPCII::MO_DARWIN_STUB;
3159 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3160 // every direct call is) turn it into a TargetGlobalAddress /
3161 // TargetExternalSymbol node so that legalize doesn't hack it.
3162 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3163 Callee.getValueType(),
3165 needIndirectCall = false;
3169 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3170 unsigned char OpFlags = 0;
3172 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3173 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3174 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3175 // PC-relative references to external symbols should go through $stub,
3176 // unless we're building with the leopard linker or later, which
3177 // automatically synthesizes these stubs.
3178 OpFlags = PPCII::MO_DARWIN_STUB;
3181 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3183 needIndirectCall = false;
3186 if (needIndirectCall) {
3187 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3188 // to do the call, we can't use PPCISD::CALL.
3189 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3191 if (isSVR4ABI && isPPC64) {
3192 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3193 // entry point, but to the function descriptor (the function entry point
3194 // address is part of the function descriptor though).
3195 // The function descriptor is a three doubleword structure with the
3196 // following fields: function entry point, TOC base address and
3197 // environment pointer.
3198 // Thus for a call through a function pointer, the following actions need
3200 // 1. Save the TOC of the caller in the TOC save area of its stack
3201 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3202 // 2. Load the address of the function entry point from the function
3204 // 3. Load the TOC of the callee from the function descriptor into r2.
3205 // 4. Load the environment pointer from the function descriptor into
3207 // 5. Branch to the function entry point address.
3208 // 6. On return of the callee, the TOC of the caller needs to be
3209 // restored (this is done in FinishCall()).
3211 // All those operations are flagged together to ensure that no other
3212 // operations can be scheduled in between. E.g. without flagging the
3213 // operations together, a TOC access in the caller could be scheduled
3214 // between the load of the callee TOC and the branch to the callee, which
3215 // results in the TOC access going through the TOC of the callee instead
3216 // of going through the TOC of the caller, which leads to incorrect code.
3218 // Load the address of the function entry point from the function
3220 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3221 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3222 InFlag.getNode() ? 3 : 2);
3223 Chain = LoadFuncPtr.getValue(1);
3224 InFlag = LoadFuncPtr.getValue(2);
3226 // Load environment pointer into r11.
3227 // Offset of the environment pointer within the function descriptor.
3228 SDValue PtrOff = DAG.getIntPtrConstant(16);
3230 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3231 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3233 Chain = LoadEnvPtr.getValue(1);
3234 InFlag = LoadEnvPtr.getValue(2);
3236 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3238 Chain = EnvVal.getValue(0);
3239 InFlag = EnvVal.getValue(1);
3241 // Load TOC of the callee into r2. We are using a target-specific load
3242 // with r2 hard coded, because the result of a target-independent load
3243 // would never go directly into r2, since r2 is a reserved register (which
3244 // prevents the register allocator from allocating it), resulting in an
3245 // additional register being allocated and an unnecessary move instruction
3247 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3248 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3250 Chain = LoadTOCPtr.getValue(0);
3251 InFlag = LoadTOCPtr.getValue(1);
3253 MTCTROps[0] = Chain;
3254 MTCTROps[1] = LoadFuncPtr;
3255 MTCTROps[2] = InFlag;
3258 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3259 2 + (InFlag.getNode() != 0));
3260 InFlag = Chain.getValue(1);
3263 NodeTys.push_back(MVT::Other);
3264 NodeTys.push_back(MVT::Glue);
3265 Ops.push_back(Chain);
3266 CallOpc = PPCISD::BCTRL;
3268 // Add use of X11 (holding environment pointer)
3269 if (isSVR4ABI && isPPC64)
3270 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3271 // Add CTR register as callee so a bctr can be emitted later.
3273 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3276 // If this is a direct call, pass the chain and the callee.
3277 if (Callee.getNode()) {
3278 Ops.push_back(Chain);
3279 Ops.push_back(Callee);
3281 // If this is a tail call add stack pointer delta.
3283 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3285 // Add argument registers to the end of the list so that they are known live
3287 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3288 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3289 RegsToPass[i].second.getValueType()));
3295 bool isLocalCall(const SDValue &Callee)
3297 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3298 return !G->getGlobal()->isDeclaration() &&
3299 !G->getGlobal()->isWeakForLinker();
3304 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3305 CallingConv::ID CallConv, bool isVarArg,
3306 const SmallVectorImpl<ISD::InputArg> &Ins,
3307 DebugLoc dl, SelectionDAG &DAG,
3308 SmallVectorImpl<SDValue> &InVals) const {
3310 SmallVector<CCValAssign, 16> RVLocs;
3311 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3312 getTargetMachine(), RVLocs, *DAG.getContext());
3313 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3315 // Copy all of the result registers out of their specified physreg.
3316 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3317 CCValAssign &VA = RVLocs[i];
3318 assert(VA.isRegLoc() && "Can only return in registers!");
3320 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3321 VA.getLocReg(), VA.getLocVT(), InFlag);
3322 Chain = Val.getValue(1);
3323 InFlag = Val.getValue(2);
3325 switch (VA.getLocInfo()) {
3326 default: llvm_unreachable("Unknown loc info!");
3327 case CCValAssign::Full: break;
3328 case CCValAssign::AExt:
3329 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3331 case CCValAssign::ZExt:
3332 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3333 DAG.getValueType(VA.getValVT()));
3334 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3336 case CCValAssign::SExt:
3337 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3338 DAG.getValueType(VA.getValVT()));
3339 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3343 InVals.push_back(Val);
3350 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3351 bool isTailCall, bool isVarArg,
3353 SmallVector<std::pair<unsigned, SDValue>, 8>
3355 SDValue InFlag, SDValue Chain,
3357 int SPDiff, unsigned NumBytes,
3358 const SmallVectorImpl<ISD::InputArg> &Ins,
3359 SmallVectorImpl<SDValue> &InVals) const {
3360 std::vector<EVT> NodeTys;
3361 SmallVector<SDValue, 8> Ops;
3362 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3363 isTailCall, RegsToPass, Ops, NodeTys,
3366 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3367 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3368 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3370 // When performing tail call optimization the callee pops its arguments off
3371 // the stack. Account for this here so these bytes can be pushed back on in
3372 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3373 int BytesCalleePops =
3374 (CallConv == CallingConv::Fast &&
3375 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3377 // Add a register mask operand representing the call-preserved registers.
3378 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3379 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3380 assert(Mask && "Missing call preserved mask for calling convention");
3381 Ops.push_back(DAG.getRegisterMask(Mask));
3383 if (InFlag.getNode())
3384 Ops.push_back(InFlag);
3388 assert(((Callee.getOpcode() == ISD::Register &&
3389 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3390 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3391 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3392 isa<ConstantSDNode>(Callee)) &&
3393 "Expecting an global address, external symbol, absolute value or register");
3395 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3398 // Add a NOP immediately after the branch instruction when using the 64-bit
3399 // SVR4 ABI. At link time, if caller and callee are in a different module and
3400 // thus have a different TOC, the call will be replaced with a call to a stub
3401 // function which saves the current TOC, loads the TOC of the callee and
3402 // branches to the callee. The NOP will be replaced with a load instruction
3403 // which restores the TOC of the caller from the TOC save slot of the current
3404 // stack frame. If caller and callee belong to the same module (and have the
3405 // same TOC), the NOP will remain unchanged.
3407 bool needsTOCRestore = false;
3408 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3409 if (CallOpc == PPCISD::BCTRL) {
3410 // This is a call through a function pointer.
3411 // Restore the caller TOC from the save area into R2.
3412 // See PrepareCall() for more information about calls through function
3413 // pointers in the 64-bit SVR4 ABI.
3414 // We are using a target-specific load with r2 hard coded, because the
3415 // result of a target-independent load would never go directly into r2,
3416 // since r2 is a reserved register (which prevents the register allocator
3417 // from allocating it), resulting in an additional register being
3418 // allocated and an unnecessary move instruction being generated.
3419 needsTOCRestore = true;
3420 } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) {
3421 // Otherwise insert NOP for non-local calls.
3422 CallOpc = PPCISD::CALL_NOP;
3426 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3427 InFlag = Chain.getValue(1);
3429 if (needsTOCRestore) {
3430 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3431 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3432 InFlag = Chain.getValue(1);
3435 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3436 DAG.getIntPtrConstant(BytesCalleePops, true),
3439 InFlag = Chain.getValue(1);
3441 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3442 Ins, dl, DAG, InVals);
3446 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3447 SmallVectorImpl<SDValue> &InVals) const {
3448 SelectionDAG &DAG = CLI.DAG;
3449 DebugLoc &dl = CLI.DL;
3450 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3451 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3452 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3453 SDValue Chain = CLI.Chain;
3454 SDValue Callee = CLI.Callee;
3455 bool &isTailCall = CLI.IsTailCall;
3456 CallingConv::ID CallConv = CLI.CallConv;
3457 bool isVarArg = CLI.IsVarArg;
3460 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3463 if (PPCSubTarget.isSVR4ABI()) {
3464 if (PPCSubTarget.isPPC64())
3465 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3466 isTailCall, Outs, OutVals, Ins,
3469 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3470 isTailCall, Outs, OutVals, Ins,
3474 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3475 isTailCall, Outs, OutVals, Ins,
3480 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3481 CallingConv::ID CallConv, bool isVarArg,
3483 const SmallVectorImpl<ISD::OutputArg> &Outs,
3484 const SmallVectorImpl<SDValue> &OutVals,
3485 const SmallVectorImpl<ISD::InputArg> &Ins,
3486 DebugLoc dl, SelectionDAG &DAG,
3487 SmallVectorImpl<SDValue> &InVals) const {
3488 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3489 // of the 32-bit SVR4 ABI stack frame layout.
3491 assert((CallConv == CallingConv::C ||
3492 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3494 unsigned PtrByteSize = 4;
3496 MachineFunction &MF = DAG.getMachineFunction();
3498 // Mark this function as potentially containing a function that contains a
3499 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3500 // and restoring the callers stack pointer in this functions epilog. This is
3501 // done because by tail calling the called function might overwrite the value
3502 // in this function's (MF) stack pointer stack slot 0(SP).
3503 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3504 CallConv == CallingConv::Fast)
3505 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3507 // Count how many bytes are to be pushed on the stack, including the linkage
3508 // area, parameter list area and the part of the local variable space which
3509 // contains copies of aggregates which are passed by value.
3511 // Assign locations to all of the outgoing arguments.
3512 SmallVector<CCValAssign, 16> ArgLocs;
3513 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3514 getTargetMachine(), ArgLocs, *DAG.getContext());
3516 // Reserve space for the linkage area on the stack.
3517 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3520 // Handle fixed and variable vector arguments differently.
3521 // Fixed vector arguments go into registers as long as registers are
3522 // available. Variable vector arguments always go into memory.
3523 unsigned NumArgs = Outs.size();
3525 for (unsigned i = 0; i != NumArgs; ++i) {
3526 MVT ArgVT = Outs[i].VT;
3527 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3530 if (Outs[i].IsFixed) {
3531 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3534 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3540 errs() << "Call operand #" << i << " has unhandled type "
3541 << EVT(ArgVT).getEVTString() << "\n";
3543 llvm_unreachable(0);
3547 // All arguments are treated the same.
3548 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3551 // Assign locations to all of the outgoing aggregate by value arguments.
3552 SmallVector<CCValAssign, 16> ByValArgLocs;
3553 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3554 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3556 // Reserve stack space for the allocations in CCInfo.
3557 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3559 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3561 // Size of the linkage area, parameter list area and the part of the local
3562 // space variable where copies of aggregates which are passed by value are
3564 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3566 // Calculate by how many bytes the stack has to be adjusted in case of tail
3567 // call optimization.
3568 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3570 // Adjust the stack pointer for the new arguments...
3571 // These operations are automatically eliminated by the prolog/epilog pass
3572 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3573 SDValue CallSeqStart = Chain;
3575 // Load the return address and frame pointer so it can be moved somewhere else
3578 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3581 // Set up a copy of the stack pointer for use loading and storing any
3582 // arguments that may not fit in the registers available for argument
3584 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3586 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3587 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3588 SmallVector<SDValue, 8> MemOpChains;
3590 bool seenFloatArg = false;
3591 // Walk the register/memloc assignments, inserting copies/loads.
3592 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3595 CCValAssign &VA = ArgLocs[i];
3596 SDValue Arg = OutVals[i];
3597 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3599 if (Flags.isByVal()) {
3600 // Argument is an aggregate which is passed by value, thus we need to
3601 // create a copy of it in the local variable space of the current stack
3602 // frame (which is the stack frame of the caller) and pass the address of
3603 // this copy to the callee.
3604 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3605 CCValAssign &ByValVA = ByValArgLocs[j++];
3606 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3608 // Memory reserved in the local variable space of the callers stack frame.
3609 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3611 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3612 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3614 // Create a copy of the argument in the local area of the current
3616 SDValue MemcpyCall =
3617 CreateCopyOfByValArgument(Arg, PtrOff,
3618 CallSeqStart.getNode()->getOperand(0),
3621 // This must go outside the CALLSEQ_START..END.
3622 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3623 CallSeqStart.getNode()->getOperand(1));
3624 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3625 NewCallSeqStart.getNode());
3626 Chain = CallSeqStart = NewCallSeqStart;
3628 // Pass the address of the aggregate copy on the stack either in a
3629 // physical register or in the parameter list area of the current stack
3630 // frame to the callee.
3634 if (VA.isRegLoc()) {
3635 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3636 // Put argument in a physical register.
3637 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3639 // Put argument in the parameter list area of the current stack frame.
3640 assert(VA.isMemLoc());
3641 unsigned LocMemOffset = VA.getLocMemOffset();
3644 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3645 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3647 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3648 MachinePointerInfo(),
3651 // Calculate and remember argument location.
3652 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3658 if (!MemOpChains.empty())
3659 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3660 &MemOpChains[0], MemOpChains.size());
3662 // Build a sequence of copy-to-reg nodes chained together with token chain
3663 // and flag operands which copy the outgoing args into the appropriate regs.
3665 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3666 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3667 RegsToPass[i].second, InFlag);
3668 InFlag = Chain.getValue(1);
3671 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3674 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3675 SDValue Ops[] = { Chain, InFlag };
3677 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3678 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3680 InFlag = Chain.getValue(1);
3684 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3685 false, TailCallArguments);
3687 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3688 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3692 // Copy an argument into memory, being careful to do this outside the
3693 // call sequence for the call to which the argument belongs.
3695 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3696 SDValue CallSeqStart,
3697 ISD::ArgFlagsTy Flags,
3699 DebugLoc dl) const {
3700 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3701 CallSeqStart.getNode()->getOperand(0),
3703 // The MEMCPY must go outside the CALLSEQ_START..END.
3704 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3705 CallSeqStart.getNode()->getOperand(1));
3706 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3707 NewCallSeqStart.getNode());
3708 return NewCallSeqStart;
3712 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3713 CallingConv::ID CallConv, bool isVarArg,
3715 const SmallVectorImpl<ISD::OutputArg> &Outs,
3716 const SmallVectorImpl<SDValue> &OutVals,
3717 const SmallVectorImpl<ISD::InputArg> &Ins,
3718 DebugLoc dl, SelectionDAG &DAG,
3719 SmallVectorImpl<SDValue> &InVals) const {
3721 unsigned NumOps = Outs.size();
3723 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3724 unsigned PtrByteSize = 8;
3726 MachineFunction &MF = DAG.getMachineFunction();
3728 // Mark this function as potentially containing a function that contains a
3729 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3730 // and restoring the callers stack pointer in this functions epilog. This is
3731 // done because by tail calling the called function might overwrite the value
3732 // in this function's (MF) stack pointer stack slot 0(SP).
3733 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3734 CallConv == CallingConv::Fast)
3735 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3737 unsigned nAltivecParamsAtEnd = 0;
3739 // Count how many bytes are to be pushed on the stack, including the linkage
3740 // area, and parameter passing area. We start with at least 48 bytes, which
3741 // is reserved space for [SP][CR][LR][3 x unused].
3742 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3745 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3746 Outs, OutVals, nAltivecParamsAtEnd);
3748 // Calculate by how many bytes the stack has to be adjusted in case of tail
3749 // call optimization.
3750 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3752 // To protect arguments on the stack from being clobbered in a tail call,
3753 // force all the loads to happen before doing any other lowering.
3755 Chain = DAG.getStackArgumentTokenFactor(Chain);
3757 // Adjust the stack pointer for the new arguments...
3758 // These operations are automatically eliminated by the prolog/epilog pass
3759 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3760 SDValue CallSeqStart = Chain;
3762 // Load the return address and frame pointer so it can be move somewhere else
3765 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3768 // Set up a copy of the stack pointer for use loading and storing any
3769 // arguments that may not fit in the registers available for argument
3771 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3773 // Figure out which arguments are going to go in registers, and which in
3774 // memory. Also, if this is a vararg function, floating point operations
3775 // must be stored to our stack, and loaded into integer regs as well, if
3776 // any integer regs are available for argument passing.
3777 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3778 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3780 static const uint16_t GPR[] = {
3781 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3782 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3784 static const uint16_t *FPR = GetFPR();
3786 static const uint16_t VR[] = {
3787 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3788 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3790 const unsigned NumGPRs = array_lengthof(GPR);
3791 const unsigned NumFPRs = 13;
3792 const unsigned NumVRs = array_lengthof(VR);
3794 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3795 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3797 SmallVector<SDValue, 8> MemOpChains;
3798 for (unsigned i = 0; i != NumOps; ++i) {
3799 SDValue Arg = OutVals[i];
3800 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3802 // PtrOff will be used to store the current argument to the stack if a
3803 // register cannot be found for it.
3806 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3808 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3810 // Promote integers to 64-bit values.
3811 if (Arg.getValueType() == MVT::i32) {
3812 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3813 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3814 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3817 // FIXME memcpy is used way more than necessary. Correctness first.
3818 // Note: "by value" is code for passing a structure by value, not
3820 if (Flags.isByVal()) {
3821 // Note: Size includes alignment padding, so
3822 // struct x { short a; char b; }
3823 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3824 // These are the proper values we need for right-justifying the
3825 // aggregate in a parameter register.
3826 unsigned Size = Flags.getByValSize();
3828 // An empty aggregate parameter takes up no storage and no
3833 // All aggregates smaller than 8 bytes must be passed right-justified.
3834 if (Size==1 || Size==2 || Size==4) {
3835 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3836 if (GPR_idx != NumGPRs) {
3837 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3838 MachinePointerInfo(), VT,
3840 MemOpChains.push_back(Load.getValue(1));
3841 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3843 ArgOffset += PtrByteSize;
3848 if (GPR_idx == NumGPRs && Size < 8) {
3849 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3850 PtrOff.getValueType());
3851 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3852 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3855 ArgOffset += PtrByteSize;
3858 // Copy entire object into memory. There are cases where gcc-generated
3859 // code assumes it is there, even if it could be put entirely into
3860 // registers. (This is not what the doc says.)
3862 // FIXME: The above statement is likely due to a misunderstanding of the
3863 // documents. All arguments must be copied into the parameter area BY
3864 // THE CALLEE in the event that the callee takes the address of any
3865 // formal argument. That has not yet been implemented. However, it is
3866 // reasonable to use the stack area as a staging area for the register
3869 // Skip this for small aggregates, as we will use the same slot for a
3870 // right-justified copy, below.
3872 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3876 // When a register is available, pass a small aggregate right-justified.
3877 if (Size < 8 && GPR_idx != NumGPRs) {
3878 // The easiest way to get this right-justified in a register
3879 // is to copy the structure into the rightmost portion of a
3880 // local variable slot, then load the whole slot into the
3882 // FIXME: The memcpy seems to produce pretty awful code for
3883 // small aggregates, particularly for packed ones.
3884 // FIXME: It would be preferable to use the slot in the
3885 // parameter save area instead of a new local variable.
3886 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3887 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3888 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3892 // Load the slot into the register.
3893 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3894 MachinePointerInfo(),
3895 false, false, false, 0);
3896 MemOpChains.push_back(Load.getValue(1));
3897 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3899 // Done with this argument.
3900 ArgOffset += PtrByteSize;
3904 // For aggregates larger than PtrByteSize, copy the pieces of the
3905 // object that fit into registers from the parameter save area.
3906 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3907 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3908 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3909 if (GPR_idx != NumGPRs) {
3910 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3911 MachinePointerInfo(),
3912 false, false, false, 0);
3913 MemOpChains.push_back(Load.getValue(1));
3914 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3915 ArgOffset += PtrByteSize;
3917 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3924 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3925 default: llvm_unreachable("Unexpected ValueType for argument!");
3928 if (GPR_idx != NumGPRs) {
3929 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3931 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3932 true, isTailCall, false, MemOpChains,
3933 TailCallArguments, dl);
3935 ArgOffset += PtrByteSize;
3939 if (FPR_idx != NumFPRs) {
3940 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3943 // A single float or an aggregate containing only a single float
3944 // must be passed right-justified in the stack doubleword, and
3945 // in the GPR, if one is available.
3947 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3948 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3949 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3953 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3954 MachinePointerInfo(), false, false, 0);
3955 MemOpChains.push_back(Store);
3957 // Float varargs are always shadowed in available integer registers
3958 if (GPR_idx != NumGPRs) {
3959 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3960 MachinePointerInfo(), false, false,
3962 MemOpChains.push_back(Load.getValue(1));
3963 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3965 } else if (GPR_idx != NumGPRs)
3966 // If we have any FPRs remaining, we may also have GPRs remaining.
3969 // Single-precision floating-point values are mapped to the
3970 // second (rightmost) word of the stack doubleword.
3971 if (Arg.getValueType() == MVT::f32) {
3972 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3973 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3976 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3977 true, isTailCall, false, MemOpChains,
3978 TailCallArguments, dl);
3987 // These go aligned on the stack, or in the corresponding R registers
3988 // when within range. The Darwin PPC ABI doc claims they also go in
3989 // V registers; in fact gcc does this only for arguments that are
3990 // prototyped, not for those that match the ... We do it for all
3991 // arguments, seems to work.
3992 while (ArgOffset % 16 !=0) {
3993 ArgOffset += PtrByteSize;
3994 if (GPR_idx != NumGPRs)
3997 // We could elide this store in the case where the object fits
3998 // entirely in R registers. Maybe later.
3999 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4000 DAG.getConstant(ArgOffset, PtrVT));
4001 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4002 MachinePointerInfo(), false, false, 0);
4003 MemOpChains.push_back(Store);
4004 if (VR_idx != NumVRs) {
4005 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4006 MachinePointerInfo(),
4007 false, false, false, 0);
4008 MemOpChains.push_back(Load.getValue(1));
4009 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4012 for (unsigned i=0; i<16; i+=PtrByteSize) {
4013 if (GPR_idx == NumGPRs)
4015 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4016 DAG.getConstant(i, PtrVT));
4017 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4018 false, false, false, 0);
4019 MemOpChains.push_back(Load.getValue(1));
4020 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4025 // Non-varargs Altivec params generally go in registers, but have
4026 // stack space allocated at the end.
4027 if (VR_idx != NumVRs) {
4028 // Doesn't have GPR space allocated.
4029 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4031 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4032 true, isTailCall, true, MemOpChains,
4033 TailCallArguments, dl);
4040 if (!MemOpChains.empty())
4041 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4042 &MemOpChains[0], MemOpChains.size());
4044 // Check if this is an indirect call (MTCTR/BCTRL).
4045 // See PrepareCall() for more information about calls through function
4046 // pointers in the 64-bit SVR4 ABI.
4048 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4049 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4050 !isBLACompatibleAddress(Callee, DAG)) {
4051 // Load r2 into a virtual register and store it to the TOC save area.
4052 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4053 // TOC save area offset.
4054 SDValue PtrOff = DAG.getIntPtrConstant(40);
4055 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4056 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4058 // R12 must contain the address of an indirect callee. This does not
4059 // mean the MTCTR instruction must use R12; it's easier to model this
4060 // as an extra parameter, so do that.
4061 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4064 // Build a sequence of copy-to-reg nodes chained together with token chain
4065 // and flag operands which copy the outgoing args into the appropriate regs.
4067 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4068 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4069 RegsToPass[i].second, InFlag);
4070 InFlag = Chain.getValue(1);
4074 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4075 FPOp, true, TailCallArguments);
4077 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4078 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4083 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4084 CallingConv::ID CallConv, bool isVarArg,
4086 const SmallVectorImpl<ISD::OutputArg> &Outs,
4087 const SmallVectorImpl<SDValue> &OutVals,
4088 const SmallVectorImpl<ISD::InputArg> &Ins,
4089 DebugLoc dl, SelectionDAG &DAG,
4090 SmallVectorImpl<SDValue> &InVals) const {
4092 unsigned NumOps = Outs.size();
4094 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4095 bool isPPC64 = PtrVT == MVT::i64;
4096 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4098 MachineFunction &MF = DAG.getMachineFunction();
4100 // Mark this function as potentially containing a function that contains a
4101 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4102 // and restoring the callers stack pointer in this functions epilog. This is
4103 // done because by tail calling the called function might overwrite the value
4104 // in this function's (MF) stack pointer stack slot 0(SP).
4105 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4106 CallConv == CallingConv::Fast)
4107 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4109 unsigned nAltivecParamsAtEnd = 0;
4111 // Count how many bytes are to be pushed on the stack, including the linkage
4112 // area, and parameter passing area. We start with 24/48 bytes, which is
4113 // prereserved space for [SP][CR][LR][3 x unused].
4115 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4117 nAltivecParamsAtEnd);
4119 // Calculate by how many bytes the stack has to be adjusted in case of tail
4120 // call optimization.
4121 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4123 // To protect arguments on the stack from being clobbered in a tail call,
4124 // force all the loads to happen before doing any other lowering.
4126 Chain = DAG.getStackArgumentTokenFactor(Chain);
4128 // Adjust the stack pointer for the new arguments...
4129 // These operations are automatically eliminated by the prolog/epilog pass
4130 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4131 SDValue CallSeqStart = Chain;
4133 // Load the return address and frame pointer so it can be move somewhere else
4136 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4139 // Set up a copy of the stack pointer for use loading and storing any
4140 // arguments that may not fit in the registers available for argument
4144 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4146 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4148 // Figure out which arguments are going to go in registers, and which in
4149 // memory. Also, if this is a vararg function, floating point operations
4150 // must be stored to our stack, and loaded into integer regs as well, if
4151 // any integer regs are available for argument passing.
4152 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4153 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4155 static const uint16_t GPR_32[] = { // 32-bit registers.
4156 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4157 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4159 static const uint16_t GPR_64[] = { // 64-bit registers.
4160 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4161 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4163 static const uint16_t *FPR = GetFPR();
4165 static const uint16_t VR[] = {
4166 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4167 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4169 const unsigned NumGPRs = array_lengthof(GPR_32);
4170 const unsigned NumFPRs = 13;
4171 const unsigned NumVRs = array_lengthof(VR);
4173 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4175 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4176 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4178 SmallVector<SDValue, 8> MemOpChains;
4179 for (unsigned i = 0; i != NumOps; ++i) {
4180 SDValue Arg = OutVals[i];
4181 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4183 // PtrOff will be used to store the current argument to the stack if a
4184 // register cannot be found for it.
4187 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4189 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4191 // On PPC64, promote integers to 64-bit values.
4192 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4193 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4194 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4195 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4198 // FIXME memcpy is used way more than necessary. Correctness first.
4199 // Note: "by value" is code for passing a structure by value, not
4201 if (Flags.isByVal()) {
4202 unsigned Size = Flags.getByValSize();
4203 // Very small objects are passed right-justified. Everything else is
4204 // passed left-justified.
4205 if (Size==1 || Size==2) {
4206 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4207 if (GPR_idx != NumGPRs) {
4208 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4209 MachinePointerInfo(), VT,
4211 MemOpChains.push_back(Load.getValue(1));
4212 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4214 ArgOffset += PtrByteSize;
4216 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4217 PtrOff.getValueType());
4218 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4219 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4222 ArgOffset += PtrByteSize;
4226 // Copy entire object into memory. There are cases where gcc-generated
4227 // code assumes it is there, even if it could be put entirely into
4228 // registers. (This is not what the doc says.)
4229 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4233 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4234 // copy the pieces of the object that fit into registers from the
4235 // parameter save area.
4236 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4237 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4238 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4239 if (GPR_idx != NumGPRs) {
4240 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4241 MachinePointerInfo(),
4242 false, false, false, 0);
4243 MemOpChains.push_back(Load.getValue(1));
4244 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4245 ArgOffset += PtrByteSize;
4247 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4254 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4255 default: llvm_unreachable("Unexpected ValueType for argument!");
4258 if (GPR_idx != NumGPRs) {
4259 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4261 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4262 isPPC64, isTailCall, false, MemOpChains,
4263 TailCallArguments, dl);
4265 ArgOffset += PtrByteSize;
4269 if (FPR_idx != NumFPRs) {
4270 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4273 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4274 MachinePointerInfo(), false, false, 0);
4275 MemOpChains.push_back(Store);
4277 // Float varargs are always shadowed in available integer registers
4278 if (GPR_idx != NumGPRs) {
4279 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4280 MachinePointerInfo(), false, false,
4282 MemOpChains.push_back(Load.getValue(1));
4283 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4285 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4286 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4287 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4288 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4289 MachinePointerInfo(),
4290 false, false, false, 0);
4291 MemOpChains.push_back(Load.getValue(1));
4292 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4295 // If we have any FPRs remaining, we may also have GPRs remaining.
4296 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4298 if (GPR_idx != NumGPRs)
4300 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4301 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4305 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4306 isPPC64, isTailCall, false, MemOpChains,
4307 TailCallArguments, dl);
4311 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4318 // These go aligned on the stack, or in the corresponding R registers
4319 // when within range. The Darwin PPC ABI doc claims they also go in
4320 // V registers; in fact gcc does this only for arguments that are
4321 // prototyped, not for those that match the ... We do it for all
4322 // arguments, seems to work.
4323 while (ArgOffset % 16 !=0) {
4324 ArgOffset += PtrByteSize;
4325 if (GPR_idx != NumGPRs)
4328 // We could elide this store in the case where the object fits
4329 // entirely in R registers. Maybe later.
4330 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4331 DAG.getConstant(ArgOffset, PtrVT));
4332 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4333 MachinePointerInfo(), false, false, 0);
4334 MemOpChains.push_back(Store);
4335 if (VR_idx != NumVRs) {
4336 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4337 MachinePointerInfo(),
4338 false, false, false, 0);
4339 MemOpChains.push_back(Load.getValue(1));
4340 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4343 for (unsigned i=0; i<16; i+=PtrByteSize) {
4344 if (GPR_idx == NumGPRs)
4346 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4347 DAG.getConstant(i, PtrVT));
4348 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4349 false, false, false, 0);
4350 MemOpChains.push_back(Load.getValue(1));
4351 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4356 // Non-varargs Altivec params generally go in registers, but have
4357 // stack space allocated at the end.
4358 if (VR_idx != NumVRs) {
4359 // Doesn't have GPR space allocated.
4360 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4361 } else if (nAltivecParamsAtEnd==0) {
4362 // We are emitting Altivec params in order.
4363 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4364 isPPC64, isTailCall, true, MemOpChains,
4365 TailCallArguments, dl);
4371 // If all Altivec parameters fit in registers, as they usually do,
4372 // they get stack space following the non-Altivec parameters. We
4373 // don't track this here because nobody below needs it.
4374 // If there are more Altivec parameters than fit in registers emit
4376 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4378 // Offset is aligned; skip 1st 12 params which go in V registers.
4379 ArgOffset = ((ArgOffset+15)/16)*16;
4381 for (unsigned i = 0; i != NumOps; ++i) {
4382 SDValue Arg = OutVals[i];
4383 EVT ArgType = Outs[i].VT;
4384 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4385 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4388 // We are emitting Altivec params in order.
4389 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4390 isPPC64, isTailCall, true, MemOpChains,
4391 TailCallArguments, dl);
4398 if (!MemOpChains.empty())
4399 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4400 &MemOpChains[0], MemOpChains.size());
4402 // On Darwin, R12 must contain the address of an indirect callee. This does
4403 // not mean the MTCTR instruction must use R12; it's easier to model this as
4404 // an extra parameter, so do that.
4406 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4407 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4408 !isBLACompatibleAddress(Callee, DAG))
4409 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4410 PPC::R12), Callee));
4412 // Build a sequence of copy-to-reg nodes chained together with token chain
4413 // and flag operands which copy the outgoing args into the appropriate regs.
4415 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4416 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4417 RegsToPass[i].second, InFlag);
4418 InFlag = Chain.getValue(1);
4422 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4423 FPOp, true, TailCallArguments);
4425 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4426 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4431 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4432 MachineFunction &MF, bool isVarArg,
4433 const SmallVectorImpl<ISD::OutputArg> &Outs,
4434 LLVMContext &Context) const {
4435 SmallVector<CCValAssign, 16> RVLocs;
4436 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4438 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4442 PPCTargetLowering::LowerReturn(SDValue Chain,
4443 CallingConv::ID CallConv, bool isVarArg,
4444 const SmallVectorImpl<ISD::OutputArg> &Outs,
4445 const SmallVectorImpl<SDValue> &OutVals,
4446 DebugLoc dl, SelectionDAG &DAG) const {
4448 SmallVector<CCValAssign, 16> RVLocs;
4449 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4450 getTargetMachine(), RVLocs, *DAG.getContext());
4451 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4454 SmallVector<SDValue, 4> RetOps(1, Chain);
4456 // Copy the result values into the output registers.
4457 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4458 CCValAssign &VA = RVLocs[i];
4459 assert(VA.isRegLoc() && "Can only return in registers!");
4461 SDValue Arg = OutVals[i];
4463 switch (VA.getLocInfo()) {
4464 default: llvm_unreachable("Unknown loc info!");
4465 case CCValAssign::Full: break;
4466 case CCValAssign::AExt:
4467 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4469 case CCValAssign::ZExt:
4470 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4472 case CCValAssign::SExt:
4473 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4477 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4478 Flag = Chain.getValue(1);
4479 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4482 RetOps[0] = Chain; // Update chain.
4484 // Add the flag if we have it.
4486 RetOps.push_back(Flag);
4488 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4489 &RetOps[0], RetOps.size());
4492 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4493 const PPCSubtarget &Subtarget) const {
4494 // When we pop the dynamic allocation we need to restore the SP link.
4495 DebugLoc dl = Op.getDebugLoc();
4497 // Get the corect type for pointers.
4498 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4500 // Construct the stack pointer operand.
4501 bool isPPC64 = Subtarget.isPPC64();
4502 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4503 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4505 // Get the operands for the STACKRESTORE.
4506 SDValue Chain = Op.getOperand(0);
4507 SDValue SaveSP = Op.getOperand(1);
4509 // Load the old link SP.
4510 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4511 MachinePointerInfo(),
4512 false, false, false, 0);
4514 // Restore the stack pointer.
4515 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4517 // Store the old link SP.
4518 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4525 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4526 MachineFunction &MF = DAG.getMachineFunction();
4527 bool isPPC64 = PPCSubTarget.isPPC64();
4528 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4529 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4531 // Get current frame pointer save index. The users of this index will be
4532 // primarily DYNALLOC instructions.
4533 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4534 int RASI = FI->getReturnAddrSaveIndex();
4536 // If the frame pointer save index hasn't been defined yet.
4538 // Find out what the fix offset of the frame pointer save area.
4539 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4540 // Allocate the frame index for frame pointer save area.
4541 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4543 FI->setReturnAddrSaveIndex(RASI);
4545 return DAG.getFrameIndex(RASI, PtrVT);
4549 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4550 MachineFunction &MF = DAG.getMachineFunction();
4551 bool isPPC64 = PPCSubTarget.isPPC64();
4552 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4553 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4555 // Get current frame pointer save index. The users of this index will be
4556 // primarily DYNALLOC instructions.
4557 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4558 int FPSI = FI->getFramePointerSaveIndex();
4560 // If the frame pointer save index hasn't been defined yet.
4562 // Find out what the fix offset of the frame pointer save area.
4563 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4566 // Allocate the frame index for frame pointer save area.
4567 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4569 FI->setFramePointerSaveIndex(FPSI);
4571 return DAG.getFrameIndex(FPSI, PtrVT);
4574 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4576 const PPCSubtarget &Subtarget) const {
4578 SDValue Chain = Op.getOperand(0);
4579 SDValue Size = Op.getOperand(1);
4580 DebugLoc dl = Op.getDebugLoc();
4582 // Get the corect type for pointers.
4583 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4585 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4586 DAG.getConstant(0, PtrVT), Size);
4587 // Construct a node for the frame pointer save index.
4588 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4589 // Build a DYNALLOC node.
4590 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4591 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4592 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4595 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4596 SelectionDAG &DAG) const {
4597 DebugLoc DL = Op.getDebugLoc();
4598 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4599 DAG.getVTList(MVT::i32, MVT::Other),
4600 Op.getOperand(0), Op.getOperand(1));
4603 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4604 SelectionDAG &DAG) const {
4605 DebugLoc DL = Op.getDebugLoc();
4606 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4607 Op.getOperand(0), Op.getOperand(1));
4610 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4612 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4613 // Not FP? Not a fsel.
4614 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4615 !Op.getOperand(2).getValueType().isFloatingPoint())
4618 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4620 // Cannot handle SETEQ/SETNE.
4621 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4623 EVT ResVT = Op.getValueType();
4624 EVT CmpVT = Op.getOperand(0).getValueType();
4625 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4626 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4627 DebugLoc dl = Op.getDebugLoc();
4629 // If the RHS of the comparison is a 0.0, we don't need to do the
4630 // subtraction at all.
4631 if (isFloatingPointZero(RHS))
4633 default: break; // SETUO etc aren't handled by fsel.
4636 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4639 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4640 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4641 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4644 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4647 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4648 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4649 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4650 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4655 default: break; // SETUO etc aren't handled by fsel.
4658 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4659 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4660 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4661 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4664 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4665 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4666 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4667 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4670 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4671 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4672 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4673 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4676 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4677 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4678 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4679 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4684 // FIXME: Split this code up when LegalizeDAGTypes lands.
4685 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4686 DebugLoc dl) const {
4687 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4688 SDValue Src = Op.getOperand(0);
4689 if (Src.getValueType() == MVT::f32)
4690 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4693 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4694 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4696 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4701 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4705 // Convert the FP value to an int value through memory.
4706 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4708 // Emit a store to the stack slot.
4709 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4710 MachinePointerInfo(), false, false, 0);
4712 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4714 if (Op.getValueType() == MVT::i32)
4715 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4716 DAG.getConstant(4, FIPtr.getValueType()));
4717 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4718 false, false, false, 0);
4721 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4722 SelectionDAG &DAG) const {
4723 DebugLoc dl = Op.getDebugLoc();
4724 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4725 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4728 if (Op.getOperand(0).getValueType() == MVT::i64) {
4729 SDValue SINT = Op.getOperand(0);
4730 // When converting to single-precision, we actually need to convert
4731 // to double-precision first and then round to single-precision.
4732 // To avoid double-rounding effects during that operation, we have
4733 // to prepare the input operand. Bits that might be truncated when
4734 // converting to double-precision are replaced by a bit that won't
4735 // be lost at this stage, but is below the single-precision rounding
4738 // However, if -enable-unsafe-fp-math is in effect, accept double
4739 // rounding to avoid the extra overhead.
4740 if (Op.getValueType() == MVT::f32 &&
4741 !DAG.getTarget().Options.UnsafeFPMath) {
4743 // Twiddle input to make sure the low 11 bits are zero. (If this
4744 // is the case, we are guaranteed the value will fit into the 53 bit
4745 // mantissa of an IEEE double-precision value without rounding.)
4746 // If any of those low 11 bits were not zero originally, make sure
4747 // bit 12 (value 2048) is set instead, so that the final rounding
4748 // to single-precision gets the correct result.
4749 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4750 SINT, DAG.getConstant(2047, MVT::i64));
4751 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4752 Round, DAG.getConstant(2047, MVT::i64));
4753 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4754 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4755 Round, DAG.getConstant(-2048, MVT::i64));
4757 // However, we cannot use that value unconditionally: if the magnitude
4758 // of the input value is small, the bit-twiddling we did above might
4759 // end up visibly changing the output. Fortunately, in that case, we
4760 // don't need to twiddle bits since the original input will convert
4761 // exactly to double-precision floating-point already. Therefore,
4762 // construct a conditional to use the original value if the top 11
4763 // bits are all sign-bit copies, and use the rounded value computed
4765 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4766 SINT, DAG.getConstant(53, MVT::i32));
4767 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4768 Cond, DAG.getConstant(1, MVT::i64));
4769 Cond = DAG.getSetCC(dl, MVT::i32,
4770 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4772 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4774 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4775 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4776 if (Op.getValueType() == MVT::f32)
4777 FP = DAG.getNode(ISD::FP_ROUND, dl,
4778 MVT::f32, FP, DAG.getIntPtrConstant(0));
4782 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4783 "Unhandled SINT_TO_FP type in custom expander!");
4784 // Since we only generate this in 64-bit mode, we can take advantage of
4785 // 64-bit registers. In particular, sign extend the input value into the
4786 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4787 // then lfd it and fcfid it.
4788 MachineFunction &MF = DAG.getMachineFunction();
4789 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4790 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4791 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4792 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4794 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4797 // STD the extended value into the stack slot.
4798 MachineMemOperand *MMO =
4799 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4800 MachineMemOperand::MOStore, 8, 8);
4801 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4803 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4804 Ops, 4, MVT::i64, MMO);
4805 // Load the value as a double.
4806 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4807 false, false, false, 0);
4809 // FCFID it and return it.
4810 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4811 if (Op.getValueType() == MVT::f32)
4812 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4816 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4817 SelectionDAG &DAG) const {
4818 DebugLoc dl = Op.getDebugLoc();
4820 The rounding mode is in bits 30:31 of FPSR, and has the following
4827 FLT_ROUNDS, on the other hand, expects the following:
4834 To perform the conversion, we do:
4835 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4838 MachineFunction &MF = DAG.getMachineFunction();
4839 EVT VT = Op.getValueType();
4840 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4841 SDValue MFFSreg, InFlag;
4843 // Save FP Control Word to register
4845 MVT::f64, // return register
4846 MVT::Glue // unused in this context
4848 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4850 // Save FP register to stack slot
4851 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4852 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4853 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4854 StackSlot, MachinePointerInfo(), false, false,0);
4856 // Load FP Control Word from low 32 bits of stack slot.
4857 SDValue Four = DAG.getConstant(4, PtrVT);
4858 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4859 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4860 false, false, false, 0);
4862 // Transform as necessary
4864 DAG.getNode(ISD::AND, dl, MVT::i32,
4865 CWD, DAG.getConstant(3, MVT::i32));
4867 DAG.getNode(ISD::SRL, dl, MVT::i32,
4868 DAG.getNode(ISD::AND, dl, MVT::i32,
4869 DAG.getNode(ISD::XOR, dl, MVT::i32,
4870 CWD, DAG.getConstant(3, MVT::i32)),
4871 DAG.getConstant(3, MVT::i32)),
4872 DAG.getConstant(1, MVT::i32));
4875 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4877 return DAG.getNode((VT.getSizeInBits() < 16 ?
4878 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4881 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4882 EVT VT = Op.getValueType();
4883 unsigned BitWidth = VT.getSizeInBits();
4884 DebugLoc dl = Op.getDebugLoc();
4885 assert(Op.getNumOperands() == 3 &&
4886 VT == Op.getOperand(1).getValueType() &&
4889 // Expand into a bunch of logical ops. Note that these ops
4890 // depend on the PPC behavior for oversized shift amounts.
4891 SDValue Lo = Op.getOperand(0);
4892 SDValue Hi = Op.getOperand(1);
4893 SDValue Amt = Op.getOperand(2);
4894 EVT AmtVT = Amt.getValueType();
4896 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4897 DAG.getConstant(BitWidth, AmtVT), Amt);
4898 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4899 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4900 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4901 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4902 DAG.getConstant(-BitWidth, AmtVT));
4903 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4904 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4905 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4906 SDValue OutOps[] = { OutLo, OutHi };
4907 return DAG.getMergeValues(OutOps, 2, dl);
4910 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4911 EVT VT = Op.getValueType();
4912 DebugLoc dl = Op.getDebugLoc();
4913 unsigned BitWidth = VT.getSizeInBits();
4914 assert(Op.getNumOperands() == 3 &&
4915 VT == Op.getOperand(1).getValueType() &&
4918 // Expand into a bunch of logical ops. Note that these ops
4919 // depend on the PPC behavior for oversized shift amounts.
4920 SDValue Lo = Op.getOperand(0);
4921 SDValue Hi = Op.getOperand(1);
4922 SDValue Amt = Op.getOperand(2);
4923 EVT AmtVT = Amt.getValueType();
4925 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4926 DAG.getConstant(BitWidth, AmtVT), Amt);
4927 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4928 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4929 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4930 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4931 DAG.getConstant(-BitWidth, AmtVT));
4932 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4933 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4934 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4935 SDValue OutOps[] = { OutLo, OutHi };
4936 return DAG.getMergeValues(OutOps, 2, dl);
4939 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4940 DebugLoc dl = Op.getDebugLoc();
4941 EVT VT = Op.getValueType();
4942 unsigned BitWidth = VT.getSizeInBits();
4943 assert(Op.getNumOperands() == 3 &&
4944 VT == Op.getOperand(1).getValueType() &&
4947 // Expand into a bunch of logical ops, followed by a select_cc.
4948 SDValue Lo = Op.getOperand(0);
4949 SDValue Hi = Op.getOperand(1);
4950 SDValue Amt = Op.getOperand(2);
4951 EVT AmtVT = Amt.getValueType();
4953 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4954 DAG.getConstant(BitWidth, AmtVT), Amt);
4955 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4956 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4957 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4958 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4959 DAG.getConstant(-BitWidth, AmtVT));
4960 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4961 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4962 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4963 Tmp4, Tmp6, ISD::SETLE);
4964 SDValue OutOps[] = { OutLo, OutHi };
4965 return DAG.getMergeValues(OutOps, 2, dl);
4968 //===----------------------------------------------------------------------===//
4969 // Vector related lowering.
4972 /// BuildSplatI - Build a canonical splati of Val with an element size of
4973 /// SplatSize. Cast the result to VT.
4974 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4975 SelectionDAG &DAG, DebugLoc dl) {
4976 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4978 static const EVT VTys[] = { // canonical VT to use for each size.
4979 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4982 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4984 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4988 EVT CanonicalVT = VTys[SplatSize-1];
4990 // Build a canonical splat for this value.
4991 SDValue Elt = DAG.getConstant(Val, MVT::i32);
4992 SmallVector<SDValue, 8> Ops;
4993 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4994 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4995 &Ops[0], Ops.size());
4996 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
4999 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5000 /// specified intrinsic ID.
5001 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5002 SelectionDAG &DAG, DebugLoc dl,
5003 EVT DestVT = MVT::Other) {
5004 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5005 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5006 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5009 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5010 /// specified intrinsic ID.
5011 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5012 SDValue Op2, SelectionDAG &DAG,
5013 DebugLoc dl, EVT DestVT = MVT::Other) {
5014 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5015 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5016 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5020 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5021 /// amount. The result has the specified value type.
5022 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5023 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
5024 // Force LHS/RHS to be the right type.
5025 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5026 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5029 for (unsigned i = 0; i != 16; ++i)
5031 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5032 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5035 // If this is a case we can't handle, return null and let the default
5036 // expansion code take care of it. If we CAN select this case, and if it
5037 // selects to a single instruction, return Op. Otherwise, if we can codegen
5038 // this case more efficiently than a constant pool load, lower it to the
5039 // sequence of ops that should be used.
5040 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5041 SelectionDAG &DAG) const {
5042 DebugLoc dl = Op.getDebugLoc();
5043 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5044 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5046 // Check if this is a splat of a constant value.
5047 APInt APSplatBits, APSplatUndef;
5048 unsigned SplatBitSize;
5050 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5051 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5054 unsigned SplatBits = APSplatBits.getZExtValue();
5055 unsigned SplatUndef = APSplatUndef.getZExtValue();
5056 unsigned SplatSize = SplatBitSize / 8;
5058 // First, handle single instruction cases.
5061 if (SplatBits == 0) {
5062 // Canonicalize all zero vectors to be v4i32.
5063 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5064 SDValue Z = DAG.getConstant(0, MVT::i32);
5065 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5066 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5071 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5072 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5074 if (SextVal >= -16 && SextVal <= 15)
5075 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5078 // Two instruction sequences.
5080 // If this value is in the range [-32,30] and is even, use:
5081 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5082 // If this value is in the range [17,31] and is odd, use:
5083 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5084 // If this value is in the range [-31,-17] and is odd, use:
5085 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5086 // Note the last two are three-instruction sequences.
5087 if (SextVal >= -32 && SextVal <= 31) {
5088 // To avoid having these optimizations undone by constant folding,
5089 // we convert to a pseudo that will be expanded later into one of
5091 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5092 EVT VT = Op.getValueType();
5093 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5094 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5095 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5098 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5099 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5101 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5102 // Make -1 and vspltisw -1:
5103 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5105 // Make the VSLW intrinsic, computing 0x8000_0000.
5106 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5109 // xor by OnesV to invert it.
5110 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5111 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5114 // Check to see if this is a wide variety of vsplti*, binop self cases.
5115 static const signed char SplatCsts[] = {
5116 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5117 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5120 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5121 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5122 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5123 int i = SplatCsts[idx];
5125 // Figure out what shift amount will be used by altivec if shifted by i in
5127 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5129 // vsplti + shl self.
5130 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5131 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5132 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5133 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5134 Intrinsic::ppc_altivec_vslw
5136 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5137 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5140 // vsplti + srl self.
5141 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5142 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5143 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5144 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5145 Intrinsic::ppc_altivec_vsrw
5147 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5148 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5151 // vsplti + sra self.
5152 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5153 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5154 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5155 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5156 Intrinsic::ppc_altivec_vsraw
5158 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5159 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5162 // vsplti + rol self.
5163 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5164 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5165 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5166 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5167 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5168 Intrinsic::ppc_altivec_vrlw
5170 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5171 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5174 // t = vsplti c, result = vsldoi t, t, 1
5175 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5176 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5177 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5179 // t = vsplti c, result = vsldoi t, t, 2
5180 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5181 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5182 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5184 // t = vsplti c, result = vsldoi t, t, 3
5185 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5186 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5187 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5194 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5195 /// the specified operations to build the shuffle.
5196 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5197 SDValue RHS, SelectionDAG &DAG,
5199 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5200 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5201 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5204 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5216 if (OpNum == OP_COPY) {
5217 if (LHSID == (1*9+2)*9+3) return LHS;
5218 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5222 SDValue OpLHS, OpRHS;
5223 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5224 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5228 default: llvm_unreachable("Unknown i32 permute!");
5230 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5231 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5232 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5233 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5236 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5237 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5238 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5239 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5242 for (unsigned i = 0; i != 16; ++i)
5243 ShufIdxs[i] = (i&3)+0;
5246 for (unsigned i = 0; i != 16; ++i)
5247 ShufIdxs[i] = (i&3)+4;
5250 for (unsigned i = 0; i != 16; ++i)
5251 ShufIdxs[i] = (i&3)+8;
5254 for (unsigned i = 0; i != 16; ++i)
5255 ShufIdxs[i] = (i&3)+12;
5258 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5260 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5262 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5264 EVT VT = OpLHS.getValueType();
5265 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5266 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5267 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5268 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5271 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5272 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5273 /// return the code it can be lowered into. Worst case, it can always be
5274 /// lowered into a vperm.
5275 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5276 SelectionDAG &DAG) const {
5277 DebugLoc dl = Op.getDebugLoc();
5278 SDValue V1 = Op.getOperand(0);
5279 SDValue V2 = Op.getOperand(1);
5280 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5281 EVT VT = Op.getValueType();
5283 // Cases that are handled by instructions that take permute immediates
5284 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5285 // selected by the instruction selector.
5286 if (V2.getOpcode() == ISD::UNDEF) {
5287 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5288 PPC::isSplatShuffleMask(SVOp, 2) ||
5289 PPC::isSplatShuffleMask(SVOp, 4) ||
5290 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5291 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5292 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5293 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5294 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5295 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5296 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5297 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5298 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5303 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5304 // and produce a fixed permutation. If any of these match, do not lower to
5306 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5307 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5308 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5309 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5310 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5311 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5312 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5313 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5314 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5317 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5318 // perfect shuffle table to emit an optimal matching sequence.
5319 ArrayRef<int> PermMask = SVOp->getMask();
5321 unsigned PFIndexes[4];
5322 bool isFourElementShuffle = true;
5323 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5324 unsigned EltNo = 8; // Start out undef.
5325 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5326 if (PermMask[i*4+j] < 0)
5327 continue; // Undef, ignore it.
5329 unsigned ByteSource = PermMask[i*4+j];
5330 if ((ByteSource & 3) != j) {
5331 isFourElementShuffle = false;
5336 EltNo = ByteSource/4;
5337 } else if (EltNo != ByteSource/4) {
5338 isFourElementShuffle = false;
5342 PFIndexes[i] = EltNo;
5345 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5346 // perfect shuffle vector to determine if it is cost effective to do this as
5347 // discrete instructions, or whether we should use a vperm.
5348 if (isFourElementShuffle) {
5349 // Compute the index in the perfect shuffle table.
5350 unsigned PFTableIndex =
5351 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5353 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5354 unsigned Cost = (PFEntry >> 30);
5356 // Determining when to avoid vperm is tricky. Many things affect the cost
5357 // of vperm, particularly how many times the perm mask needs to be computed.
5358 // For example, if the perm mask can be hoisted out of a loop or is already
5359 // used (perhaps because there are multiple permutes with the same shuffle
5360 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5361 // the loop requires an extra register.
5363 // As a compromise, we only emit discrete instructions if the shuffle can be
5364 // generated in 3 or fewer operations. When we have loop information
5365 // available, if this block is within a loop, we should avoid using vperm
5366 // for 3-operation perms and use a constant pool load instead.
5368 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5371 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5372 // vector that will get spilled to the constant pool.
5373 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5375 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5376 // that it is in input element units, not in bytes. Convert now.
5377 EVT EltVT = V1.getValueType().getVectorElementType();
5378 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5380 SmallVector<SDValue, 16> ResultMask;
5381 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5382 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5384 for (unsigned j = 0; j != BytesPerElement; ++j)
5385 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5389 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5390 &ResultMask[0], ResultMask.size());
5391 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5394 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5395 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5396 /// information about the intrinsic.
5397 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5399 unsigned IntrinsicID =
5400 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5403 switch (IntrinsicID) {
5404 default: return false;
5405 // Comparison predicates.
5406 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5407 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5408 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5409 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5410 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5411 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5412 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5413 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5414 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5415 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5416 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5417 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5418 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5420 // Normal Comparisons.
5421 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5422 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5423 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5424 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5425 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5426 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5427 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5428 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5429 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5430 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5431 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5432 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5433 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5438 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5439 /// lower, do it, otherwise return null.
5440 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5441 SelectionDAG &DAG) const {
5442 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5443 // opcode number of the comparison.
5444 DebugLoc dl = Op.getDebugLoc();
5447 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5448 return SDValue(); // Don't custom lower most intrinsics.
5450 // If this is a non-dot comparison, make the VCMP node and we are done.
5452 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5453 Op.getOperand(1), Op.getOperand(2),
5454 DAG.getConstant(CompareOpc, MVT::i32));
5455 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5458 // Create the PPCISD altivec 'dot' comparison node.
5460 Op.getOperand(2), // LHS
5461 Op.getOperand(3), // RHS
5462 DAG.getConstant(CompareOpc, MVT::i32)
5464 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5465 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5467 // Now that we have the comparison, emit a copy from the CR to a GPR.
5468 // This is flagged to the above dot comparison.
5469 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5470 DAG.getRegister(PPC::CR6, MVT::i32),
5471 CompNode.getValue(1));
5473 // Unpack the result based on how the target uses it.
5474 unsigned BitNo; // Bit # of CR6.
5475 bool InvertBit; // Invert result?
5476 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5477 default: // Can't happen, don't crash on invalid number though.
5478 case 0: // Return the value of the EQ bit of CR6.
5479 BitNo = 0; InvertBit = false;
5481 case 1: // Return the inverted value of the EQ bit of CR6.
5482 BitNo = 0; InvertBit = true;
5484 case 2: // Return the value of the LT bit of CR6.
5485 BitNo = 2; InvertBit = false;
5487 case 3: // Return the inverted value of the LT bit of CR6.
5488 BitNo = 2; InvertBit = true;
5492 // Shift the bit into the low position.
5493 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5494 DAG.getConstant(8-(3-BitNo), MVT::i32));
5496 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5497 DAG.getConstant(1, MVT::i32));
5499 // If we are supposed to, toggle the bit.
5501 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5502 DAG.getConstant(1, MVT::i32));
5506 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5507 SelectionDAG &DAG) const {
5508 DebugLoc dl = Op.getDebugLoc();
5509 // Create a stack slot that is 16-byte aligned.
5510 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5511 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5512 EVT PtrVT = getPointerTy();
5513 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5515 // Store the input value into Value#0 of the stack slot.
5516 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5517 Op.getOperand(0), FIdx, MachinePointerInfo(),
5520 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5521 false, false, false, 0);
5524 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5525 DebugLoc dl = Op.getDebugLoc();
5526 if (Op.getValueType() == MVT::v4i32) {
5527 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5529 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5530 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5532 SDValue RHSSwap = // = vrlw RHS, 16
5533 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5535 // Shrinkify inputs to v8i16.
5536 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5537 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5538 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5540 // Low parts multiplied together, generating 32-bit results (we ignore the
5542 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5543 LHS, RHS, DAG, dl, MVT::v4i32);
5545 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5546 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5547 // Shift the high parts up 16 bits.
5548 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5550 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5551 } else if (Op.getValueType() == MVT::v8i16) {
5552 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5554 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5556 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5557 LHS, RHS, Zero, DAG, dl);
5558 } else if (Op.getValueType() == MVT::v16i8) {
5559 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5561 // Multiply the even 8-bit parts, producing 16-bit sums.
5562 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5563 LHS, RHS, DAG, dl, MVT::v8i16);
5564 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5566 // Multiply the odd 8-bit parts, producing 16-bit sums.
5567 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5568 LHS, RHS, DAG, dl, MVT::v8i16);
5569 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5571 // Merge the results together.
5573 for (unsigned i = 0; i != 8; ++i) {
5575 Ops[i*2+1] = 2*i+1+16;
5577 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5579 llvm_unreachable("Unknown mul to lower!");
5583 /// LowerOperation - Provide custom lowering hooks for some operations.
5585 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5586 switch (Op.getOpcode()) {
5587 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5588 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5589 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5590 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5591 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5592 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5593 case ISD::SETCC: return LowerSETCC(Op, DAG);
5594 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5595 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5597 return LowerVASTART(Op, DAG, PPCSubTarget);
5600 return LowerVAARG(Op, DAG, PPCSubTarget);
5602 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5603 case ISD::DYNAMIC_STACKALLOC:
5604 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5606 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5607 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5609 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5610 case ISD::FP_TO_UINT:
5611 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5613 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5614 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5616 // Lower 64-bit shifts.
5617 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5618 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5619 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5621 // Vector-related lowering.
5622 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5623 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5624 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5625 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5626 case ISD::MUL: return LowerMUL(Op, DAG);
5628 // Frame & Return address.
5629 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5630 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5634 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5635 SmallVectorImpl<SDValue>&Results,
5636 SelectionDAG &DAG) const {
5637 const TargetMachine &TM = getTargetMachine();
5638 DebugLoc dl = N->getDebugLoc();
5639 switch (N->getOpcode()) {
5641 llvm_unreachable("Do not know how to custom type legalize this operation!");
5643 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5644 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5647 EVT VT = N->getValueType(0);
5649 if (VT == MVT::i64) {
5650 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5652 Results.push_back(NewNode);
5653 Results.push_back(NewNode.getValue(1));
5657 case ISD::FP_ROUND_INREG: {
5658 assert(N->getValueType(0) == MVT::ppcf128);
5659 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5660 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5661 MVT::f64, N->getOperand(0),
5662 DAG.getIntPtrConstant(0));
5663 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5664 MVT::f64, N->getOperand(0),
5665 DAG.getIntPtrConstant(1));
5667 // Add the two halves of the long double in round-to-zero mode.
5668 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5670 // We know the low half is about to be thrown away, so just use something
5672 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5676 case ISD::FP_TO_SINT:
5677 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5683 //===----------------------------------------------------------------------===//
5684 // Other Lowering Code
5685 //===----------------------------------------------------------------------===//
5688 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5689 bool is64bit, unsigned BinOpcode) const {
5690 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5691 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5693 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5694 MachineFunction *F = BB->getParent();
5695 MachineFunction::iterator It = BB;
5698 unsigned dest = MI->getOperand(0).getReg();
5699 unsigned ptrA = MI->getOperand(1).getReg();
5700 unsigned ptrB = MI->getOperand(2).getReg();
5701 unsigned incr = MI->getOperand(3).getReg();
5702 DebugLoc dl = MI->getDebugLoc();
5704 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5705 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5706 F->insert(It, loopMBB);
5707 F->insert(It, exitMBB);
5708 exitMBB->splice(exitMBB->begin(), BB,
5709 llvm::next(MachineBasicBlock::iterator(MI)),
5711 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5713 MachineRegisterInfo &RegInfo = F->getRegInfo();
5714 unsigned TmpReg = (!BinOpcode) ? incr :
5715 RegInfo.createVirtualRegister(
5716 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5717 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5721 // fallthrough --> loopMBB
5722 BB->addSuccessor(loopMBB);
5725 // l[wd]arx dest, ptr
5726 // add r0, dest, incr
5727 // st[wd]cx. r0, ptr
5729 // fallthrough --> exitMBB
5731 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5732 .addReg(ptrA).addReg(ptrB);
5734 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5735 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5736 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5737 BuildMI(BB, dl, TII->get(PPC::BCC))
5738 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5739 BB->addSuccessor(loopMBB);
5740 BB->addSuccessor(exitMBB);
5749 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5750 MachineBasicBlock *BB,
5751 bool is8bit, // operation
5752 unsigned BinOpcode) const {
5753 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5754 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5755 // In 64 bit mode we have to use 64 bits for addresses, even though the
5756 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5757 // registers without caring whether they're 32 or 64, but here we're
5758 // doing actual arithmetic on the addresses.
5759 bool is64bit = PPCSubTarget.isPPC64();
5760 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5762 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5763 MachineFunction *F = BB->getParent();
5764 MachineFunction::iterator It = BB;
5767 unsigned dest = MI->getOperand(0).getReg();
5768 unsigned ptrA = MI->getOperand(1).getReg();
5769 unsigned ptrB = MI->getOperand(2).getReg();
5770 unsigned incr = MI->getOperand(3).getReg();
5771 DebugLoc dl = MI->getDebugLoc();
5773 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5774 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5775 F->insert(It, loopMBB);
5776 F->insert(It, exitMBB);
5777 exitMBB->splice(exitMBB->begin(), BB,
5778 llvm::next(MachineBasicBlock::iterator(MI)),
5780 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5782 MachineRegisterInfo &RegInfo = F->getRegInfo();
5783 const TargetRegisterClass *RC =
5784 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5785 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5786 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5787 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5788 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5789 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5790 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5791 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5792 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5793 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5794 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5795 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5796 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5798 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5802 // fallthrough --> loopMBB
5803 BB->addSuccessor(loopMBB);
5805 // The 4-byte load must be aligned, while a char or short may be
5806 // anywhere in the word. Hence all this nasty bookkeeping code.
5807 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5808 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5809 // xori shift, shift1, 24 [16]
5810 // rlwinm ptr, ptr1, 0, 0, 29
5811 // slw incr2, incr, shift
5812 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5813 // slw mask, mask2, shift
5815 // lwarx tmpDest, ptr
5816 // add tmp, tmpDest, incr2
5817 // andc tmp2, tmpDest, mask
5818 // and tmp3, tmp, mask
5819 // or tmp4, tmp3, tmp2
5822 // fallthrough --> exitMBB
5823 // srw dest, tmpDest, shift
5824 if (ptrA != ZeroReg) {
5825 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5826 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5827 .addReg(ptrA).addReg(ptrB);
5831 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5832 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5833 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5834 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5836 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5837 .addReg(Ptr1Reg).addImm(0).addImm(61);
5839 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5840 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5841 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5842 .addReg(incr).addReg(ShiftReg);
5844 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5846 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5847 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5849 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5850 .addReg(Mask2Reg).addReg(ShiftReg);
5853 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5854 .addReg(ZeroReg).addReg(PtrReg);
5856 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5857 .addReg(Incr2Reg).addReg(TmpDestReg);
5858 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5859 .addReg(TmpDestReg).addReg(MaskReg);
5860 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5861 .addReg(TmpReg).addReg(MaskReg);
5862 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5863 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5864 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5865 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5866 BuildMI(BB, dl, TII->get(PPC::BCC))
5867 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5868 BB->addSuccessor(loopMBB);
5869 BB->addSuccessor(exitMBB);
5874 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5879 llvm::MachineBasicBlock*
5880 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
5881 MachineBasicBlock *MBB) const {
5882 DebugLoc DL = MI->getDebugLoc();
5883 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5885 MachineFunction *MF = MBB->getParent();
5886 MachineRegisterInfo &MRI = MF->getRegInfo();
5888 const BasicBlock *BB = MBB->getBasicBlock();
5889 MachineFunction::iterator I = MBB;
5893 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
5894 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
5896 unsigned DstReg = MI->getOperand(0).getReg();
5897 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
5898 assert(RC->hasType(MVT::i32) && "Invalid destination!");
5899 unsigned mainDstReg = MRI.createVirtualRegister(RC);
5900 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
5902 MVT PVT = getPointerTy();
5903 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
5904 "Invalid Pointer Size!");
5905 // For v = setjmp(buf), we generate
5908 // SjLjSetup mainMBB
5914 // buf[LabelOffset] = LR
5918 // v = phi(main, restore)
5921 MachineBasicBlock *thisMBB = MBB;
5922 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
5923 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
5924 MF->insert(I, mainMBB);
5925 MF->insert(I, sinkMBB);
5927 MachineInstrBuilder MIB;
5929 // Transfer the remainder of BB and its successor edges to sinkMBB.
5930 sinkMBB->splice(sinkMBB->begin(), MBB,
5931 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
5932 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
5934 // Note that the structure of the jmp_buf used here is not compatible
5935 // with that used by libc, and is not designed to be. Specifically, it
5936 // stores only those 'reserved' registers that LLVM does not otherwise
5937 // understand how to spill. Also, by convention, by the time this
5938 // intrinsic is called, Clang has already stored the frame address in the
5939 // first slot of the buffer and stack address in the third. Following the
5940 // X86 target code, we'll store the jump address in the second slot. We also
5941 // need to save the TOC pointer (R2) to handle jumps between shared
5942 // libraries, and that will be stored in the fourth slot. The thread
5943 // identifier (R13) is not affected.
5946 const int64_t LabelOffset = 1 * PVT.getStoreSize();
5947 const int64_t TOCOffset = 3 * PVT.getStoreSize();
5949 // Prepare IP either in reg.
5950 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
5951 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
5952 unsigned BufReg = MI->getOperand(1).getReg();
5954 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
5955 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
5957 .addImm(TOCOffset / 4)
5960 MIB.setMemRefs(MMOBegin, MMOEnd);
5964 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCL)).addMBB(mainMBB);
5965 MIB.addRegMask(PPCRegInfo->getNoPreservedMask());
5967 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
5969 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
5971 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
5973 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
5974 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
5978 MIB = BuildMI(mainMBB, DL,
5979 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
5982 if (PPCSubTarget.isPPC64()) {
5983 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
5985 .addImm(LabelOffset / 4)
5988 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
5990 .addImm(LabelOffset)
5994 MIB.setMemRefs(MMOBegin, MMOEnd);
5996 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
5997 mainMBB->addSuccessor(sinkMBB);
6000 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6001 TII->get(PPC::PHI), DstReg)
6002 .addReg(mainDstReg).addMBB(mainMBB)
6003 .addReg(restoreDstReg).addMBB(thisMBB);
6005 MI->eraseFromParent();
6010 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6011 MachineBasicBlock *MBB) const {
6012 DebugLoc DL = MI->getDebugLoc();
6013 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6015 MachineFunction *MF = MBB->getParent();
6016 MachineRegisterInfo &MRI = MF->getRegInfo();
6019 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6020 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6022 MVT PVT = getPointerTy();
6023 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6024 "Invalid Pointer Size!");
6026 const TargetRegisterClass *RC =
6027 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6028 unsigned Tmp = MRI.createVirtualRegister(RC);
6029 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6030 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6031 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6033 MachineInstrBuilder MIB;
6035 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6036 const int64_t SPOffset = 2 * PVT.getStoreSize();
6037 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6039 unsigned BufReg = MI->getOperand(0).getReg();
6041 // Reload FP (the jumped-to function may not have had a
6042 // frame pointer, and if so, then its r31 will be restored
6044 if (PVT == MVT::i64) {
6045 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6049 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6053 MIB.setMemRefs(MMOBegin, MMOEnd);
6056 if (PVT == MVT::i64) {
6057 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6058 .addImm(LabelOffset / 4)
6061 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6062 .addImm(LabelOffset)
6065 MIB.setMemRefs(MMOBegin, MMOEnd);
6068 if (PVT == MVT::i64) {
6069 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6070 .addImm(SPOffset / 4)
6073 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6077 MIB.setMemRefs(MMOBegin, MMOEnd);
6079 // FIXME: When we also support base pointers, that register must also be
6083 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6084 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6085 .addImm(TOCOffset / 4)
6088 MIB.setMemRefs(MMOBegin, MMOEnd);
6092 BuildMI(*MBB, MI, DL,
6093 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6094 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6096 MI->eraseFromParent();
6101 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6102 MachineBasicBlock *BB) const {
6103 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6104 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6105 return emitEHSjLjSetJmp(MI, BB);
6106 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6107 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6108 return emitEHSjLjLongJmp(MI, BB);
6111 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6113 // To "insert" these instructions we actually have to insert their
6114 // control-flow patterns.
6115 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6116 MachineFunction::iterator It = BB;
6119 MachineFunction *F = BB->getParent();
6121 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6122 MI->getOpcode() == PPC::SELECT_CC_I8)) {
6123 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
6124 PPC::ISEL8 : PPC::ISEL;
6125 unsigned SelectPred = MI->getOperand(4).getImm();
6126 DebugLoc dl = MI->getDebugLoc();
6130 switch (SelectPred) {
6131 default: llvm_unreachable("invalid predicate for isel");
6132 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
6133 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
6134 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
6135 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
6136 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
6137 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
6138 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
6139 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
6142 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
6143 .addReg(MI->getOperand(SwapOps? 3 : 2).getReg())
6144 .addReg(MI->getOperand(SwapOps? 2 : 3).getReg())
6145 .addReg(MI->getOperand(1).getReg(), 0, SubIdx);
6146 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6147 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6148 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6149 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6150 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6153 // The incoming instruction knows the destination vreg to set, the
6154 // condition code register to branch on, the true/false values to
6155 // select between, and a branch opcode to use.
6160 // cmpTY ccX, r1, r2
6162 // fallthrough --> copy0MBB
6163 MachineBasicBlock *thisMBB = BB;
6164 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6165 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6166 unsigned SelectPred = MI->getOperand(4).getImm();
6167 DebugLoc dl = MI->getDebugLoc();
6168 F->insert(It, copy0MBB);
6169 F->insert(It, sinkMBB);
6171 // Transfer the remainder of BB and its successor edges to sinkMBB.
6172 sinkMBB->splice(sinkMBB->begin(), BB,
6173 llvm::next(MachineBasicBlock::iterator(MI)),
6175 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6177 // Next, add the true and fallthrough blocks as its successors.
6178 BB->addSuccessor(copy0MBB);
6179 BB->addSuccessor(sinkMBB);
6181 BuildMI(BB, dl, TII->get(PPC::BCC))
6182 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6185 // %FalseValue = ...
6186 // # fallthrough to sinkMBB
6189 // Update machine-CFG edges
6190 BB->addSuccessor(sinkMBB);
6193 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6196 BuildMI(*BB, BB->begin(), dl,
6197 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6198 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6199 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6201 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6202 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6203 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6204 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6205 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6206 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6207 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6208 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6210 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6211 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6212 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6213 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6214 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6215 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6216 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6217 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6219 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6220 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6221 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6222 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6223 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6224 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6225 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6226 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6228 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6229 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6230 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6231 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6232 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6233 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6234 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6235 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6237 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6238 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6239 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6240 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6241 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6242 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6243 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6244 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6246 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6247 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6248 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6249 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6250 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6251 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6252 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6253 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6255 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6256 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6257 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6258 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6259 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6260 BB = EmitAtomicBinary(MI, BB, false, 0);
6261 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6262 BB = EmitAtomicBinary(MI, BB, true, 0);
6264 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6265 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6266 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6268 unsigned dest = MI->getOperand(0).getReg();
6269 unsigned ptrA = MI->getOperand(1).getReg();
6270 unsigned ptrB = MI->getOperand(2).getReg();
6271 unsigned oldval = MI->getOperand(3).getReg();
6272 unsigned newval = MI->getOperand(4).getReg();
6273 DebugLoc dl = MI->getDebugLoc();
6275 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6276 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6277 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6278 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6279 F->insert(It, loop1MBB);
6280 F->insert(It, loop2MBB);
6281 F->insert(It, midMBB);
6282 F->insert(It, exitMBB);
6283 exitMBB->splice(exitMBB->begin(), BB,
6284 llvm::next(MachineBasicBlock::iterator(MI)),
6286 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6290 // fallthrough --> loopMBB
6291 BB->addSuccessor(loop1MBB);
6294 // l[wd]arx dest, ptr
6295 // cmp[wd] dest, oldval
6298 // st[wd]cx. newval, ptr
6302 // st[wd]cx. dest, ptr
6305 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6306 .addReg(ptrA).addReg(ptrB);
6307 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6308 .addReg(oldval).addReg(dest);
6309 BuildMI(BB, dl, TII->get(PPC::BCC))
6310 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6311 BB->addSuccessor(loop2MBB);
6312 BB->addSuccessor(midMBB);
6315 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6316 .addReg(newval).addReg(ptrA).addReg(ptrB);
6317 BuildMI(BB, dl, TII->get(PPC::BCC))
6318 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6319 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6320 BB->addSuccessor(loop1MBB);
6321 BB->addSuccessor(exitMBB);
6324 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6325 .addReg(dest).addReg(ptrA).addReg(ptrB);
6326 BB->addSuccessor(exitMBB);
6331 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6332 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6333 // We must use 64-bit registers for addresses when targeting 64-bit,
6334 // since we're actually doing arithmetic on them. Other registers
6336 bool is64bit = PPCSubTarget.isPPC64();
6337 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6339 unsigned dest = MI->getOperand(0).getReg();
6340 unsigned ptrA = MI->getOperand(1).getReg();
6341 unsigned ptrB = MI->getOperand(2).getReg();
6342 unsigned oldval = MI->getOperand(3).getReg();
6343 unsigned newval = MI->getOperand(4).getReg();
6344 DebugLoc dl = MI->getDebugLoc();
6346 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6347 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6348 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6349 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6350 F->insert(It, loop1MBB);
6351 F->insert(It, loop2MBB);
6352 F->insert(It, midMBB);
6353 F->insert(It, exitMBB);
6354 exitMBB->splice(exitMBB->begin(), BB,
6355 llvm::next(MachineBasicBlock::iterator(MI)),
6357 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6359 MachineRegisterInfo &RegInfo = F->getRegInfo();
6360 const TargetRegisterClass *RC =
6361 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6362 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6363 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6364 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6365 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6366 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6367 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6368 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6369 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6370 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6371 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6372 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6373 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6374 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6375 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6377 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6378 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6381 // fallthrough --> loopMBB
6382 BB->addSuccessor(loop1MBB);
6384 // The 4-byte load must be aligned, while a char or short may be
6385 // anywhere in the word. Hence all this nasty bookkeeping code.
6386 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6387 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6388 // xori shift, shift1, 24 [16]
6389 // rlwinm ptr, ptr1, 0, 0, 29
6390 // slw newval2, newval, shift
6391 // slw oldval2, oldval,shift
6392 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6393 // slw mask, mask2, shift
6394 // and newval3, newval2, mask
6395 // and oldval3, oldval2, mask
6397 // lwarx tmpDest, ptr
6398 // and tmp, tmpDest, mask
6399 // cmpw tmp, oldval3
6402 // andc tmp2, tmpDest, mask
6403 // or tmp4, tmp2, newval3
6408 // stwcx. tmpDest, ptr
6410 // srw dest, tmpDest, shift
6411 if (ptrA != ZeroReg) {
6412 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6413 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6414 .addReg(ptrA).addReg(ptrB);
6418 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6419 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6420 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6421 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6423 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6424 .addReg(Ptr1Reg).addImm(0).addImm(61);
6426 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6427 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6428 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6429 .addReg(newval).addReg(ShiftReg);
6430 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6431 .addReg(oldval).addReg(ShiftReg);
6433 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6435 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6436 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6437 .addReg(Mask3Reg).addImm(65535);
6439 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6440 .addReg(Mask2Reg).addReg(ShiftReg);
6441 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6442 .addReg(NewVal2Reg).addReg(MaskReg);
6443 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6444 .addReg(OldVal2Reg).addReg(MaskReg);
6447 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6448 .addReg(ZeroReg).addReg(PtrReg);
6449 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6450 .addReg(TmpDestReg).addReg(MaskReg);
6451 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6452 .addReg(TmpReg).addReg(OldVal3Reg);
6453 BuildMI(BB, dl, TII->get(PPC::BCC))
6454 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6455 BB->addSuccessor(loop2MBB);
6456 BB->addSuccessor(midMBB);
6459 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6460 .addReg(TmpDestReg).addReg(MaskReg);
6461 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6462 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6463 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6464 .addReg(ZeroReg).addReg(PtrReg);
6465 BuildMI(BB, dl, TII->get(PPC::BCC))
6466 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6467 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6468 BB->addSuccessor(loop1MBB);
6469 BB->addSuccessor(exitMBB);
6472 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6473 .addReg(ZeroReg).addReg(PtrReg);
6474 BB->addSuccessor(exitMBB);
6479 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6481 } else if (MI->getOpcode() == PPC::FADDrtz) {
6482 // This pseudo performs an FADD with rounding mode temporarily forced
6483 // to round-to-zero. We emit this via custom inserter since the FPSCR
6484 // is not modeled at the SelectionDAG level.
6485 unsigned Dest = MI->getOperand(0).getReg();
6486 unsigned Src1 = MI->getOperand(1).getReg();
6487 unsigned Src2 = MI->getOperand(2).getReg();
6488 DebugLoc dl = MI->getDebugLoc();
6490 MachineRegisterInfo &RegInfo = F->getRegInfo();
6491 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6493 // Save FPSCR value.
6494 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6496 // Set rounding mode to round-to-zero.
6497 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6498 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6500 // Perform addition.
6501 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6503 // Restore FPSCR value.
6504 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6506 llvm_unreachable("Unexpected instr type to insert");
6509 MI->eraseFromParent(); // The pseudo instruction is gone now.
6513 //===----------------------------------------------------------------------===//
6514 // Target Optimization Hooks
6515 //===----------------------------------------------------------------------===//
6517 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6518 DAGCombinerInfo &DCI) const {
6519 const TargetMachine &TM = getTargetMachine();
6520 SelectionDAG &DAG = DCI.DAG;
6521 DebugLoc dl = N->getDebugLoc();
6522 switch (N->getOpcode()) {
6525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6526 if (C->isNullValue()) // 0 << V -> 0.
6527 return N->getOperand(0);
6531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6532 if (C->isNullValue()) // 0 >>u V -> 0.
6533 return N->getOperand(0);
6537 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6538 if (C->isNullValue() || // 0 >>s V -> 0.
6539 C->isAllOnesValue()) // -1 >>s V -> -1.
6540 return N->getOperand(0);
6544 case ISD::SINT_TO_FP:
6545 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6546 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6547 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6548 // We allow the src/dst to be either f32/f64, but the intermediate
6549 // type must be i64.
6550 if (N->getOperand(0).getValueType() == MVT::i64 &&
6551 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6552 SDValue Val = N->getOperand(0).getOperand(0);
6553 if (Val.getValueType() == MVT::f32) {
6554 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6555 DCI.AddToWorklist(Val.getNode());
6558 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6559 DCI.AddToWorklist(Val.getNode());
6560 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6561 DCI.AddToWorklist(Val.getNode());
6562 if (N->getValueType(0) == MVT::f32) {
6563 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6564 DAG.getIntPtrConstant(0));
6565 DCI.AddToWorklist(Val.getNode());
6568 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6569 // If the intermediate type is i32, we can avoid the load/store here
6576 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6577 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6578 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6579 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6580 N->getOperand(1).getValueType() == MVT::i32 &&
6581 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6582 SDValue Val = N->getOperand(1).getOperand(0);
6583 if (Val.getValueType() == MVT::f32) {
6584 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6585 DCI.AddToWorklist(Val.getNode());
6587 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6588 DCI.AddToWorklist(Val.getNode());
6590 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6591 N->getOperand(2), N->getOperand(3));
6592 DCI.AddToWorklist(Val.getNode());
6596 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6597 if (cast<StoreSDNode>(N)->isUnindexed() &&
6598 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6599 N->getOperand(1).getNode()->hasOneUse() &&
6600 (N->getOperand(1).getValueType() == MVT::i32 ||
6601 N->getOperand(1).getValueType() == MVT::i16)) {
6602 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6603 // Do an any-extend to 32-bits if this is a half-word input.
6604 if (BSwapOp.getValueType() == MVT::i16)
6605 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6608 N->getOperand(0), BSwapOp, N->getOperand(2),
6609 DAG.getValueType(N->getOperand(1).getValueType())
6612 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6613 Ops, array_lengthof(Ops),
6614 cast<StoreSDNode>(N)->getMemoryVT(),
6615 cast<StoreSDNode>(N)->getMemOperand());
6619 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6620 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6621 N->getOperand(0).hasOneUse() &&
6622 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6623 SDValue Load = N->getOperand(0);
6624 LoadSDNode *LD = cast<LoadSDNode>(Load);
6625 // Create the byte-swapping load.
6627 LD->getChain(), // Chain
6628 LD->getBasePtr(), // Ptr
6629 DAG.getValueType(N->getValueType(0)) // VT
6632 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6633 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6634 LD->getMemoryVT(), LD->getMemOperand());
6636 // If this is an i16 load, insert the truncate.
6637 SDValue ResVal = BSLoad;
6638 if (N->getValueType(0) == MVT::i16)
6639 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6641 // First, combine the bswap away. This makes the value produced by the
6643 DCI.CombineTo(N, ResVal);
6645 // Next, combine the load away, we give it a bogus result value but a real
6646 // chain result. The result value is dead because the bswap is dead.
6647 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6649 // Return N so it doesn't get rechecked!
6650 return SDValue(N, 0);
6654 case PPCISD::VCMP: {
6655 // If a VCMPo node already exists with exactly the same operands as this
6656 // node, use its result instead of this node (VCMPo computes both a CR6 and
6657 // a normal output).
6659 if (!N->getOperand(0).hasOneUse() &&
6660 !N->getOperand(1).hasOneUse() &&
6661 !N->getOperand(2).hasOneUse()) {
6663 // Scan all of the users of the LHS, looking for VCMPo's that match.
6664 SDNode *VCMPoNode = 0;
6666 SDNode *LHSN = N->getOperand(0).getNode();
6667 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6669 if (UI->getOpcode() == PPCISD::VCMPo &&
6670 UI->getOperand(1) == N->getOperand(1) &&
6671 UI->getOperand(2) == N->getOperand(2) &&
6672 UI->getOperand(0) == N->getOperand(0)) {
6677 // If there is no VCMPo node, or if the flag value has a single use, don't
6679 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6682 // Look at the (necessarily single) use of the flag value. If it has a
6683 // chain, this transformation is more complex. Note that multiple things
6684 // could use the value result, which we should ignore.
6685 SDNode *FlagUser = 0;
6686 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6687 FlagUser == 0; ++UI) {
6688 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6690 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6691 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6698 // If the user is a MFCR instruction, we know this is safe. Otherwise we
6699 // give up for right now.
6700 if (FlagUser->getOpcode() == PPCISD::MFCR)
6701 return SDValue(VCMPoNode, 0);
6706 // If this is a branch on an altivec predicate comparison, lower this so
6707 // that we don't have to do a MFCR: instead, branch directly on CR6. This
6708 // lowering is done pre-legalize, because the legalizer lowers the predicate
6709 // compare down to code that is difficult to reassemble.
6710 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6711 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6715 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6716 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6717 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6718 assert(isDot && "Can't compare against a vector result!");
6720 // If this is a comparison against something other than 0/1, then we know
6721 // that the condition is never/always true.
6722 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6723 if (Val != 0 && Val != 1) {
6724 if (CC == ISD::SETEQ) // Cond never true, remove branch.
6725 return N->getOperand(0);
6726 // Always !=, turn it into an unconditional branch.
6727 return DAG.getNode(ISD::BR, dl, MVT::Other,
6728 N->getOperand(0), N->getOperand(4));
6731 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6733 // Create the PPCISD altivec 'dot' comparison node.
6735 LHS.getOperand(2), // LHS of compare
6736 LHS.getOperand(3), // RHS of compare
6737 DAG.getConstant(CompareOpc, MVT::i32)
6739 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
6740 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6742 // Unpack the result based on how the target uses it.
6743 PPC::Predicate CompOpc;
6744 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6745 default: // Can't happen, don't crash on invalid number though.
6746 case 0: // Branch on the value of the EQ bit of CR6.
6747 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6749 case 1: // Branch on the inverted value of the EQ bit of CR6.
6750 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6752 case 2: // Branch on the value of the LT bit of CR6.
6753 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6755 case 3: // Branch on the inverted value of the LT bit of CR6.
6756 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6760 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6761 DAG.getConstant(CompOpc, MVT::i32),
6762 DAG.getRegister(PPC::CR6, MVT::i32),
6763 N->getOperand(4), CompNode.getValue(1));
6772 //===----------------------------------------------------------------------===//
6773 // Inline Assembly Support
6774 //===----------------------------------------------------------------------===//
6776 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6779 const SelectionDAG &DAG,
6780 unsigned Depth) const {
6781 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6782 switch (Op.getOpcode()) {
6784 case PPCISD::LBRX: {
6785 // lhbrx is known to have the top bits cleared out.
6786 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6787 KnownZero = 0xFFFF0000;
6790 case ISD::INTRINSIC_WO_CHAIN: {
6791 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6793 case Intrinsic::ppc_altivec_vcmpbfp_p:
6794 case Intrinsic::ppc_altivec_vcmpeqfp_p:
6795 case Intrinsic::ppc_altivec_vcmpequb_p:
6796 case Intrinsic::ppc_altivec_vcmpequh_p:
6797 case Intrinsic::ppc_altivec_vcmpequw_p:
6798 case Intrinsic::ppc_altivec_vcmpgefp_p:
6799 case Intrinsic::ppc_altivec_vcmpgtfp_p:
6800 case Intrinsic::ppc_altivec_vcmpgtsb_p:
6801 case Intrinsic::ppc_altivec_vcmpgtsh_p:
6802 case Intrinsic::ppc_altivec_vcmpgtsw_p:
6803 case Intrinsic::ppc_altivec_vcmpgtub_p:
6804 case Intrinsic::ppc_altivec_vcmpgtuh_p:
6805 case Intrinsic::ppc_altivec_vcmpgtuw_p:
6806 KnownZero = ~1U; // All bits but the low one are known to be zero.
6814 /// getConstraintType - Given a constraint, return the type of
6815 /// constraint it is for this target.
6816 PPCTargetLowering::ConstraintType
6817 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6818 if (Constraint.size() == 1) {
6819 switch (Constraint[0]) {
6826 return C_RegisterClass;
6828 // FIXME: While Z does indicate a memory constraint, it specifically
6829 // indicates an r+r address (used in conjunction with the 'y' modifier
6830 // in the replacement string). Currently, we're forcing the base
6831 // register to be r0 in the asm printer (which is interpreted as zero)
6832 // and forming the complete address in the second register. This is
6837 return TargetLowering::getConstraintType(Constraint);
6840 /// Examine constraint type and operand type and determine a weight value.
6841 /// This object must already have been set up with the operand type
6842 /// and the current alternative constraint selected.
6843 TargetLowering::ConstraintWeight
6844 PPCTargetLowering::getSingleConstraintMatchWeight(
6845 AsmOperandInfo &info, const char *constraint) const {
6846 ConstraintWeight weight = CW_Invalid;
6847 Value *CallOperandVal = info.CallOperandVal;
6848 // If we don't have a value, we can't do a match,
6849 // but allow it at the lowest weight.
6850 if (CallOperandVal == NULL)
6852 Type *type = CallOperandVal->getType();
6853 // Look at the constraint type.
6854 switch (*constraint) {
6856 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6859 if (type->isIntegerTy())
6860 weight = CW_Register;
6863 if (type->isFloatTy())
6864 weight = CW_Register;
6867 if (type->isDoubleTy())
6868 weight = CW_Register;
6871 if (type->isVectorTy())
6872 weight = CW_Register;
6875 weight = CW_Register;
6884 std::pair<unsigned, const TargetRegisterClass*>
6885 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6887 if (Constraint.size() == 1) {
6888 // GCC RS6000 Constraint Letters
6889 switch (Constraint[0]) {
6891 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6892 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
6893 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
6895 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6896 return std::make_pair(0U, &PPC::G8RCRegClass);
6897 return std::make_pair(0U, &PPC::GPRCRegClass);
6899 if (VT == MVT::f32 || VT == MVT::i32)
6900 return std::make_pair(0U, &PPC::F4RCRegClass);
6901 if (VT == MVT::f64 || VT == MVT::i64)
6902 return std::make_pair(0U, &PPC::F8RCRegClass);
6905 return std::make_pair(0U, &PPC::VRRCRegClass);
6907 return std::make_pair(0U, &PPC::CRRCRegClass);
6911 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6915 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6916 /// vector. If it is invalid, don't add anything to Ops.
6917 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6918 std::string &Constraint,
6919 std::vector<SDValue>&Ops,
6920 SelectionDAG &DAG) const {
6921 SDValue Result(0,0);
6923 // Only support length 1 constraints.
6924 if (Constraint.length() > 1) return;
6926 char Letter = Constraint[0];
6937 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6938 if (!CST) return; // Must be an immediate to match.
6939 unsigned Value = CST->getZExtValue();
6941 default: llvm_unreachable("Unknown constraint letter!");
6942 case 'I': // "I" is a signed 16-bit constant.
6943 if ((short)Value == (int)Value)
6944 Result = DAG.getTargetConstant(Value, Op.getValueType());
6946 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
6947 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
6948 if ((short)Value == 0)
6949 Result = DAG.getTargetConstant(Value, Op.getValueType());
6951 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
6952 if ((Value >> 16) == 0)
6953 Result = DAG.getTargetConstant(Value, Op.getValueType());
6955 case 'M': // "M" is a constant that is greater than 31.
6957 Result = DAG.getTargetConstant(Value, Op.getValueType());
6959 case 'N': // "N" is a positive constant that is an exact power of two.
6960 if ((int)Value > 0 && isPowerOf2_32(Value))
6961 Result = DAG.getTargetConstant(Value, Op.getValueType());
6963 case 'O': // "O" is the constant zero.
6965 Result = DAG.getTargetConstant(Value, Op.getValueType());
6967 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
6968 if ((short)-Value == (int)-Value)
6969 Result = DAG.getTargetConstant(Value, Op.getValueType());
6976 if (Result.getNode()) {
6977 Ops.push_back(Result);
6981 // Handle standard constraint letters.
6982 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6985 // isLegalAddressingMode - Return true if the addressing mode represented
6986 // by AM is legal for this target, for a load/store of the specified type.
6987 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6989 // FIXME: PPC does not allow r+i addressing modes for vectors!
6991 // PPC allows a sign-extended 16-bit immediate field.
6992 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
6995 // No global is ever allowed as a base.
6999 // PPC only support r+r,
7001 case 0: // "r+i" or just "i", depending on HasBaseReg.
7004 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
7006 // Otherwise we have r+r or r+i.
7009 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
7011 // Allow 2*r as r+r.
7014 // No other scales are supported.
7021 /// isLegalAddressImmediate - Return true if the integer value can be used
7022 /// as the offset of the target addressing mode for load / store of the
7024 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
7025 // PPC allows a sign-extended 16-bit immediate field.
7026 return (V > -(1 << 16) && V < (1 << 16)-1);
7029 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
7033 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7034 SelectionDAG &DAG) const {
7035 MachineFunction &MF = DAG.getMachineFunction();
7036 MachineFrameInfo *MFI = MF.getFrameInfo();
7037 MFI->setReturnAddressIsTaken(true);
7039 DebugLoc dl = Op.getDebugLoc();
7040 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7042 // Make sure the function does not optimize away the store of the RA to
7044 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7045 FuncInfo->setLRStoreRequired();
7046 bool isPPC64 = PPCSubTarget.isPPC64();
7047 bool isDarwinABI = PPCSubTarget.isDarwinABI();
7050 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7053 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7054 isPPC64? MVT::i64 : MVT::i32);
7055 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7056 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7058 MachinePointerInfo(), false, false, false, 0);
7061 // Just load the return address off the stack.
7062 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7063 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7064 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7067 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7068 SelectionDAG &DAG) const {
7069 DebugLoc dl = Op.getDebugLoc();
7070 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7072 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7073 bool isPPC64 = PtrVT == MVT::i64;
7075 MachineFunction &MF = DAG.getMachineFunction();
7076 MachineFrameInfo *MFI = MF.getFrameInfo();
7077 MFI->setFrameAddressIsTaken(true);
7079 // Naked functions never have a frame pointer, and so we use r1. For all
7080 // other functions, this decision must be delayed until during PEI.
7082 if (MF.getFunction()->getAttributes().hasAttribute(
7083 AttributeSet::FunctionIndex, Attribute::Naked))
7084 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7086 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7088 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7091 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7092 FrameAddr, MachinePointerInfo(), false, false,
7098 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7099 // The PowerPC target isn't yet aware of offsets.
7103 /// getOptimalMemOpType - Returns the target specific optimal type for load
7104 /// and store operations as a result of memset, memcpy, and memmove
7105 /// lowering. If DstAlign is zero that means it's safe to destination
7106 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7107 /// means there isn't a need to check it against alignment requirement,
7108 /// probably because the source does not need to be loaded. If 'IsMemset' is
7109 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7110 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7111 /// source is constant so it does not need to be loaded.
7112 /// It returns EVT::Other if the type should be determined using generic
7113 /// target-independent logic.
7114 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7115 unsigned DstAlign, unsigned SrcAlign,
7116 bool IsMemset, bool ZeroMemset,
7118 MachineFunction &MF) const {
7119 if (this->PPCSubTarget.isPPC64()) {
7126 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7128 if (DisablePPCUnaligned)
7131 // PowerPC supports unaligned memory access for simple non-vector types.
7132 // Although accessing unaligned addresses is not as efficient as accessing
7133 // aligned addresses, it is generally more efficient than manual expansion,
7134 // and generally only traps for software emulation when crossing page
7140 if (VT.getSimpleVT().isVector())
7143 if (VT == MVT::ppcf128)
7152 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
7153 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
7154 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
7155 /// is expanded to mul + add.
7156 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
7160 switch (VT.getSimpleVT().SimpleTy) {
7172 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7174 return TargetLowering::getSchedulingPreference(N);