1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
40 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
41 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
43 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
44 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
46 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
47 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
49 // FIXME: Remove this once the bug has been fixed!
50 extern cl::opt<bool> ANDIGlueBug;
52 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
53 if (TM.getSubtargetImpl()->isDarwin())
54 return new TargetLoweringObjectFileMachO();
56 if (TM.getSubtargetImpl()->isSVR4ABI())
57 return new PPC64LinuxTargetObjectFile();
59 return new TargetLoweringObjectFileELF();
62 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
63 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
64 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
68 // Use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(true);
72 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73 // arguments are at least 4/8 bytes aligned.
74 bool isPPC64 = Subtarget->isPPC64();
75 setMinStackArgumentAlignment(isPPC64 ? 8:4);
77 // Set up the register classes.
78 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
82 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
86 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88 // PowerPC has pre-inc load and store's.
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
100 if (Subtarget->useCRBits()) {
101 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 if (isPPC64 || Subtarget->hasFPCVT()) {
104 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
109 isPPC64 ? MVT::i64 : MVT::i32);
111 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115 // PowerPC does not support direct load / store of condition registers
116 setOperationAction(ISD::LOAD, MVT::i1, Custom);
117 setOperationAction(ISD::STORE, MVT::i1, Custom);
119 // FIXME: Remove this once the ANDI glue bug is fixed:
121 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget->hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget->hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath &&
185 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget->hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget->hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget->hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget->useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget->useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget->useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget->isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget->isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget->has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (PPCSubTarget.hasFPCVT()) {
371 if (Subtarget->has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget->use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget->hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
407 // add/sub are legal for all supported vector VT's.
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
411 // We promote all shuffles to v16i8.
412 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
415 // We promote all non-typed operations to v4i32.
416 setOperationAction(ISD::AND , VT, Promote);
417 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
418 setOperationAction(ISD::OR , VT, Promote);
419 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
420 setOperationAction(ISD::XOR , VT, Promote);
421 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
422 setOperationAction(ISD::LOAD , VT, Promote);
423 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
424 setOperationAction(ISD::SELECT, VT, Promote);
425 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426 setOperationAction(ISD::STORE, VT, Promote);
427 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
429 // No other operations are legal.
430 setOperationAction(ISD::MUL , VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::SREM, VT, Expand);
433 setOperationAction(ISD::UDIV, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
435 setOperationAction(ISD::FDIV, VT, Expand);
436 setOperationAction(ISD::FREM, VT, Expand);
437 setOperationAction(ISD::FNEG, VT, Expand);
438 setOperationAction(ISD::FSQRT, VT, Expand);
439 setOperationAction(ISD::FLOG, VT, Expand);
440 setOperationAction(ISD::FLOG10, VT, Expand);
441 setOperationAction(ISD::FLOG2, VT, Expand);
442 setOperationAction(ISD::FEXP, VT, Expand);
443 setOperationAction(ISD::FEXP2, VT, Expand);
444 setOperationAction(ISD::FSIN, VT, Expand);
445 setOperationAction(ISD::FCOS, VT, Expand);
446 setOperationAction(ISD::FABS, VT, Expand);
447 setOperationAction(ISD::FPOWI, VT, Expand);
448 setOperationAction(ISD::FFLOOR, VT, Expand);
449 setOperationAction(ISD::FCEIL, VT, Expand);
450 setOperationAction(ISD::FTRUNC, VT, Expand);
451 setOperationAction(ISD::FRINT, VT, Expand);
452 setOperationAction(ISD::FNEARBYINT, VT, Expand);
453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458 setOperationAction(ISD::UDIVREM, VT, Expand);
459 setOperationAction(ISD::SDIVREM, VT, Expand);
460 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461 setOperationAction(ISD::FPOW, VT, Expand);
462 setOperationAction(ISD::CTPOP, VT, Expand);
463 setOperationAction(ISD::CTLZ, VT, Expand);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
465 setOperationAction(ISD::CTTZ, VT, Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
467 setOperationAction(ISD::VSELECT, VT, Expand);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
471 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
472 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
473 setTruncStoreAction(VT, InnerVT, Expand);
475 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
476 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
477 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
480 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
481 // with merges, splats, etc.
482 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
484 setOperationAction(ISD::AND , MVT::v4i32, Legal);
485 setOperationAction(ISD::OR , MVT::v4i32, Legal);
486 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
487 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
488 setOperationAction(ISD::SELECT, MVT::v4i32,
489 Subtarget->useCRBits() ? Legal : Expand);
490 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
491 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
492 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
493 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
494 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
495 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
496 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
497 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
500 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
501 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
502 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
503 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
505 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
506 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
508 if (TM.Options.UnsafeFPMath || Subtarget->hasVSX()) {
509 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
510 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
513 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
515 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
517 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
518 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
522 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
523 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
525 // Altivec does not contain unordered floating-point compare instructions
526 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
527 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
531 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536 if (Subtarget->hasVSX()) {
537 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
540 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
541 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
543 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
545 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
547 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
548 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
550 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
551 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
553 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
554 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
559 // Share the Altivec comparison restrictions.
560 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
561 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
562 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
567 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
570 addRegisterClass(MVT::f64, &PPC::VSRCRegClass);
572 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
573 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
575 // VSX v2i64 only supports non-arithmetic operations.
576 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
577 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
579 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
583 if (Subtarget->has64BitSupport()) {
584 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
585 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
588 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
589 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
590 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
591 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
593 setBooleanContents(ZeroOrOneBooleanContent);
594 // Altivec instructions set fields to all zeros or all ones.
595 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
598 setStackPointerRegisterToSaveRestore(PPC::X1);
599 setExceptionPointerRegister(PPC::X3);
600 setExceptionSelectorRegister(PPC::X4);
602 setStackPointerRegisterToSaveRestore(PPC::R1);
603 setExceptionPointerRegister(PPC::R3);
604 setExceptionSelectorRegister(PPC::R4);
607 // We have target-specific dag combine patterns for the following nodes:
608 setTargetDAGCombine(ISD::SINT_TO_FP);
609 setTargetDAGCombine(ISD::LOAD);
610 setTargetDAGCombine(ISD::STORE);
611 setTargetDAGCombine(ISD::BR_CC);
612 if (Subtarget->useCRBits())
613 setTargetDAGCombine(ISD::BRCOND);
614 setTargetDAGCombine(ISD::BSWAP);
615 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
617 setTargetDAGCombine(ISD::SIGN_EXTEND);
618 setTargetDAGCombine(ISD::ZERO_EXTEND);
619 setTargetDAGCombine(ISD::ANY_EXTEND);
621 if (Subtarget->useCRBits()) {
622 setTargetDAGCombine(ISD::TRUNCATE);
623 setTargetDAGCombine(ISD::SETCC);
624 setTargetDAGCombine(ISD::SELECT_CC);
627 // Use reciprocal estimates.
628 if (TM.Options.UnsafeFPMath) {
629 setTargetDAGCombine(ISD::FDIV);
630 setTargetDAGCombine(ISD::FSQRT);
633 // Darwin long double math library functions have $LDBL128 appended.
634 if (Subtarget->isDarwin()) {
635 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
636 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
637 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
638 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
639 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
640 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
641 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
642 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
643 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
644 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
647 // With 32 condition bits, we don't need to sink (and duplicate) compares
648 // aggressively in CodeGenPrep.
649 if (Subtarget->useCRBits())
650 setHasMultipleConditionRegisters();
652 setMinFunctionAlignment(2);
653 if (PPCSubTarget.isDarwin())
654 setPrefFunctionAlignment(4);
656 if (isPPC64 && Subtarget->isJITCodeModel())
657 // Temporary workaround for the inability of PPC64 JIT to handle jump
659 setSupportJumpTables(false);
661 setInsertFencesForAtomic(true);
663 if (Subtarget->enableMachineScheduler())
664 setSchedulingPreference(Sched::Source);
666 setSchedulingPreference(Sched::Hybrid);
668 computeRegisterProperties();
670 // The Freescale cores does better with aggressive inlining of memcpy and
671 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
672 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
673 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
674 MaxStoresPerMemset = 32;
675 MaxStoresPerMemsetOptSize = 16;
676 MaxStoresPerMemcpy = 32;
677 MaxStoresPerMemcpyOptSize = 8;
678 MaxStoresPerMemmove = 32;
679 MaxStoresPerMemmoveOptSize = 8;
681 setPrefFunctionAlignment(4);
685 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
686 /// the desired ByVal argument alignment.
687 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
688 unsigned MaxMaxAlign) {
689 if (MaxAlign == MaxMaxAlign)
691 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
692 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
694 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
696 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
697 unsigned EltAlign = 0;
698 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
699 if (EltAlign > MaxAlign)
701 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
702 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
703 unsigned EltAlign = 0;
704 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
705 if (EltAlign > MaxAlign)
707 if (MaxAlign == MaxMaxAlign)
713 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
714 /// function arguments in the caller parameter area.
715 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
716 // Darwin passes everything on 4 byte boundary.
717 if (PPCSubTarget.isDarwin())
720 // 16byte and wider vectors are passed on 16byte boundary.
721 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
722 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
723 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
724 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
728 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
731 case PPCISD::FSEL: return "PPCISD::FSEL";
732 case PPCISD::FCFID: return "PPCISD::FCFID";
733 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
734 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
735 case PPCISD::FRE: return "PPCISD::FRE";
736 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
737 case PPCISD::STFIWX: return "PPCISD::STFIWX";
738 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
739 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
740 case PPCISD::VPERM: return "PPCISD::VPERM";
741 case PPCISD::Hi: return "PPCISD::Hi";
742 case PPCISD::Lo: return "PPCISD::Lo";
743 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
744 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
745 case PPCISD::LOAD: return "PPCISD::LOAD";
746 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
747 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
748 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
749 case PPCISD::SRL: return "PPCISD::SRL";
750 case PPCISD::SRA: return "PPCISD::SRA";
751 case PPCISD::SHL: return "PPCISD::SHL";
752 case PPCISD::CALL: return "PPCISD::CALL";
753 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
754 case PPCISD::MTCTR: return "PPCISD::MTCTR";
755 case PPCISD::BCTRL: return "PPCISD::BCTRL";
756 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
757 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
758 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
759 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
760 case PPCISD::VCMP: return "PPCISD::VCMP";
761 case PPCISD::VCMPo: return "PPCISD::VCMPo";
762 case PPCISD::LBRX: return "PPCISD::LBRX";
763 case PPCISD::STBRX: return "PPCISD::STBRX";
764 case PPCISD::LARX: return "PPCISD::LARX";
765 case PPCISD::STCX: return "PPCISD::STCX";
766 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
767 case PPCISD::BDNZ: return "PPCISD::BDNZ";
768 case PPCISD::BDZ: return "PPCISD::BDZ";
769 case PPCISD::MFFS: return "PPCISD::MFFS";
770 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
771 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
772 case PPCISD::CR6SET: return "PPCISD::CR6SET";
773 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
774 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
775 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
776 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
777 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
778 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
779 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
780 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
781 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
782 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
783 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
784 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
785 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
786 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
787 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
788 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
789 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
790 case PPCISD::SC: return "PPCISD::SC";
794 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
796 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
797 return VT.changeVectorElementTypeToInteger();
800 //===----------------------------------------------------------------------===//
801 // Node matching predicates, for use by the tblgen matching code.
802 //===----------------------------------------------------------------------===//
804 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
805 static bool isFloatingPointZero(SDValue Op) {
806 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
807 return CFP->getValueAPF().isZero();
808 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
809 // Maybe this has already been legalized into the constant pool?
810 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
811 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
812 return CFP->getValueAPF().isZero();
817 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
818 /// true if Op is undef or if it matches the specified value.
819 static bool isConstantOrUndef(int Op, int Val) {
820 return Op < 0 || Op == Val;
823 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
824 /// VPKUHUM instruction.
825 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
827 for (unsigned i = 0; i != 16; ++i)
828 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
831 for (unsigned i = 0; i != 8; ++i)
832 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
833 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
839 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
840 /// VPKUWUM instruction.
841 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
843 for (unsigned i = 0; i != 16; i += 2)
844 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
845 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
848 for (unsigned i = 0; i != 8; i += 2)
849 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
850 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
851 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
852 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
858 /// isVMerge - Common function, used to match vmrg* shuffles.
860 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
861 unsigned LHSStart, unsigned RHSStart) {
862 assert(N->getValueType(0) == MVT::v16i8 &&
863 "PPC only supports shuffles by bytes!");
864 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
865 "Unsupported merge size!");
867 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
868 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
869 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
870 LHSStart+j+i*UnitSize) ||
871 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
872 RHSStart+j+i*UnitSize))
878 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
879 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
880 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
883 return isVMerge(N, UnitSize, 8, 24);
884 return isVMerge(N, UnitSize, 8, 8);
887 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
888 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
889 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
892 return isVMerge(N, UnitSize, 0, 16);
893 return isVMerge(N, UnitSize, 0, 0);
897 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
898 /// amount, otherwise return -1.
899 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
900 assert(N->getValueType(0) == MVT::v16i8 &&
901 "PPC only supports shuffles by bytes!");
903 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
905 // Find the first non-undef value in the shuffle mask.
907 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
910 if (i == 16) return -1; // all undef.
912 // Otherwise, check to see if the rest of the elements are consecutively
913 // numbered from this value.
914 unsigned ShiftAmt = SVOp->getMaskElt(i);
915 if (ShiftAmt < i) return -1;
919 // Check the rest of the elements to see if they are consecutive.
920 for (++i; i != 16; ++i)
921 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
924 // Check the rest of the elements to see if they are consecutive.
925 for (++i; i != 16; ++i)
926 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
932 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
933 /// specifies a splat of a single element that is suitable for input to
934 /// VSPLTB/VSPLTH/VSPLTW.
935 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
936 assert(N->getValueType(0) == MVT::v16i8 &&
937 (EltSize == 1 || EltSize == 2 || EltSize == 4));
939 // This is a splat operation if each element of the permute is the same, and
940 // if the value doesn't reference the second vector.
941 unsigned ElementBase = N->getMaskElt(0);
943 // FIXME: Handle UNDEF elements too!
944 if (ElementBase >= 16)
947 // Check that the indices are consecutive, in the case of a multi-byte element
948 // splatted with a v16i8 mask.
949 for (unsigned i = 1; i != EltSize; ++i)
950 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
953 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
954 if (N->getMaskElt(i) < 0) continue;
955 for (unsigned j = 0; j != EltSize; ++j)
956 if (N->getMaskElt(i+j) != N->getMaskElt(j))
962 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
964 bool PPC::isAllNegativeZeroVector(SDNode *N) {
965 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
967 APInt APVal, APUndef;
971 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
972 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
973 return CFP->getValueAPF().isNegZero();
978 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
979 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
980 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
981 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
982 assert(isSplatShuffleMask(SVOp, EltSize));
983 return SVOp->getMaskElt(0) / EltSize;
986 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
987 /// by using a vspltis[bhw] instruction of the specified element size, return
988 /// the constant being splatted. The ByteSize field indicates the number of
989 /// bytes of each element [124] -> [bhw].
990 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
993 // If ByteSize of the splat is bigger than the element size of the
994 // build_vector, then we have a case where we are checking for a splat where
995 // multiple elements of the buildvector are folded together into a single
996 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
997 unsigned EltSize = 16/N->getNumOperands();
998 if (EltSize < ByteSize) {
999 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1000 SDValue UniquedVals[4];
1001 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1003 // See if all of the elements in the buildvector agree across.
1004 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1005 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1006 // If the element isn't a constant, bail fully out.
1007 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1010 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
1011 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1012 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1013 return SDValue(); // no match.
1016 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1017 // either constant or undef values that are identical for each chunk. See
1018 // if these chunks can form into a larger vspltis*.
1020 // Check to see if all of the leading entries are either 0 or -1. If
1021 // neither, then this won't fit into the immediate field.
1022 bool LeadingZero = true;
1023 bool LeadingOnes = true;
1024 for (unsigned i = 0; i != Multiple-1; ++i) {
1025 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
1027 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1028 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1030 // Finally, check the least significant entry.
1032 if (UniquedVals[Multiple-1].getNode() == 0)
1033 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1034 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1036 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1039 if (UniquedVals[Multiple-1].getNode() == 0)
1040 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1041 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1042 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1043 return DAG.getTargetConstant(Val, MVT::i32);
1049 // Check to see if this buildvec has a single non-undef value in its elements.
1050 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1051 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1052 if (OpVal.getNode() == 0)
1053 OpVal = N->getOperand(i);
1054 else if (OpVal != N->getOperand(i))
1058 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
1060 unsigned ValSizeInBytes = EltSize;
1062 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1063 Value = CN->getZExtValue();
1064 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1065 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1066 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1069 // If the splat value is larger than the element value, then we can never do
1070 // this splat. The only case that we could fit the replicated bits into our
1071 // immediate field for would be zero, and we prefer to use vxor for it.
1072 if (ValSizeInBytes < ByteSize) return SDValue();
1074 // If the element value is larger than the splat value, cut it in half and
1075 // check to see if the two halves are equal. Continue doing this until we
1076 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1077 while (ValSizeInBytes > ByteSize) {
1078 ValSizeInBytes >>= 1;
1080 // If the top half equals the bottom half, we're still ok.
1081 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1082 (Value & ((1 << (8*ValSizeInBytes))-1)))
1086 // Properly sign extend the value.
1087 int MaskVal = SignExtend32(Value, ByteSize * 8);
1089 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1090 if (MaskVal == 0) return SDValue();
1092 // Finally, if this value fits in a 5 bit sext field, return it
1093 if (SignExtend32<5>(MaskVal) == MaskVal)
1094 return DAG.getTargetConstant(MaskVal, MVT::i32);
1098 //===----------------------------------------------------------------------===//
1099 // Addressing Mode Selection
1100 //===----------------------------------------------------------------------===//
1102 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1103 /// or 64-bit immediate, and if the value can be accurately represented as a
1104 /// sign extension from a 16-bit value. If so, this returns true and the
1106 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1107 if (N->getOpcode() != ISD::Constant)
1110 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1111 if (N->getValueType(0) == MVT::i32)
1112 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1114 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1116 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1117 return isIntS16Immediate(Op.getNode(), Imm);
1121 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1122 /// can be represented as an indexed [r+r] operation. Returns false if it
1123 /// can be more efficiently represented with [r+imm].
1124 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1126 SelectionDAG &DAG) const {
1128 if (N.getOpcode() == ISD::ADD) {
1129 if (isIntS16Immediate(N.getOperand(1), imm))
1130 return false; // r+i
1131 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1132 return false; // r+i
1134 Base = N.getOperand(0);
1135 Index = N.getOperand(1);
1137 } else if (N.getOpcode() == ISD::OR) {
1138 if (isIntS16Immediate(N.getOperand(1), imm))
1139 return false; // r+i can fold it if we can.
1141 // If this is an or of disjoint bitfields, we can codegen this as an add
1142 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1144 APInt LHSKnownZero, LHSKnownOne;
1145 APInt RHSKnownZero, RHSKnownOne;
1146 DAG.ComputeMaskedBits(N.getOperand(0),
1147 LHSKnownZero, LHSKnownOne);
1149 if (LHSKnownZero.getBoolValue()) {
1150 DAG.ComputeMaskedBits(N.getOperand(1),
1151 RHSKnownZero, RHSKnownOne);
1152 // If all of the bits are known zero on the LHS or RHS, the add won't
1154 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1155 Base = N.getOperand(0);
1156 Index = N.getOperand(1);
1165 // If we happen to be doing an i64 load or store into a stack slot that has
1166 // less than a 4-byte alignment, then the frame-index elimination may need to
1167 // use an indexed load or store instruction (because the offset may not be a
1168 // multiple of 4). The extra register needed to hold the offset comes from the
1169 // register scavenger, and it is possible that the scavenger will need to use
1170 // an emergency spill slot. As a result, we need to make sure that a spill slot
1171 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1173 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1174 // FIXME: This does not handle the LWA case.
1178 // NOTE: We'll exclude negative FIs here, which come from argument
1179 // lowering, because there are no known test cases triggering this problem
1180 // using packed structures (or similar). We can remove this exclusion if
1181 // we find such a test case. The reason why this is so test-case driven is
1182 // because this entire 'fixup' is only to prevent crashes (from the
1183 // register scavenger) on not-really-valid inputs. For example, if we have:
1185 // %b = bitcast i1* %a to i64*
1186 // store i64* a, i64 b
1187 // then the store should really be marked as 'align 1', but is not. If it
1188 // were marked as 'align 1' then the indexed form would have been
1189 // instruction-selected initially, and the problem this 'fixup' is preventing
1190 // won't happen regardless.
1194 MachineFunction &MF = DAG.getMachineFunction();
1195 MachineFrameInfo *MFI = MF.getFrameInfo();
1197 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1201 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1202 FuncInfo->setHasNonRISpills();
1205 /// Returns true if the address N can be represented by a base register plus
1206 /// a signed 16-bit displacement [r+imm], and if it is not better
1207 /// represented as reg+reg. If Aligned is true, only accept displacements
1208 /// suitable for STD and friends, i.e. multiples of 4.
1209 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1212 bool Aligned) const {
1213 // FIXME dl should come from parent load or store, not from address
1215 // If this can be more profitably realized as r+r, fail.
1216 if (SelectAddressRegReg(N, Disp, Base, DAG))
1219 if (N.getOpcode() == ISD::ADD) {
1221 if (isIntS16Immediate(N.getOperand(1), imm) &&
1222 (!Aligned || (imm & 3) == 0)) {
1223 Disp = DAG.getTargetConstant(imm, N.getValueType());
1224 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1225 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1226 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1228 Base = N.getOperand(0);
1230 return true; // [r+i]
1231 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1232 // Match LOAD (ADD (X, Lo(G))).
1233 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1234 && "Cannot handle constant offsets yet!");
1235 Disp = N.getOperand(1).getOperand(0); // The global address.
1236 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1237 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1238 Disp.getOpcode() == ISD::TargetConstantPool ||
1239 Disp.getOpcode() == ISD::TargetJumpTable);
1240 Base = N.getOperand(0);
1241 return true; // [&g+r]
1243 } else if (N.getOpcode() == ISD::OR) {
1245 if (isIntS16Immediate(N.getOperand(1), imm) &&
1246 (!Aligned || (imm & 3) == 0)) {
1247 // If this is an or of disjoint bitfields, we can codegen this as an add
1248 // (for better address arithmetic) if the LHS and RHS of the OR are
1249 // provably disjoint.
1250 APInt LHSKnownZero, LHSKnownOne;
1251 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1253 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1254 // If all of the bits are known zero on the LHS or RHS, the add won't
1256 Base = N.getOperand(0);
1257 Disp = DAG.getTargetConstant(imm, N.getValueType());
1261 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1262 // Loading from a constant address.
1264 // If this address fits entirely in a 16-bit sext immediate field, codegen
1267 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1268 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1269 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1270 CN->getValueType(0));
1274 // Handle 32-bit sext immediates with LIS + addr mode.
1275 if ((CN->getValueType(0) == MVT::i32 ||
1276 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1277 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1278 int Addr = (int)CN->getZExtValue();
1280 // Otherwise, break this down into an LIS + disp.
1281 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1283 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1284 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1285 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1290 Disp = DAG.getTargetConstant(0, getPointerTy());
1291 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1292 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1293 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1296 return true; // [r+0]
1299 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1300 /// represented as an indexed [r+r] operation.
1301 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1303 SelectionDAG &DAG) const {
1304 // Check to see if we can easily represent this as an [r+r] address. This
1305 // will fail if it thinks that the address is more profitably represented as
1306 // reg+imm, e.g. where imm = 0.
1307 if (SelectAddressRegReg(N, Base, Index, DAG))
1310 // If the operand is an addition, always emit this as [r+r], since this is
1311 // better (for code size, and execution, as the memop does the add for free)
1312 // than emitting an explicit add.
1313 if (N.getOpcode() == ISD::ADD) {
1314 Base = N.getOperand(0);
1315 Index = N.getOperand(1);
1319 // Otherwise, do it the hard way, using R0 as the base register.
1320 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1326 /// getPreIndexedAddressParts - returns true by value, base pointer and
1327 /// offset pointer and addressing mode by reference if the node's address
1328 /// can be legally represented as pre-indexed load / store address.
1329 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1331 ISD::MemIndexedMode &AM,
1332 SelectionDAG &DAG) const {
1333 if (DisablePPCPreinc) return false;
1339 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1340 Ptr = LD->getBasePtr();
1341 VT = LD->getMemoryVT();
1342 Alignment = LD->getAlignment();
1343 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1344 Ptr = ST->getBasePtr();
1345 VT = ST->getMemoryVT();
1346 Alignment = ST->getAlignment();
1351 // PowerPC doesn't have preinc load/store instructions for vectors.
1355 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1357 // Common code will reject creating a pre-inc form if the base pointer
1358 // is a frame index, or if N is a store and the base pointer is either
1359 // the same as or a predecessor of the value being stored. Check for
1360 // those situations here, and try with swapped Base/Offset instead.
1363 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1366 SDValue Val = cast<StoreSDNode>(N)->getValue();
1367 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1372 std::swap(Base, Offset);
1378 // LDU/STU can only handle immediates that are a multiple of 4.
1379 if (VT != MVT::i64) {
1380 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1383 // LDU/STU need an address with at least 4-byte alignment.
1387 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1391 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1392 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1393 // sext i32 to i64 when addr mode is r+i.
1394 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1395 LD->getExtensionType() == ISD::SEXTLOAD &&
1396 isa<ConstantSDNode>(Offset))
1404 //===----------------------------------------------------------------------===//
1405 // LowerOperation implementation
1406 //===----------------------------------------------------------------------===//
1408 /// GetLabelAccessInfo - Return true if we should reference labels using a
1409 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1410 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1411 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1412 HiOpFlags = PPCII::MO_HA;
1413 LoOpFlags = PPCII::MO_LO;
1415 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1416 // non-darwin platform. We don't support PIC on other platforms yet.
1417 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1418 TM.getSubtarget<PPCSubtarget>().isDarwin();
1420 HiOpFlags |= PPCII::MO_PIC_FLAG;
1421 LoOpFlags |= PPCII::MO_PIC_FLAG;
1424 // If this is a reference to a global value that requires a non-lazy-ptr, make
1425 // sure that instruction lowering adds it.
1426 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1427 HiOpFlags |= PPCII::MO_NLP_FLAG;
1428 LoOpFlags |= PPCII::MO_NLP_FLAG;
1430 if (GV->hasHiddenVisibility()) {
1431 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1432 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1439 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1440 SelectionDAG &DAG) {
1441 EVT PtrVT = HiPart.getValueType();
1442 SDValue Zero = DAG.getConstant(0, PtrVT);
1445 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1446 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1448 // With PIC, the first instruction is actually "GR+hi(&G)".
1450 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1451 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1453 // Generate non-pic code that has direct accesses to the constant pool.
1454 // The address of the global is just (hi(&g)+lo(&g)).
1455 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1458 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1459 SelectionDAG &DAG) const {
1460 EVT PtrVT = Op.getValueType();
1461 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1462 const Constant *C = CP->getConstVal();
1464 // 64-bit SVR4 ABI code is always position-independent.
1465 // The actual address of the GlobalValue is stored in the TOC.
1466 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1467 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1468 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1469 DAG.getRegister(PPC::X2, MVT::i64));
1472 unsigned MOHiFlag, MOLoFlag;
1473 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1475 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1477 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1478 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1481 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1482 EVT PtrVT = Op.getValueType();
1483 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1485 // 64-bit SVR4 ABI code is always position-independent.
1486 // The actual address of the GlobalValue is stored in the TOC.
1487 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1488 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1489 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1490 DAG.getRegister(PPC::X2, MVT::i64));
1493 unsigned MOHiFlag, MOLoFlag;
1494 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1495 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1496 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1497 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1500 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1501 SelectionDAG &DAG) const {
1502 EVT PtrVT = Op.getValueType();
1504 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1506 unsigned MOHiFlag, MOLoFlag;
1507 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1508 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1509 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1510 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1513 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1514 SelectionDAG &DAG) const {
1516 // FIXME: TLS addresses currently use medium model code sequences,
1517 // which is the most useful form. Eventually support for small and
1518 // large models could be added if users need it, at the cost of
1519 // additional complexity.
1520 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1522 const GlobalValue *GV = GA->getGlobal();
1523 EVT PtrVT = getPointerTy();
1524 bool is64bit = PPCSubTarget.isPPC64();
1526 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1528 if (Model == TLSModel::LocalExec) {
1529 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1530 PPCII::MO_TPREL_HA);
1531 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1532 PPCII::MO_TPREL_LO);
1533 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1534 is64bit ? MVT::i64 : MVT::i32);
1535 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1536 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1539 if (Model == TLSModel::InitialExec) {
1540 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1541 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1545 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1546 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1547 PtrVT, GOTReg, TGA);
1549 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1550 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1551 PtrVT, TGA, GOTPtr);
1552 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1555 if (Model == TLSModel::GeneralDynamic) {
1556 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1557 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1558 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1560 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1563 // We need a chain node, and don't have one handy. The underlying
1564 // call has no side effects, so using the function entry node
1566 SDValue Chain = DAG.getEntryNode();
1567 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1568 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1569 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1570 PtrVT, ParmReg, TGA);
1571 // The return value from GET_TLS_ADDR really is in X3 already, but
1572 // some hacks are needed here to tie everything together. The extra
1573 // copies dissolve during subsequent transforms.
1574 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1575 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1578 if (Model == TLSModel::LocalDynamic) {
1579 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1580 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1581 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1583 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1586 // We need a chain node, and don't have one handy. The underlying
1587 // call has no side effects, so using the function entry node
1589 SDValue Chain = DAG.getEntryNode();
1590 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1591 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1592 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1593 PtrVT, ParmReg, TGA);
1594 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1595 // some hacks are needed here to tie everything together. The extra
1596 // copies dissolve during subsequent transforms.
1597 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1598 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1599 Chain, ParmReg, TGA);
1600 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1603 llvm_unreachable("Unknown TLS model!");
1606 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1607 SelectionDAG &DAG) const {
1608 EVT PtrVT = Op.getValueType();
1609 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1611 const GlobalValue *GV = GSDN->getGlobal();
1613 // 64-bit SVR4 ABI code is always position-independent.
1614 // The actual address of the GlobalValue is stored in the TOC.
1615 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1616 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1617 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1618 DAG.getRegister(PPC::X2, MVT::i64));
1621 unsigned MOHiFlag, MOLoFlag;
1622 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1625 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1627 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1629 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1631 // If the global reference is actually to a non-lazy-pointer, we have to do an
1632 // extra load to get the address of the global.
1633 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1634 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1635 false, false, false, 0);
1639 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1640 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1643 // If we're comparing for equality to zero, expose the fact that this is
1644 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1645 // fold the new nodes.
1646 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1647 if (C->isNullValue() && CC == ISD::SETEQ) {
1648 EVT VT = Op.getOperand(0).getValueType();
1649 SDValue Zext = Op.getOperand(0);
1650 if (VT.bitsLT(MVT::i32)) {
1652 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1654 unsigned Log2b = Log2_32(VT.getSizeInBits());
1655 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1656 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1657 DAG.getConstant(Log2b, MVT::i32));
1658 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1660 // Leave comparisons against 0 and -1 alone for now, since they're usually
1661 // optimized. FIXME: revisit this when we can custom lower all setcc
1663 if (C->isAllOnesValue() || C->isNullValue())
1667 // If we have an integer seteq/setne, turn it into a compare against zero
1668 // by xor'ing the rhs with the lhs, which is faster than setting a
1669 // condition register, reading it back out, and masking the correct bit. The
1670 // normal approach here uses sub to do this instead of xor. Using xor exposes
1671 // the result to other bit-twiddling opportunities.
1672 EVT LHSVT = Op.getOperand(0).getValueType();
1673 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1674 EVT VT = Op.getValueType();
1675 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1677 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1682 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1683 const PPCSubtarget &Subtarget) const {
1684 SDNode *Node = Op.getNode();
1685 EVT VT = Node->getValueType(0);
1686 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1687 SDValue InChain = Node->getOperand(0);
1688 SDValue VAListPtr = Node->getOperand(1);
1689 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1692 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1695 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1696 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1698 InChain = GprIndex.getValue(1);
1700 if (VT == MVT::i64) {
1701 // Check if GprIndex is even
1702 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1703 DAG.getConstant(1, MVT::i32));
1704 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1705 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1706 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1707 DAG.getConstant(1, MVT::i32));
1708 // Align GprIndex to be even if it isn't
1709 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1713 // fpr index is 1 byte after gpr
1714 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1715 DAG.getConstant(1, MVT::i32));
1718 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1719 FprPtr, MachinePointerInfo(SV), MVT::i8,
1721 InChain = FprIndex.getValue(1);
1723 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1724 DAG.getConstant(8, MVT::i32));
1726 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1727 DAG.getConstant(4, MVT::i32));
1730 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1731 MachinePointerInfo(), false, false,
1733 InChain = OverflowArea.getValue(1);
1735 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1736 MachinePointerInfo(), false, false,
1738 InChain = RegSaveArea.getValue(1);
1740 // select overflow_area if index > 8
1741 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1742 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1744 // adjustment constant gpr_index * 4/8
1745 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1746 VT.isInteger() ? GprIndex : FprIndex,
1747 DAG.getConstant(VT.isInteger() ? 4 : 8,
1750 // OurReg = RegSaveArea + RegConstant
1751 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1754 // Floating types are 32 bytes into RegSaveArea
1755 if (VT.isFloatingPoint())
1756 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1757 DAG.getConstant(32, MVT::i32));
1759 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1760 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1761 VT.isInteger() ? GprIndex : FprIndex,
1762 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1765 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1766 VT.isInteger() ? VAListPtr : FprPtr,
1767 MachinePointerInfo(SV),
1768 MVT::i8, false, false, 0);
1770 // determine if we should load from reg_save_area or overflow_area
1771 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1773 // increase overflow_area by 4/8 if gpr/fpr > 8
1774 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1775 DAG.getConstant(VT.isInteger() ? 4 : 8,
1778 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1781 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1783 MachinePointerInfo(),
1784 MVT::i32, false, false, 0);
1786 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1787 false, false, false, 0);
1790 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1791 const PPCSubtarget &Subtarget) const {
1792 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1794 // We have to copy the entire va_list struct:
1795 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1796 return DAG.getMemcpy(Op.getOperand(0), Op,
1797 Op.getOperand(1), Op.getOperand(2),
1798 DAG.getConstant(12, MVT::i32), 8, false, true,
1799 MachinePointerInfo(), MachinePointerInfo());
1802 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1803 SelectionDAG &DAG) const {
1804 return Op.getOperand(0);
1807 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1808 SelectionDAG &DAG) const {
1809 SDValue Chain = Op.getOperand(0);
1810 SDValue Trmp = Op.getOperand(1); // trampoline
1811 SDValue FPtr = Op.getOperand(2); // nested function
1812 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1815 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1816 bool isPPC64 = (PtrVT == MVT::i64);
1818 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1821 TargetLowering::ArgListTy Args;
1822 TargetLowering::ArgListEntry Entry;
1824 Entry.Ty = IntPtrTy;
1825 Entry.Node = Trmp; Args.push_back(Entry);
1827 // TrampSize == (isPPC64 ? 48 : 40);
1828 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1829 isPPC64 ? MVT::i64 : MVT::i32);
1830 Args.push_back(Entry);
1832 Entry.Node = FPtr; Args.push_back(Entry);
1833 Entry.Node = Nest; Args.push_back(Entry);
1835 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1836 TargetLowering::CallLoweringInfo CLI(Chain,
1837 Type::getVoidTy(*DAG.getContext()),
1838 false, false, false, false, 0,
1840 /*isTailCall=*/false,
1841 /*doesNotRet=*/false,
1842 /*isReturnValueUsed=*/true,
1843 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1845 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1847 return CallResult.second;
1850 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1851 const PPCSubtarget &Subtarget) const {
1852 MachineFunction &MF = DAG.getMachineFunction();
1853 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1857 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1858 // vastart just stores the address of the VarArgsFrameIndex slot into the
1859 // memory location argument.
1860 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1861 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1862 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1863 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1864 MachinePointerInfo(SV),
1868 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1869 // We suppose the given va_list is already allocated.
1872 // char gpr; /* index into the array of 8 GPRs
1873 // * stored in the register save area
1874 // * gpr=0 corresponds to r3,
1875 // * gpr=1 to r4, etc.
1877 // char fpr; /* index into the array of 8 FPRs
1878 // * stored in the register save area
1879 // * fpr=0 corresponds to f1,
1880 // * fpr=1 to f2, etc.
1882 // char *overflow_arg_area;
1883 // /* location on stack that holds
1884 // * the next overflow argument
1886 // char *reg_save_area;
1887 // /* where r3:r10 and f1:f8 (if saved)
1893 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1894 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1897 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1899 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1901 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1904 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1905 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1907 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1908 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1910 uint64_t FPROffset = 1;
1911 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1913 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1915 // Store first byte : number of int regs
1916 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1918 MachinePointerInfo(SV),
1919 MVT::i8, false, false, 0);
1920 uint64_t nextOffset = FPROffset;
1921 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1924 // Store second byte : number of float regs
1925 SDValue secondStore =
1926 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1927 MachinePointerInfo(SV, nextOffset), MVT::i8,
1929 nextOffset += StackOffset;
1930 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1932 // Store second word : arguments given on stack
1933 SDValue thirdStore =
1934 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1935 MachinePointerInfo(SV, nextOffset),
1937 nextOffset += FrameOffset;
1938 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1940 // Store third word : arguments given in registers
1941 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1942 MachinePointerInfo(SV, nextOffset),
1947 #include "PPCGenCallingConv.inc"
1949 // Function whose sole purpose is to kill compiler warnings
1950 // stemming from unused functions included from PPCGenCallingConv.inc.
1951 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1952 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1955 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1956 CCValAssign::LocInfo &LocInfo,
1957 ISD::ArgFlagsTy &ArgFlags,
1962 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1964 CCValAssign::LocInfo &LocInfo,
1965 ISD::ArgFlagsTy &ArgFlags,
1967 static const uint16_t ArgRegs[] = {
1968 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1969 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1971 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1973 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1975 // Skip one register if the first unallocated register has an even register
1976 // number and there are still argument registers available which have not been
1977 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1978 // need to skip a register if RegNum is odd.
1979 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1980 State.AllocateReg(ArgRegs[RegNum]);
1983 // Always return false here, as this function only makes sure that the first
1984 // unallocated register has an odd register number and does not actually
1985 // allocate a register for the current argument.
1989 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1991 CCValAssign::LocInfo &LocInfo,
1992 ISD::ArgFlagsTy &ArgFlags,
1994 static const uint16_t ArgRegs[] = {
1995 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1999 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2001 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2003 // If there is only one Floating-point register left we need to put both f64
2004 // values of a split ppc_fp128 value on the stack.
2005 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2006 State.AllocateReg(ArgRegs[RegNum]);
2009 // Always return false here, as this function only makes sure that the two f64
2010 // values a ppc_fp128 value is split into are both passed in registers or both
2011 // passed on the stack and does not actually allocate a register for the
2012 // current argument.
2016 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2018 static const uint16_t *GetFPR() {
2019 static const uint16_t FPR[] = {
2020 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2021 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2027 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2029 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2030 unsigned PtrByteSize) {
2031 unsigned ArgSize = ArgVT.getStoreSize();
2032 if (Flags.isByVal())
2033 ArgSize = Flags.getByValSize();
2034 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2040 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2041 CallingConv::ID CallConv, bool isVarArg,
2042 const SmallVectorImpl<ISD::InputArg>
2044 SDLoc dl, SelectionDAG &DAG,
2045 SmallVectorImpl<SDValue> &InVals)
2047 if (PPCSubTarget.isSVR4ABI()) {
2048 if (PPCSubTarget.isPPC64())
2049 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2052 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2055 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2061 PPCTargetLowering::LowerFormalArguments_32SVR4(
2063 CallingConv::ID CallConv, bool isVarArg,
2064 const SmallVectorImpl<ISD::InputArg>
2066 SDLoc dl, SelectionDAG &DAG,
2067 SmallVectorImpl<SDValue> &InVals) const {
2069 // 32-bit SVR4 ABI Stack Frame Layout:
2070 // +-----------------------------------+
2071 // +--> | Back chain |
2072 // | +-----------------------------------+
2073 // | | Floating-point register save area |
2074 // | +-----------------------------------+
2075 // | | General register save area |
2076 // | +-----------------------------------+
2077 // | | CR save word |
2078 // | +-----------------------------------+
2079 // | | VRSAVE save word |
2080 // | +-----------------------------------+
2081 // | | Alignment padding |
2082 // | +-----------------------------------+
2083 // | | Vector register save area |
2084 // | +-----------------------------------+
2085 // | | Local variable space |
2086 // | +-----------------------------------+
2087 // | | Parameter list area |
2088 // | +-----------------------------------+
2089 // | | LR save word |
2090 // | +-----------------------------------+
2091 // SP--> +--- | Back chain |
2092 // +-----------------------------------+
2095 // System V Application Binary Interface PowerPC Processor Supplement
2096 // AltiVec Technology Programming Interface Manual
2098 MachineFunction &MF = DAG.getMachineFunction();
2099 MachineFrameInfo *MFI = MF.getFrameInfo();
2100 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2102 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2103 // Potential tail calls could cause overwriting of argument stack slots.
2104 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2105 (CallConv == CallingConv::Fast));
2106 unsigned PtrByteSize = 4;
2108 // Assign locations to all of the incoming arguments.
2109 SmallVector<CCValAssign, 16> ArgLocs;
2110 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2111 getTargetMachine(), ArgLocs, *DAG.getContext());
2113 // Reserve space for the linkage area on the stack.
2114 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2116 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2118 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2119 CCValAssign &VA = ArgLocs[i];
2121 // Arguments stored in registers.
2122 if (VA.isRegLoc()) {
2123 const TargetRegisterClass *RC;
2124 EVT ValVT = VA.getValVT();
2126 switch (ValVT.getSimpleVT().SimpleTy) {
2128 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2131 RC = &PPC::GPRCRegClass;
2134 RC = &PPC::F4RCRegClass;
2137 RC = &PPC::F8RCRegClass;
2145 RC = &PPC::VRRCRegClass;
2149 // Transform the arguments stored in physical registers into virtual ones.
2150 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2151 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2152 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2154 if (ValVT == MVT::i1)
2155 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2157 InVals.push_back(ArgValue);
2159 // Argument stored in memory.
2160 assert(VA.isMemLoc());
2162 unsigned ArgSize = VA.getLocVT().getStoreSize();
2163 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2166 // Create load nodes to retrieve arguments from the stack.
2167 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2168 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2169 MachinePointerInfo(),
2170 false, false, false, 0));
2174 // Assign locations to all of the incoming aggregate by value arguments.
2175 // Aggregates passed by value are stored in the local variable space of the
2176 // caller's stack frame, right above the parameter list area.
2177 SmallVector<CCValAssign, 16> ByValArgLocs;
2178 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2179 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2181 // Reserve stack space for the allocations in CCInfo.
2182 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2184 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2186 // Area that is at least reserved in the caller of this function.
2187 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2189 // Set the size that is at least reserved in caller of this function. Tail
2190 // call optimized function's reserved stack space needs to be aligned so that
2191 // taking the difference between two stack areas will result in an aligned
2193 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2196 std::max(MinReservedArea,
2197 PPCFrameLowering::getMinCallFrameSize(false, false));
2199 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2200 getStackAlignment();
2201 unsigned AlignMask = TargetAlign-1;
2202 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2204 FI->setMinReservedArea(MinReservedArea);
2206 SmallVector<SDValue, 8> MemOps;
2208 // If the function takes variable number of arguments, make a frame index for
2209 // the start of the first vararg value... for expansion of llvm.va_start.
2211 static const uint16_t GPArgRegs[] = {
2212 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2213 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2215 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2217 static const uint16_t FPArgRegs[] = {
2218 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2221 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2223 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2225 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2228 // Make room for NumGPArgRegs and NumFPArgRegs.
2229 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2230 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2232 FuncInfo->setVarArgsStackOffset(
2233 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2234 CCInfo.getNextStackOffset(), true));
2236 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2237 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2239 // The fixed integer arguments of a variadic function are stored to the
2240 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2241 // the result of va_next.
2242 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2243 // Get an existing live-in vreg, or add a new one.
2244 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2246 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2248 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2249 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2250 MachinePointerInfo(), false, false, 0);
2251 MemOps.push_back(Store);
2252 // Increment the address by four for the next argument to store
2253 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2254 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2257 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2259 // The double arguments are stored to the VarArgsFrameIndex
2261 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2262 // Get an existing live-in vreg, or add a new one.
2263 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2265 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2267 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2268 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2269 MachinePointerInfo(), false, false, 0);
2270 MemOps.push_back(Store);
2271 // Increment the address by eight for the next argument to store
2272 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2274 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2278 if (!MemOps.empty())
2279 Chain = DAG.getNode(ISD::TokenFactor, dl,
2280 MVT::Other, &MemOps[0], MemOps.size());
2285 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2286 // value to MVT::i64 and then truncate to the correct register size.
2288 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2289 SelectionDAG &DAG, SDValue ArgVal,
2292 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2293 DAG.getValueType(ObjectVT));
2294 else if (Flags.isZExt())
2295 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2296 DAG.getValueType(ObjectVT));
2298 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2301 // Set the size that is at least reserved in caller of this function. Tail
2302 // call optimized functions' reserved stack space needs to be aligned so that
2303 // taking the difference between two stack areas will result in an aligned
2306 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2307 unsigned nAltivecParamsAtEnd,
2308 unsigned MinReservedArea,
2309 bool isPPC64) const {
2310 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2311 // Add the Altivec parameters at the end, if needed.
2312 if (nAltivecParamsAtEnd) {
2313 MinReservedArea = ((MinReservedArea+15)/16)*16;
2314 MinReservedArea += 16*nAltivecParamsAtEnd;
2317 std::max(MinReservedArea,
2318 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2319 unsigned TargetAlign
2320 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2321 getStackAlignment();
2322 unsigned AlignMask = TargetAlign-1;
2323 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2324 FI->setMinReservedArea(MinReservedArea);
2328 PPCTargetLowering::LowerFormalArguments_64SVR4(
2330 CallingConv::ID CallConv, bool isVarArg,
2331 const SmallVectorImpl<ISD::InputArg>
2333 SDLoc dl, SelectionDAG &DAG,
2334 SmallVectorImpl<SDValue> &InVals) const {
2335 // TODO: add description of PPC stack frame format, or at least some docs.
2337 MachineFunction &MF = DAG.getMachineFunction();
2338 MachineFrameInfo *MFI = MF.getFrameInfo();
2339 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2341 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2342 // Potential tail calls could cause overwriting of argument stack slots.
2343 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2344 (CallConv == CallingConv::Fast));
2345 unsigned PtrByteSize = 8;
2347 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2348 // Area that is at least reserved in caller of this function.
2349 unsigned MinReservedArea = ArgOffset;
2351 static const uint16_t GPR[] = {
2352 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2353 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2356 static const uint16_t *FPR = GetFPR();
2358 static const uint16_t VR[] = {
2359 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2360 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2363 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2364 const unsigned Num_FPR_Regs = 13;
2365 const unsigned Num_VR_Regs = array_lengthof(VR);
2367 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2369 // Add DAG nodes to load the arguments or copy them out of registers. On
2370 // entry to a function on PPC, the arguments start after the linkage area,
2371 // although the first ones are often in registers.
2373 SmallVector<SDValue, 8> MemOps;
2374 unsigned nAltivecParamsAtEnd = 0;
2375 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2376 unsigned CurArgIdx = 0;
2377 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2379 bool needsLoad = false;
2380 EVT ObjectVT = Ins[ArgNo].VT;
2381 unsigned ObjSize = ObjectVT.getStoreSize();
2382 unsigned ArgSize = ObjSize;
2383 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2384 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2385 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2387 unsigned CurArgOffset = ArgOffset;
2389 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2390 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2391 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2392 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2394 MinReservedArea = ((MinReservedArea+15)/16)*16;
2395 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2399 nAltivecParamsAtEnd++;
2401 // Calculate min reserved area.
2402 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2406 // FIXME the codegen can be much improved in some cases.
2407 // We do not have to keep everything in memory.
2408 if (Flags.isByVal()) {
2409 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2410 ObjSize = Flags.getByValSize();
2411 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2412 // Empty aggregate parameters do not take up registers. Examples:
2416 // etc. However, we have to provide a place-holder in InVals, so
2417 // pretend we have an 8-byte item at the current address for that
2420 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2421 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2422 InVals.push_back(FIN);
2426 unsigned BVAlign = Flags.getByValAlign();
2428 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2429 CurArgOffset = ArgOffset;
2432 // All aggregates smaller than 8 bytes must be passed right-justified.
2433 if (ObjSize < PtrByteSize)
2434 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2435 // The value of the object is its address.
2436 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2437 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2438 InVals.push_back(FIN);
2441 if (GPR_idx != Num_GPR_Regs) {
2442 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2443 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2446 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2447 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2448 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2449 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2450 MachinePointerInfo(FuncArg),
2451 ObjType, false, false, 0);
2453 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2454 // store the whole register as-is to the parameter save area
2455 // slot. The address of the parameter was already calculated
2456 // above (InVals.push_back(FIN)) to be the right-justified
2457 // offset within the slot. For this store, we need a new
2458 // frame index that points at the beginning of the slot.
2459 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2460 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2461 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2462 MachinePointerInfo(FuncArg),
2466 MemOps.push_back(Store);
2469 // Whether we copied from a register or not, advance the offset
2470 // into the parameter save area by a full doubleword.
2471 ArgOffset += PtrByteSize;
2475 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2476 // Store whatever pieces of the object are in registers
2477 // to memory. ArgOffset will be the address of the beginning
2479 if (GPR_idx != Num_GPR_Regs) {
2481 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2482 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2483 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2484 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2485 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2486 MachinePointerInfo(FuncArg, j),
2488 MemOps.push_back(Store);
2490 ArgOffset += PtrByteSize;
2492 ArgOffset += ArgSize - j;
2499 switch (ObjectVT.getSimpleVT().SimpleTy) {
2500 default: llvm_unreachable("Unhandled argument type!");
2504 if (GPR_idx != Num_GPR_Regs) {
2505 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2506 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2508 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2509 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2510 // value to MVT::i64 and then truncate to the correct register size.
2511 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2516 ArgSize = PtrByteSize;
2523 // Every 8 bytes of argument space consumes one of the GPRs available for
2524 // argument passing.
2525 if (GPR_idx != Num_GPR_Regs) {
2528 if (FPR_idx != Num_FPR_Regs) {
2531 if (ObjectVT == MVT::f32)
2532 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2534 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2536 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2540 ArgSize = PtrByteSize;
2551 // Note that vector arguments in registers don't reserve stack space,
2552 // except in varargs functions.
2553 if (VR_idx != Num_VR_Regs) {
2554 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2555 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2557 while ((ArgOffset % 16) != 0) {
2558 ArgOffset += PtrByteSize;
2559 if (GPR_idx != Num_GPR_Regs)
2563 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2567 // Vectors are aligned.
2568 ArgOffset = ((ArgOffset+15)/16)*16;
2569 CurArgOffset = ArgOffset;
2576 // We need to load the argument to a virtual register if we determined
2577 // above that we ran out of physical registers of the appropriate type.
2579 int FI = MFI->CreateFixedObject(ObjSize,
2580 CurArgOffset + (ArgSize - ObjSize),
2582 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2583 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2584 false, false, false, 0);
2587 InVals.push_back(ArgVal);
2590 // Set the size that is at least reserved in caller of this function. Tail
2591 // call optimized functions' reserved stack space needs to be aligned so that
2592 // taking the difference between two stack areas will result in an aligned
2594 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2596 // If the function takes variable number of arguments, make a frame index for
2597 // the start of the first vararg value... for expansion of llvm.va_start.
2599 int Depth = ArgOffset;
2601 FuncInfo->setVarArgsFrameIndex(
2602 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2603 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2605 // If this function is vararg, store any remaining integer argument regs
2606 // to their spots on the stack so that they may be loaded by deferencing the
2607 // result of va_next.
2608 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2609 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2610 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2611 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2612 MachinePointerInfo(), false, false, 0);
2613 MemOps.push_back(Store);
2614 // Increment the address by four for the next argument to store
2615 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2616 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2620 if (!MemOps.empty())
2621 Chain = DAG.getNode(ISD::TokenFactor, dl,
2622 MVT::Other, &MemOps[0], MemOps.size());
2628 PPCTargetLowering::LowerFormalArguments_Darwin(
2630 CallingConv::ID CallConv, bool isVarArg,
2631 const SmallVectorImpl<ISD::InputArg>
2633 SDLoc dl, SelectionDAG &DAG,
2634 SmallVectorImpl<SDValue> &InVals) const {
2635 // TODO: add description of PPC stack frame format, or at least some docs.
2637 MachineFunction &MF = DAG.getMachineFunction();
2638 MachineFrameInfo *MFI = MF.getFrameInfo();
2639 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2641 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2642 bool isPPC64 = PtrVT == MVT::i64;
2643 // Potential tail calls could cause overwriting of argument stack slots.
2644 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2645 (CallConv == CallingConv::Fast));
2646 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2648 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2649 // Area that is at least reserved in caller of this function.
2650 unsigned MinReservedArea = ArgOffset;
2652 static const uint16_t GPR_32[] = { // 32-bit registers.
2653 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2654 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2656 static const uint16_t GPR_64[] = { // 64-bit registers.
2657 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2658 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2661 static const uint16_t *FPR = GetFPR();
2663 static const uint16_t VR[] = {
2664 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2665 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2668 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2669 const unsigned Num_FPR_Regs = 13;
2670 const unsigned Num_VR_Regs = array_lengthof( VR);
2672 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2674 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2676 // In 32-bit non-varargs functions, the stack space for vectors is after the
2677 // stack space for non-vectors. We do not use this space unless we have
2678 // too many vectors to fit in registers, something that only occurs in
2679 // constructed examples:), but we have to walk the arglist to figure
2680 // that out...for the pathological case, compute VecArgOffset as the
2681 // start of the vector parameter area. Computing VecArgOffset is the
2682 // entire point of the following loop.
2683 unsigned VecArgOffset = ArgOffset;
2684 if (!isVarArg && !isPPC64) {
2685 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2687 EVT ObjectVT = Ins[ArgNo].VT;
2688 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2690 if (Flags.isByVal()) {
2691 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2692 unsigned ObjSize = Flags.getByValSize();
2694 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2695 VecArgOffset += ArgSize;
2699 switch(ObjectVT.getSimpleVT().SimpleTy) {
2700 default: llvm_unreachable("Unhandled argument type!");
2706 case MVT::i64: // PPC64
2708 // FIXME: We are guaranteed to be !isPPC64 at this point.
2709 // Does MVT::i64 apply?
2716 // Nothing to do, we're only looking at Nonvector args here.
2721 // We've found where the vector parameter area in memory is. Skip the
2722 // first 12 parameters; these don't use that memory.
2723 VecArgOffset = ((VecArgOffset+15)/16)*16;
2724 VecArgOffset += 12*16;
2726 // Add DAG nodes to load the arguments or copy them out of registers. On
2727 // entry to a function on PPC, the arguments start after the linkage area,
2728 // although the first ones are often in registers.
2730 SmallVector<SDValue, 8> MemOps;
2731 unsigned nAltivecParamsAtEnd = 0;
2732 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2733 unsigned CurArgIdx = 0;
2734 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2736 bool needsLoad = false;
2737 EVT ObjectVT = Ins[ArgNo].VT;
2738 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2739 unsigned ArgSize = ObjSize;
2740 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2741 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2742 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2744 unsigned CurArgOffset = ArgOffset;
2746 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2747 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2748 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2749 if (isVarArg || isPPC64) {
2750 MinReservedArea = ((MinReservedArea+15)/16)*16;
2751 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2754 } else nAltivecParamsAtEnd++;
2756 // Calculate min reserved area.
2757 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2761 // FIXME the codegen can be much improved in some cases.
2762 // We do not have to keep everything in memory.
2763 if (Flags.isByVal()) {
2764 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2765 ObjSize = Flags.getByValSize();
2766 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2767 // Objects of size 1 and 2 are right justified, everything else is
2768 // left justified. This means the memory address is adjusted forwards.
2769 if (ObjSize==1 || ObjSize==2) {
2770 CurArgOffset = CurArgOffset + (4 - ObjSize);
2772 // The value of the object is its address.
2773 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2774 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2775 InVals.push_back(FIN);
2776 if (ObjSize==1 || ObjSize==2) {
2777 if (GPR_idx != Num_GPR_Regs) {
2780 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2782 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2783 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2784 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2785 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2786 MachinePointerInfo(FuncArg),
2787 ObjType, false, false, 0);
2788 MemOps.push_back(Store);
2792 ArgOffset += PtrByteSize;
2796 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2797 // Store whatever pieces of the object are in registers
2798 // to memory. ArgOffset will be the address of the beginning
2800 if (GPR_idx != Num_GPR_Regs) {
2803 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2805 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2806 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2807 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2808 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2809 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2810 MachinePointerInfo(FuncArg, j),
2812 MemOps.push_back(Store);
2814 ArgOffset += PtrByteSize;
2816 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2823 switch (ObjectVT.getSimpleVT().SimpleTy) {
2824 default: llvm_unreachable("Unhandled argument type!");
2828 if (GPR_idx != Num_GPR_Regs) {
2829 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2830 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2832 if (ObjectVT == MVT::i1)
2833 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2838 ArgSize = PtrByteSize;
2840 // All int arguments reserve stack space in the Darwin ABI.
2841 ArgOffset += PtrByteSize;
2845 case MVT::i64: // PPC64
2846 if (GPR_idx != Num_GPR_Regs) {
2847 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2848 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2850 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2851 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2852 // value to MVT::i64 and then truncate to the correct register size.
2853 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2858 ArgSize = PtrByteSize;
2860 // All int arguments reserve stack space in the Darwin ABI.
2866 // Every 4 bytes of argument space consumes one of the GPRs available for
2867 // argument passing.
2868 if (GPR_idx != Num_GPR_Regs) {
2870 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2873 if (FPR_idx != Num_FPR_Regs) {
2876 if (ObjectVT == MVT::f32)
2877 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2879 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2881 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2887 // All FP arguments reserve stack space in the Darwin ABI.
2888 ArgOffset += isPPC64 ? 8 : ObjSize;
2894 // Note that vector arguments in registers don't reserve stack space,
2895 // except in varargs functions.
2896 if (VR_idx != Num_VR_Regs) {
2897 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2898 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2900 while ((ArgOffset % 16) != 0) {
2901 ArgOffset += PtrByteSize;
2902 if (GPR_idx != Num_GPR_Regs)
2906 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2910 if (!isVarArg && !isPPC64) {
2911 // Vectors go after all the nonvectors.
2912 CurArgOffset = VecArgOffset;
2915 // Vectors are aligned.
2916 ArgOffset = ((ArgOffset+15)/16)*16;
2917 CurArgOffset = ArgOffset;
2925 // We need to load the argument to a virtual register if we determined above
2926 // that we ran out of physical registers of the appropriate type.
2928 int FI = MFI->CreateFixedObject(ObjSize,
2929 CurArgOffset + (ArgSize - ObjSize),
2931 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2932 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2933 false, false, false, 0);
2936 InVals.push_back(ArgVal);
2939 // Set the size that is at least reserved in caller of this function. Tail
2940 // call optimized functions' reserved stack space needs to be aligned so that
2941 // taking the difference between two stack areas will result in an aligned
2943 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2945 // If the function takes variable number of arguments, make a frame index for
2946 // the start of the first vararg value... for expansion of llvm.va_start.
2948 int Depth = ArgOffset;
2950 FuncInfo->setVarArgsFrameIndex(
2951 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2953 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2955 // If this function is vararg, store any remaining integer argument regs
2956 // to their spots on the stack so that they may be loaded by deferencing the
2957 // result of va_next.
2958 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2962 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2964 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2966 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2967 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2968 MachinePointerInfo(), false, false, 0);
2969 MemOps.push_back(Store);
2970 // Increment the address by four for the next argument to store
2971 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2972 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2976 if (!MemOps.empty())
2977 Chain = DAG.getNode(ISD::TokenFactor, dl,
2978 MVT::Other, &MemOps[0], MemOps.size());
2983 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2984 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2986 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2990 const SmallVectorImpl<ISD::OutputArg>
2992 const SmallVectorImpl<SDValue> &OutVals,
2993 unsigned &nAltivecParamsAtEnd) {
2994 // Count how many bytes are to be pushed on the stack, including the linkage
2995 // area, and parameter passing area. We start with 24/48 bytes, which is
2996 // prereserved space for [SP][CR][LR][3 x unused].
2997 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2998 unsigned NumOps = Outs.size();
2999 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3001 // Add up all the space actually used.
3002 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3003 // they all go in registers, but we must reserve stack space for them for
3004 // possible use by the caller. In varargs or 64-bit calls, parameters are
3005 // assigned stack space in order, with padding so Altivec parameters are
3007 nAltivecParamsAtEnd = 0;
3008 for (unsigned i = 0; i != NumOps; ++i) {
3009 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3010 EVT ArgVT = Outs[i].VT;
3011 // Varargs Altivec parameters are padded to a 16 byte boundary.
3012 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3013 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3014 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3015 if (!isVarArg && !isPPC64) {
3016 // Non-varargs Altivec parameters go after all the non-Altivec
3017 // parameters; handle those later so we know how much padding we need.
3018 nAltivecParamsAtEnd++;
3021 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3022 NumBytes = ((NumBytes+15)/16)*16;
3024 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3027 // Allow for Altivec parameters at the end, if needed.
3028 if (nAltivecParamsAtEnd) {
3029 NumBytes = ((NumBytes+15)/16)*16;
3030 NumBytes += 16*nAltivecParamsAtEnd;
3033 // The prolog code of the callee may store up to 8 GPR argument registers to
3034 // the stack, allowing va_start to index over them in memory if its varargs.
3035 // Because we cannot tell if this is needed on the caller side, we have to
3036 // conservatively assume that it is needed. As such, make sure we have at
3037 // least enough stack space for the caller to store the 8 GPRs.
3038 NumBytes = std::max(NumBytes,
3039 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3041 // Tail call needs the stack to be aligned.
3042 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3043 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3044 getFrameLowering()->getStackAlignment();
3045 unsigned AlignMask = TargetAlign-1;
3046 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3052 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3053 /// adjusted to accommodate the arguments for the tailcall.
3054 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3055 unsigned ParamSize) {
3057 if (!isTailCall) return 0;
3059 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3060 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3061 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3062 // Remember only if the new adjustement is bigger.
3063 if (SPDiff < FI->getTailCallSPDelta())
3064 FI->setTailCallSPDelta(SPDiff);
3069 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3070 /// for tail call optimization. Targets which want to do tail call
3071 /// optimization should implement this function.
3073 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3074 CallingConv::ID CalleeCC,
3076 const SmallVectorImpl<ISD::InputArg> &Ins,
3077 SelectionDAG& DAG) const {
3078 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3081 // Variable argument functions are not supported.
3085 MachineFunction &MF = DAG.getMachineFunction();
3086 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3087 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3088 // Functions containing by val parameters are not supported.
3089 for (unsigned i = 0; i != Ins.size(); i++) {
3090 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3091 if (Flags.isByVal()) return false;
3094 // Non-PIC/GOT tail calls are supported.
3095 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3098 // At the moment we can only do local tail calls (in same module, hidden
3099 // or protected) if we are generating PIC.
3100 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3101 return G->getGlobal()->hasHiddenVisibility()
3102 || G->getGlobal()->hasProtectedVisibility();
3108 /// isCallCompatibleAddress - Return the immediate to use if the specified
3109 /// 32-bit value is representable in the immediate field of a BxA instruction.
3110 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3114 int Addr = C->getZExtValue();
3115 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3116 SignExtend32<26>(Addr) != Addr)
3117 return 0; // Top 6 bits have to be sext of immediate.
3119 return DAG.getConstant((int)C->getZExtValue() >> 2,
3120 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3125 struct TailCallArgumentInfo {
3130 TailCallArgumentInfo() : FrameIdx(0) {}
3135 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3137 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3139 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3140 SmallVectorImpl<SDValue> &MemOpChains,
3142 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3143 SDValue Arg = TailCallArgs[i].Arg;
3144 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3145 int FI = TailCallArgs[i].FrameIdx;
3146 // Store relative to framepointer.
3147 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3148 MachinePointerInfo::getFixedStack(FI),
3153 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3154 /// the appropriate stack slot for the tail call optimized function call.
3155 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3156 MachineFunction &MF,
3165 // Calculate the new stack slot for the return address.
3166 int SlotSize = isPPC64 ? 8 : 4;
3167 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3169 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3170 NewRetAddrLoc, true);
3171 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3172 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3173 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3174 MachinePointerInfo::getFixedStack(NewRetAddr),
3177 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3178 // slot as the FP is never overwritten.
3181 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3182 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3184 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3185 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3186 MachinePointerInfo::getFixedStack(NewFPIdx),
3193 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3194 /// the position of the argument.
3196 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3197 SDValue Arg, int SPDiff, unsigned ArgOffset,
3198 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3199 int Offset = ArgOffset + SPDiff;
3200 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3201 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3202 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3203 SDValue FIN = DAG.getFrameIndex(FI, VT);
3204 TailCallArgumentInfo Info;
3206 Info.FrameIdxOp = FIN;
3208 TailCallArguments.push_back(Info);
3211 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3212 /// stack slot. Returns the chain as result and the loaded frame pointers in
3213 /// LROpOut/FPOpout. Used when tail calling.
3214 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3222 // Load the LR and FP stack slot for later adjusting.
3223 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3224 LROpOut = getReturnAddrFrameIndex(DAG);
3225 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3226 false, false, false, 0);
3227 Chain = SDValue(LROpOut.getNode(), 1);
3229 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3230 // slot as the FP is never overwritten.
3232 FPOpOut = getFramePointerFrameIndex(DAG);
3233 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3234 false, false, false, 0);
3235 Chain = SDValue(FPOpOut.getNode(), 1);
3241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3242 /// by "Src" to address "Dst" of size "Size". Alignment information is
3243 /// specified by the specific parameter attribute. The copy will be passed as
3244 /// a byval function parameter.
3245 /// Sometimes what we are copying is the end of a larger object, the part that
3246 /// does not fit in registers.
3248 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3249 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3251 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3252 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3253 false, false, MachinePointerInfo(0),
3254 MachinePointerInfo(0));
3257 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3260 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3261 SDValue Arg, SDValue PtrOff, int SPDiff,
3262 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3263 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3264 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3266 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3271 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3273 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3274 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3275 DAG.getConstant(ArgOffset, PtrVT));
3277 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3278 MachinePointerInfo(), false, false, 0));
3279 // Calculate and remember argument location.
3280 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3285 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3286 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3287 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3288 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3289 MachineFunction &MF = DAG.getMachineFunction();
3291 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3292 // might overwrite each other in case of tail call optimization.
3293 SmallVector<SDValue, 8> MemOpChains2;
3294 // Do not flag preceding copytoreg stuff together with the following stuff.
3296 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3298 if (!MemOpChains2.empty())
3299 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3300 &MemOpChains2[0], MemOpChains2.size());
3302 // Store the return address to the appropriate stack slot.
3303 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3304 isPPC64, isDarwinABI, dl);
3306 // Emit callseq_end just before tailcall node.
3307 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3308 DAG.getIntPtrConstant(0, true), InFlag, dl);
3309 InFlag = Chain.getValue(1);
3313 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3314 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3315 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3316 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3317 const PPCSubtarget &PPCSubTarget) {
3319 bool isPPC64 = PPCSubTarget.isPPC64();
3320 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3322 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3323 NodeTys.push_back(MVT::Other); // Returns a chain
3324 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3326 unsigned CallOpc = PPCISD::CALL;
3328 bool needIndirectCall = true;
3329 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3330 // If this is an absolute destination address, use the munged value.
3331 Callee = SDValue(Dest, 0);
3332 needIndirectCall = false;
3335 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3336 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3337 // Use indirect calls for ALL functions calls in JIT mode, since the
3338 // far-call stubs may be outside relocation limits for a BL instruction.
3339 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3340 unsigned OpFlags = 0;
3341 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3342 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3343 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3344 (G->getGlobal()->isDeclaration() ||
3345 G->getGlobal()->isWeakForLinker())) {
3346 // PC-relative references to external symbols should go through $stub,
3347 // unless we're building with the leopard linker or later, which
3348 // automatically synthesizes these stubs.
3349 OpFlags = PPCII::MO_DARWIN_STUB;
3352 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3353 // every direct call is) turn it into a TargetGlobalAddress /
3354 // TargetExternalSymbol node so that legalize doesn't hack it.
3355 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3356 Callee.getValueType(),
3358 needIndirectCall = false;
3362 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3363 unsigned char OpFlags = 0;
3365 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3366 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3367 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3368 // PC-relative references to external symbols should go through $stub,
3369 // unless we're building with the leopard linker or later, which
3370 // automatically synthesizes these stubs.
3371 OpFlags = PPCII::MO_DARWIN_STUB;
3374 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3376 needIndirectCall = false;
3379 if (needIndirectCall) {
3380 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3381 // to do the call, we can't use PPCISD::CALL.
3382 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3384 if (isSVR4ABI && isPPC64) {
3385 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3386 // entry point, but to the function descriptor (the function entry point
3387 // address is part of the function descriptor though).
3388 // The function descriptor is a three doubleword structure with the
3389 // following fields: function entry point, TOC base address and
3390 // environment pointer.
3391 // Thus for a call through a function pointer, the following actions need
3393 // 1. Save the TOC of the caller in the TOC save area of its stack
3394 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3395 // 2. Load the address of the function entry point from the function
3397 // 3. Load the TOC of the callee from the function descriptor into r2.
3398 // 4. Load the environment pointer from the function descriptor into
3400 // 5. Branch to the function entry point address.
3401 // 6. On return of the callee, the TOC of the caller needs to be
3402 // restored (this is done in FinishCall()).
3404 // All those operations are flagged together to ensure that no other
3405 // operations can be scheduled in between. E.g. without flagging the
3406 // operations together, a TOC access in the caller could be scheduled
3407 // between the load of the callee TOC and the branch to the callee, which
3408 // results in the TOC access going through the TOC of the callee instead
3409 // of going through the TOC of the caller, which leads to incorrect code.
3411 // Load the address of the function entry point from the function
3413 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3414 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3415 InFlag.getNode() ? 3 : 2);
3416 Chain = LoadFuncPtr.getValue(1);
3417 InFlag = LoadFuncPtr.getValue(2);
3419 // Load environment pointer into r11.
3420 // Offset of the environment pointer within the function descriptor.
3421 SDValue PtrOff = DAG.getIntPtrConstant(16);
3423 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3424 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3426 Chain = LoadEnvPtr.getValue(1);
3427 InFlag = LoadEnvPtr.getValue(2);
3429 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3431 Chain = EnvVal.getValue(0);
3432 InFlag = EnvVal.getValue(1);
3434 // Load TOC of the callee into r2. We are using a target-specific load
3435 // with r2 hard coded, because the result of a target-independent load
3436 // would never go directly into r2, since r2 is a reserved register (which
3437 // prevents the register allocator from allocating it), resulting in an
3438 // additional register being allocated and an unnecessary move instruction
3440 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3441 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3443 Chain = LoadTOCPtr.getValue(0);
3444 InFlag = LoadTOCPtr.getValue(1);
3446 MTCTROps[0] = Chain;
3447 MTCTROps[1] = LoadFuncPtr;
3448 MTCTROps[2] = InFlag;
3451 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3452 2 + (InFlag.getNode() != 0));
3453 InFlag = Chain.getValue(1);
3456 NodeTys.push_back(MVT::Other);
3457 NodeTys.push_back(MVT::Glue);
3458 Ops.push_back(Chain);
3459 CallOpc = PPCISD::BCTRL;
3461 // Add use of X11 (holding environment pointer)
3462 if (isSVR4ABI && isPPC64)
3463 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3464 // Add CTR register as callee so a bctr can be emitted later.
3466 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3469 // If this is a direct call, pass the chain and the callee.
3470 if (Callee.getNode()) {
3471 Ops.push_back(Chain);
3472 Ops.push_back(Callee);
3474 // If this is a tail call add stack pointer delta.
3476 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3478 // Add argument registers to the end of the list so that they are known live
3480 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3481 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3482 RegsToPass[i].second.getValueType()));
3488 bool isLocalCall(const SDValue &Callee)
3490 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3491 return !G->getGlobal()->isDeclaration() &&
3492 !G->getGlobal()->isWeakForLinker();
3497 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3498 CallingConv::ID CallConv, bool isVarArg,
3499 const SmallVectorImpl<ISD::InputArg> &Ins,
3500 SDLoc dl, SelectionDAG &DAG,
3501 SmallVectorImpl<SDValue> &InVals) const {
3503 SmallVector<CCValAssign, 16> RVLocs;
3504 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3505 getTargetMachine(), RVLocs, *DAG.getContext());
3506 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3508 // Copy all of the result registers out of their specified physreg.
3509 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3510 CCValAssign &VA = RVLocs[i];
3511 assert(VA.isRegLoc() && "Can only return in registers!");
3513 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3514 VA.getLocReg(), VA.getLocVT(), InFlag);
3515 Chain = Val.getValue(1);
3516 InFlag = Val.getValue(2);
3518 switch (VA.getLocInfo()) {
3519 default: llvm_unreachable("Unknown loc info!");
3520 case CCValAssign::Full: break;
3521 case CCValAssign::AExt:
3522 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3524 case CCValAssign::ZExt:
3525 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3526 DAG.getValueType(VA.getValVT()));
3527 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3529 case CCValAssign::SExt:
3530 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3531 DAG.getValueType(VA.getValVT()));
3532 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3536 InVals.push_back(Val);
3543 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3544 bool isTailCall, bool isVarArg,
3546 SmallVector<std::pair<unsigned, SDValue>, 8>
3548 SDValue InFlag, SDValue Chain,
3550 int SPDiff, unsigned NumBytes,
3551 const SmallVectorImpl<ISD::InputArg> &Ins,
3552 SmallVectorImpl<SDValue> &InVals) const {
3553 std::vector<EVT> NodeTys;
3554 SmallVector<SDValue, 8> Ops;
3555 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3556 isTailCall, RegsToPass, Ops, NodeTys,
3559 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3560 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3561 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3563 // When performing tail call optimization the callee pops its arguments off
3564 // the stack. Account for this here so these bytes can be pushed back on in
3565 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3566 int BytesCalleePops =
3567 (CallConv == CallingConv::Fast &&
3568 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3570 // Add a register mask operand representing the call-preserved registers.
3571 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3572 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3573 assert(Mask && "Missing call preserved mask for calling convention");
3574 Ops.push_back(DAG.getRegisterMask(Mask));
3576 if (InFlag.getNode())
3577 Ops.push_back(InFlag);
3581 assert(((Callee.getOpcode() == ISD::Register &&
3582 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3583 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3584 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3585 isa<ConstantSDNode>(Callee)) &&
3586 "Expecting an global address, external symbol, absolute value or register");
3588 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3591 // Add a NOP immediately after the branch instruction when using the 64-bit
3592 // SVR4 ABI. At link time, if caller and callee are in a different module and
3593 // thus have a different TOC, the call will be replaced with a call to a stub
3594 // function which saves the current TOC, loads the TOC of the callee and
3595 // branches to the callee. The NOP will be replaced with a load instruction
3596 // which restores the TOC of the caller from the TOC save slot of the current
3597 // stack frame. If caller and callee belong to the same module (and have the
3598 // same TOC), the NOP will remain unchanged.
3600 bool needsTOCRestore = false;
3601 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3602 if (CallOpc == PPCISD::BCTRL) {
3603 // This is a call through a function pointer.
3604 // Restore the caller TOC from the save area into R2.
3605 // See PrepareCall() for more information about calls through function
3606 // pointers in the 64-bit SVR4 ABI.
3607 // We are using a target-specific load with r2 hard coded, because the
3608 // result of a target-independent load would never go directly into r2,
3609 // since r2 is a reserved register (which prevents the register allocator
3610 // from allocating it), resulting in an additional register being
3611 // allocated and an unnecessary move instruction being generated.
3612 needsTOCRestore = true;
3613 } else if ((CallOpc == PPCISD::CALL) &&
3614 (!isLocalCall(Callee) ||
3615 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3616 // Otherwise insert NOP for non-local calls.
3617 CallOpc = PPCISD::CALL_NOP;
3621 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3622 InFlag = Chain.getValue(1);
3624 if (needsTOCRestore) {
3625 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3626 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3627 InFlag = Chain.getValue(1);
3630 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3631 DAG.getIntPtrConstant(BytesCalleePops, true),
3634 InFlag = Chain.getValue(1);
3636 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3637 Ins, dl, DAG, InVals);
3641 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3642 SmallVectorImpl<SDValue> &InVals) const {
3643 SelectionDAG &DAG = CLI.DAG;
3645 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3646 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3647 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3648 SDValue Chain = CLI.Chain;
3649 SDValue Callee = CLI.Callee;
3650 bool &isTailCall = CLI.IsTailCall;
3651 CallingConv::ID CallConv = CLI.CallConv;
3652 bool isVarArg = CLI.IsVarArg;
3655 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3658 if (PPCSubTarget.isSVR4ABI()) {
3659 if (PPCSubTarget.isPPC64())
3660 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3661 isTailCall, Outs, OutVals, Ins,
3664 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3665 isTailCall, Outs, OutVals, Ins,
3669 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3670 isTailCall, Outs, OutVals, Ins,
3675 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3676 CallingConv::ID CallConv, bool isVarArg,
3678 const SmallVectorImpl<ISD::OutputArg> &Outs,
3679 const SmallVectorImpl<SDValue> &OutVals,
3680 const SmallVectorImpl<ISD::InputArg> &Ins,
3681 SDLoc dl, SelectionDAG &DAG,
3682 SmallVectorImpl<SDValue> &InVals) const {
3683 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3684 // of the 32-bit SVR4 ABI stack frame layout.
3686 assert((CallConv == CallingConv::C ||
3687 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3689 unsigned PtrByteSize = 4;
3691 MachineFunction &MF = DAG.getMachineFunction();
3693 // Mark this function as potentially containing a function that contains a
3694 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3695 // and restoring the callers stack pointer in this functions epilog. This is
3696 // done because by tail calling the called function might overwrite the value
3697 // in this function's (MF) stack pointer stack slot 0(SP).
3698 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3699 CallConv == CallingConv::Fast)
3700 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3702 // Count how many bytes are to be pushed on the stack, including the linkage
3703 // area, parameter list area and the part of the local variable space which
3704 // contains copies of aggregates which are passed by value.
3706 // Assign locations to all of the outgoing arguments.
3707 SmallVector<CCValAssign, 16> ArgLocs;
3708 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3709 getTargetMachine(), ArgLocs, *DAG.getContext());
3711 // Reserve space for the linkage area on the stack.
3712 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3715 // Handle fixed and variable vector arguments differently.
3716 // Fixed vector arguments go into registers as long as registers are
3717 // available. Variable vector arguments always go into memory.
3718 unsigned NumArgs = Outs.size();
3720 for (unsigned i = 0; i != NumArgs; ++i) {
3721 MVT ArgVT = Outs[i].VT;
3722 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3725 if (Outs[i].IsFixed) {
3726 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3729 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3735 errs() << "Call operand #" << i << " has unhandled type "
3736 << EVT(ArgVT).getEVTString() << "\n";
3738 llvm_unreachable(0);
3742 // All arguments are treated the same.
3743 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3746 // Assign locations to all of the outgoing aggregate by value arguments.
3747 SmallVector<CCValAssign, 16> ByValArgLocs;
3748 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3749 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3751 // Reserve stack space for the allocations in CCInfo.
3752 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3754 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3756 // Size of the linkage area, parameter list area and the part of the local
3757 // space variable where copies of aggregates which are passed by value are
3759 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3761 // Calculate by how many bytes the stack has to be adjusted in case of tail
3762 // call optimization.
3763 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3765 // Adjust the stack pointer for the new arguments...
3766 // These operations are automatically eliminated by the prolog/epilog pass
3767 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3769 SDValue CallSeqStart = Chain;
3771 // Load the return address and frame pointer so it can be moved somewhere else
3774 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3777 // Set up a copy of the stack pointer for use loading and storing any
3778 // arguments that may not fit in the registers available for argument
3780 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3782 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3783 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3784 SmallVector<SDValue, 8> MemOpChains;
3786 bool seenFloatArg = false;
3787 // Walk the register/memloc assignments, inserting copies/loads.
3788 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3791 CCValAssign &VA = ArgLocs[i];
3792 SDValue Arg = OutVals[i];
3793 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3795 if (Flags.isByVal()) {
3796 // Argument is an aggregate which is passed by value, thus we need to
3797 // create a copy of it in the local variable space of the current stack
3798 // frame (which is the stack frame of the caller) and pass the address of
3799 // this copy to the callee.
3800 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3801 CCValAssign &ByValVA = ByValArgLocs[j++];
3802 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3804 // Memory reserved in the local variable space of the callers stack frame.
3805 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3807 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3808 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3810 // Create a copy of the argument in the local area of the current
3812 SDValue MemcpyCall =
3813 CreateCopyOfByValArgument(Arg, PtrOff,
3814 CallSeqStart.getNode()->getOperand(0),
3817 // This must go outside the CALLSEQ_START..END.
3818 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3819 CallSeqStart.getNode()->getOperand(1),
3821 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3822 NewCallSeqStart.getNode());
3823 Chain = CallSeqStart = NewCallSeqStart;
3825 // Pass the address of the aggregate copy on the stack either in a
3826 // physical register or in the parameter list area of the current stack
3827 // frame to the callee.
3831 if (VA.isRegLoc()) {
3832 if (Arg.getValueType() == MVT::i1)
3833 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3835 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3836 // Put argument in a physical register.
3837 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3839 // Put argument in the parameter list area of the current stack frame.
3840 assert(VA.isMemLoc());
3841 unsigned LocMemOffset = VA.getLocMemOffset();
3844 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3845 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3847 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3848 MachinePointerInfo(),
3851 // Calculate and remember argument location.
3852 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3858 if (!MemOpChains.empty())
3859 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3860 &MemOpChains[0], MemOpChains.size());
3862 // Build a sequence of copy-to-reg nodes chained together with token chain
3863 // and flag operands which copy the outgoing args into the appropriate regs.
3865 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3866 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3867 RegsToPass[i].second, InFlag);
3868 InFlag = Chain.getValue(1);
3871 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3874 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3875 SDValue Ops[] = { Chain, InFlag };
3877 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3878 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3880 InFlag = Chain.getValue(1);
3884 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3885 false, TailCallArguments);
3887 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3888 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3892 // Copy an argument into memory, being careful to do this outside the
3893 // call sequence for the call to which the argument belongs.
3895 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3896 SDValue CallSeqStart,
3897 ISD::ArgFlagsTy Flags,
3900 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3901 CallSeqStart.getNode()->getOperand(0),
3903 // The MEMCPY must go outside the CALLSEQ_START..END.
3904 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3905 CallSeqStart.getNode()->getOperand(1),
3907 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3908 NewCallSeqStart.getNode());
3909 return NewCallSeqStart;
3913 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3914 CallingConv::ID CallConv, bool isVarArg,
3916 const SmallVectorImpl<ISD::OutputArg> &Outs,
3917 const SmallVectorImpl<SDValue> &OutVals,
3918 const SmallVectorImpl<ISD::InputArg> &Ins,
3919 SDLoc dl, SelectionDAG &DAG,
3920 SmallVectorImpl<SDValue> &InVals) const {
3922 unsigned NumOps = Outs.size();
3924 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3925 unsigned PtrByteSize = 8;
3927 MachineFunction &MF = DAG.getMachineFunction();
3929 // Mark this function as potentially containing a function that contains a
3930 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3931 // and restoring the callers stack pointer in this functions epilog. This is
3932 // done because by tail calling the called function might overwrite the value
3933 // in this function's (MF) stack pointer stack slot 0(SP).
3934 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3935 CallConv == CallingConv::Fast)
3936 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3938 unsigned nAltivecParamsAtEnd = 0;
3940 // Count how many bytes are to be pushed on the stack, including the linkage
3941 // area, and parameter passing area. We start with at least 48 bytes, which
3942 // is reserved space for [SP][CR][LR][3 x unused].
3943 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3946 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3947 Outs, OutVals, nAltivecParamsAtEnd);
3949 // Calculate by how many bytes the stack has to be adjusted in case of tail
3950 // call optimization.
3951 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3953 // To protect arguments on the stack from being clobbered in a tail call,
3954 // force all the loads to happen before doing any other lowering.
3956 Chain = DAG.getStackArgumentTokenFactor(Chain);
3958 // Adjust the stack pointer for the new arguments...
3959 // These operations are automatically eliminated by the prolog/epilog pass
3960 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3962 SDValue CallSeqStart = Chain;
3964 // Load the return address and frame pointer so it can be move somewhere else
3967 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3970 // Set up a copy of the stack pointer for use loading and storing any
3971 // arguments that may not fit in the registers available for argument
3973 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3975 // Figure out which arguments are going to go in registers, and which in
3976 // memory. Also, if this is a vararg function, floating point operations
3977 // must be stored to our stack, and loaded into integer regs as well, if
3978 // any integer regs are available for argument passing.
3979 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3980 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3982 static const uint16_t GPR[] = {
3983 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3984 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3986 static const uint16_t *FPR = GetFPR();
3988 static const uint16_t VR[] = {
3989 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3990 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3992 const unsigned NumGPRs = array_lengthof(GPR);
3993 const unsigned NumFPRs = 13;
3994 const unsigned NumVRs = array_lengthof(VR);
3996 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3997 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3999 SmallVector<SDValue, 8> MemOpChains;
4000 for (unsigned i = 0; i != NumOps; ++i) {
4001 SDValue Arg = OutVals[i];
4002 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4004 // PtrOff will be used to store the current argument to the stack if a
4005 // register cannot be found for it.
4008 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4010 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4012 // Promote integers to 64-bit values.
4013 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4014 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4015 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4016 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4019 // FIXME memcpy is used way more than necessary. Correctness first.
4020 // Note: "by value" is code for passing a structure by value, not
4022 if (Flags.isByVal()) {
4023 // Note: Size includes alignment padding, so
4024 // struct x { short a; char b; }
4025 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4026 // These are the proper values we need for right-justifying the
4027 // aggregate in a parameter register.
4028 unsigned Size = Flags.getByValSize();
4030 // An empty aggregate parameter takes up no storage and no
4035 unsigned BVAlign = Flags.getByValAlign();
4037 if (BVAlign % PtrByteSize != 0)
4039 "ByVal alignment is not a multiple of the pointer size");
4041 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4044 // All aggregates smaller than 8 bytes must be passed right-justified.
4045 if (Size==1 || Size==2 || Size==4) {
4046 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4047 if (GPR_idx != NumGPRs) {
4048 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4049 MachinePointerInfo(), VT,
4051 MemOpChains.push_back(Load.getValue(1));
4052 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4054 ArgOffset += PtrByteSize;
4059 if (GPR_idx == NumGPRs && Size < 8) {
4060 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4061 PtrOff.getValueType());
4062 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4063 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4066 ArgOffset += PtrByteSize;
4069 // Copy entire object into memory. There are cases where gcc-generated
4070 // code assumes it is there, even if it could be put entirely into
4071 // registers. (This is not what the doc says.)
4073 // FIXME: The above statement is likely due to a misunderstanding of the
4074 // documents. All arguments must be copied into the parameter area BY
4075 // THE CALLEE in the event that the callee takes the address of any
4076 // formal argument. That has not yet been implemented. However, it is
4077 // reasonable to use the stack area as a staging area for the register
4080 // Skip this for small aggregates, as we will use the same slot for a
4081 // right-justified copy, below.
4083 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4087 // When a register is available, pass a small aggregate right-justified.
4088 if (Size < 8 && GPR_idx != NumGPRs) {
4089 // The easiest way to get this right-justified in a register
4090 // is to copy the structure into the rightmost portion of a
4091 // local variable slot, then load the whole slot into the
4093 // FIXME: The memcpy seems to produce pretty awful code for
4094 // small aggregates, particularly for packed ones.
4095 // FIXME: It would be preferable to use the slot in the
4096 // parameter save area instead of a new local variable.
4097 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4098 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4099 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4103 // Load the slot into the register.
4104 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4105 MachinePointerInfo(),
4106 false, false, false, 0);
4107 MemOpChains.push_back(Load.getValue(1));
4108 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4110 // Done with this argument.
4111 ArgOffset += PtrByteSize;
4115 // For aggregates larger than PtrByteSize, copy the pieces of the
4116 // object that fit into registers from the parameter save area.
4117 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4118 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4119 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4120 if (GPR_idx != NumGPRs) {
4121 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4122 MachinePointerInfo(),
4123 false, false, false, 0);
4124 MemOpChains.push_back(Load.getValue(1));
4125 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4126 ArgOffset += PtrByteSize;
4128 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4135 switch (Arg.getSimpleValueType().SimpleTy) {
4136 default: llvm_unreachable("Unexpected ValueType for argument!");
4140 if (GPR_idx != NumGPRs) {
4141 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4143 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4144 true, isTailCall, false, MemOpChains,
4145 TailCallArguments, dl);
4147 ArgOffset += PtrByteSize;
4151 if (FPR_idx != NumFPRs) {
4152 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4155 // A single float or an aggregate containing only a single float
4156 // must be passed right-justified in the stack doubleword, and
4157 // in the GPR, if one is available.
4159 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4160 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4161 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4165 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4166 MachinePointerInfo(), false, false, 0);
4167 MemOpChains.push_back(Store);
4169 // Float varargs are always shadowed in available integer registers
4170 if (GPR_idx != NumGPRs) {
4171 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4172 MachinePointerInfo(), false, false,
4174 MemOpChains.push_back(Load.getValue(1));
4175 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4177 } else if (GPR_idx != NumGPRs)
4178 // If we have any FPRs remaining, we may also have GPRs remaining.
4181 // Single-precision floating-point values are mapped to the
4182 // second (rightmost) word of the stack doubleword.
4183 if (Arg.getValueType() == MVT::f32) {
4184 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4185 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4188 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4189 true, isTailCall, false, MemOpChains,
4190 TailCallArguments, dl);
4201 // These go aligned on the stack, or in the corresponding R registers
4202 // when within range. The Darwin PPC ABI doc claims they also go in
4203 // V registers; in fact gcc does this only for arguments that are
4204 // prototyped, not for those that match the ... We do it for all
4205 // arguments, seems to work.
4206 while (ArgOffset % 16 !=0) {
4207 ArgOffset += PtrByteSize;
4208 if (GPR_idx != NumGPRs)
4211 // We could elide this store in the case where the object fits
4212 // entirely in R registers. Maybe later.
4213 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4214 DAG.getConstant(ArgOffset, PtrVT));
4215 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4216 MachinePointerInfo(), false, false, 0);
4217 MemOpChains.push_back(Store);
4218 if (VR_idx != NumVRs) {
4219 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4220 MachinePointerInfo(),
4221 false, false, false, 0);
4222 MemOpChains.push_back(Load.getValue(1));
4223 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4226 for (unsigned i=0; i<16; i+=PtrByteSize) {
4227 if (GPR_idx == NumGPRs)
4229 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4230 DAG.getConstant(i, PtrVT));
4231 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4232 false, false, false, 0);
4233 MemOpChains.push_back(Load.getValue(1));
4234 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4239 // Non-varargs Altivec params generally go in registers, but have
4240 // stack space allocated at the end.
4241 if (VR_idx != NumVRs) {
4242 // Doesn't have GPR space allocated.
4243 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4245 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4246 true, isTailCall, true, MemOpChains,
4247 TailCallArguments, dl);
4254 if (!MemOpChains.empty())
4255 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4256 &MemOpChains[0], MemOpChains.size());
4258 // Check if this is an indirect call (MTCTR/BCTRL).
4259 // See PrepareCall() for more information about calls through function
4260 // pointers in the 64-bit SVR4 ABI.
4262 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4263 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4264 !isBLACompatibleAddress(Callee, DAG)) {
4265 // Load r2 into a virtual register and store it to the TOC save area.
4266 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4267 // TOC save area offset.
4268 SDValue PtrOff = DAG.getIntPtrConstant(40);
4269 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4270 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4272 // R12 must contain the address of an indirect callee. This does not
4273 // mean the MTCTR instruction must use R12; it's easier to model this
4274 // as an extra parameter, so do that.
4275 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4278 // Build a sequence of copy-to-reg nodes chained together with token chain
4279 // and flag operands which copy the outgoing args into the appropriate regs.
4281 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4282 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4283 RegsToPass[i].second, InFlag);
4284 InFlag = Chain.getValue(1);
4288 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4289 FPOp, true, TailCallArguments);
4291 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4292 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4297 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4298 CallingConv::ID CallConv, bool isVarArg,
4300 const SmallVectorImpl<ISD::OutputArg> &Outs,
4301 const SmallVectorImpl<SDValue> &OutVals,
4302 const SmallVectorImpl<ISD::InputArg> &Ins,
4303 SDLoc dl, SelectionDAG &DAG,
4304 SmallVectorImpl<SDValue> &InVals) const {
4306 unsigned NumOps = Outs.size();
4308 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4309 bool isPPC64 = PtrVT == MVT::i64;
4310 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4312 MachineFunction &MF = DAG.getMachineFunction();
4314 // Mark this function as potentially containing a function that contains a
4315 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4316 // and restoring the callers stack pointer in this functions epilog. This is
4317 // done because by tail calling the called function might overwrite the value
4318 // in this function's (MF) stack pointer stack slot 0(SP).
4319 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4320 CallConv == CallingConv::Fast)
4321 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4323 unsigned nAltivecParamsAtEnd = 0;
4325 // Count how many bytes are to be pushed on the stack, including the linkage
4326 // area, and parameter passing area. We start with 24/48 bytes, which is
4327 // prereserved space for [SP][CR][LR][3 x unused].
4329 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4331 nAltivecParamsAtEnd);
4333 // Calculate by how many bytes the stack has to be adjusted in case of tail
4334 // call optimization.
4335 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4337 // To protect arguments on the stack from being clobbered in a tail call,
4338 // force all the loads to happen before doing any other lowering.
4340 Chain = DAG.getStackArgumentTokenFactor(Chain);
4342 // Adjust the stack pointer for the new arguments...
4343 // These operations are automatically eliminated by the prolog/epilog pass
4344 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4346 SDValue CallSeqStart = Chain;
4348 // Load the return address and frame pointer so it can be move somewhere else
4351 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4354 // Set up a copy of the stack pointer for use loading and storing any
4355 // arguments that may not fit in the registers available for argument
4359 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4361 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4363 // Figure out which arguments are going to go in registers, and which in
4364 // memory. Also, if this is a vararg function, floating point operations
4365 // must be stored to our stack, and loaded into integer regs as well, if
4366 // any integer regs are available for argument passing.
4367 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4368 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4370 static const uint16_t GPR_32[] = { // 32-bit registers.
4371 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4372 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4374 static const uint16_t GPR_64[] = { // 64-bit registers.
4375 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4376 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4378 static const uint16_t *FPR = GetFPR();
4380 static const uint16_t VR[] = {
4381 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4382 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4384 const unsigned NumGPRs = array_lengthof(GPR_32);
4385 const unsigned NumFPRs = 13;
4386 const unsigned NumVRs = array_lengthof(VR);
4388 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4390 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4391 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4393 SmallVector<SDValue, 8> MemOpChains;
4394 for (unsigned i = 0; i != NumOps; ++i) {
4395 SDValue Arg = OutVals[i];
4396 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4398 // PtrOff will be used to store the current argument to the stack if a
4399 // register cannot be found for it.
4402 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4404 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4406 // On PPC64, promote integers to 64-bit values.
4407 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4408 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4409 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4410 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4413 // FIXME memcpy is used way more than necessary. Correctness first.
4414 // Note: "by value" is code for passing a structure by value, not
4416 if (Flags.isByVal()) {
4417 unsigned Size = Flags.getByValSize();
4418 // Very small objects are passed right-justified. Everything else is
4419 // passed left-justified.
4420 if (Size==1 || Size==2) {
4421 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4422 if (GPR_idx != NumGPRs) {
4423 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4424 MachinePointerInfo(), VT,
4426 MemOpChains.push_back(Load.getValue(1));
4427 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4429 ArgOffset += PtrByteSize;
4431 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4432 PtrOff.getValueType());
4433 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4434 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4437 ArgOffset += PtrByteSize;
4441 // Copy entire object into memory. There are cases where gcc-generated
4442 // code assumes it is there, even if it could be put entirely into
4443 // registers. (This is not what the doc says.)
4444 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4448 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4449 // copy the pieces of the object that fit into registers from the
4450 // parameter save area.
4451 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4452 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4453 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4454 if (GPR_idx != NumGPRs) {
4455 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4456 MachinePointerInfo(),
4457 false, false, false, 0);
4458 MemOpChains.push_back(Load.getValue(1));
4459 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4460 ArgOffset += PtrByteSize;
4462 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4469 switch (Arg.getSimpleValueType().SimpleTy) {
4470 default: llvm_unreachable("Unexpected ValueType for argument!");
4474 if (GPR_idx != NumGPRs) {
4475 if (Arg.getValueType() == MVT::i1)
4476 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4478 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4480 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4481 isPPC64, isTailCall, false, MemOpChains,
4482 TailCallArguments, dl);
4484 ArgOffset += PtrByteSize;
4488 if (FPR_idx != NumFPRs) {
4489 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4492 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4493 MachinePointerInfo(), false, false, 0);
4494 MemOpChains.push_back(Store);
4496 // Float varargs are always shadowed in available integer registers
4497 if (GPR_idx != NumGPRs) {
4498 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4499 MachinePointerInfo(), false, false,
4501 MemOpChains.push_back(Load.getValue(1));
4502 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4504 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4505 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4506 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4507 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4508 MachinePointerInfo(),
4509 false, false, false, 0);
4510 MemOpChains.push_back(Load.getValue(1));
4511 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4514 // If we have any FPRs remaining, we may also have GPRs remaining.
4515 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4517 if (GPR_idx != NumGPRs)
4519 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4520 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4524 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4525 isPPC64, isTailCall, false, MemOpChains,
4526 TailCallArguments, dl);
4530 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4537 // These go aligned on the stack, or in the corresponding R registers
4538 // when within range. The Darwin PPC ABI doc claims they also go in
4539 // V registers; in fact gcc does this only for arguments that are
4540 // prototyped, not for those that match the ... We do it for all
4541 // arguments, seems to work.
4542 while (ArgOffset % 16 !=0) {
4543 ArgOffset += PtrByteSize;
4544 if (GPR_idx != NumGPRs)
4547 // We could elide this store in the case where the object fits
4548 // entirely in R registers. Maybe later.
4549 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4550 DAG.getConstant(ArgOffset, PtrVT));
4551 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4552 MachinePointerInfo(), false, false, 0);
4553 MemOpChains.push_back(Store);
4554 if (VR_idx != NumVRs) {
4555 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4556 MachinePointerInfo(),
4557 false, false, false, 0);
4558 MemOpChains.push_back(Load.getValue(1));
4559 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4562 for (unsigned i=0; i<16; i+=PtrByteSize) {
4563 if (GPR_idx == NumGPRs)
4565 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4566 DAG.getConstant(i, PtrVT));
4567 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4568 false, false, false, 0);
4569 MemOpChains.push_back(Load.getValue(1));
4570 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4575 // Non-varargs Altivec params generally go in registers, but have
4576 // stack space allocated at the end.
4577 if (VR_idx != NumVRs) {
4578 // Doesn't have GPR space allocated.
4579 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4580 } else if (nAltivecParamsAtEnd==0) {
4581 // We are emitting Altivec params in order.
4582 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4583 isPPC64, isTailCall, true, MemOpChains,
4584 TailCallArguments, dl);
4590 // If all Altivec parameters fit in registers, as they usually do,
4591 // they get stack space following the non-Altivec parameters. We
4592 // don't track this here because nobody below needs it.
4593 // If there are more Altivec parameters than fit in registers emit
4595 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4597 // Offset is aligned; skip 1st 12 params which go in V registers.
4598 ArgOffset = ((ArgOffset+15)/16)*16;
4600 for (unsigned i = 0; i != NumOps; ++i) {
4601 SDValue Arg = OutVals[i];
4602 EVT ArgType = Outs[i].VT;
4603 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4604 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4607 // We are emitting Altivec params in order.
4608 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4609 isPPC64, isTailCall, true, MemOpChains,
4610 TailCallArguments, dl);
4617 if (!MemOpChains.empty())
4618 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4619 &MemOpChains[0], MemOpChains.size());
4621 // On Darwin, R12 must contain the address of an indirect callee. This does
4622 // not mean the MTCTR instruction must use R12; it's easier to model this as
4623 // an extra parameter, so do that.
4625 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4626 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4627 !isBLACompatibleAddress(Callee, DAG))
4628 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4629 PPC::R12), Callee));
4631 // Build a sequence of copy-to-reg nodes chained together with token chain
4632 // and flag operands which copy the outgoing args into the appropriate regs.
4634 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4635 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4636 RegsToPass[i].second, InFlag);
4637 InFlag = Chain.getValue(1);
4641 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4642 FPOp, true, TailCallArguments);
4644 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4645 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4650 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4651 MachineFunction &MF, bool isVarArg,
4652 const SmallVectorImpl<ISD::OutputArg> &Outs,
4653 LLVMContext &Context) const {
4654 SmallVector<CCValAssign, 16> RVLocs;
4655 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4657 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4661 PPCTargetLowering::LowerReturn(SDValue Chain,
4662 CallingConv::ID CallConv, bool isVarArg,
4663 const SmallVectorImpl<ISD::OutputArg> &Outs,
4664 const SmallVectorImpl<SDValue> &OutVals,
4665 SDLoc dl, SelectionDAG &DAG) const {
4667 SmallVector<CCValAssign, 16> RVLocs;
4668 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4669 getTargetMachine(), RVLocs, *DAG.getContext());
4670 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4673 SmallVector<SDValue, 4> RetOps(1, Chain);
4675 // Copy the result values into the output registers.
4676 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4677 CCValAssign &VA = RVLocs[i];
4678 assert(VA.isRegLoc() && "Can only return in registers!");
4680 SDValue Arg = OutVals[i];
4682 switch (VA.getLocInfo()) {
4683 default: llvm_unreachable("Unknown loc info!");
4684 case CCValAssign::Full: break;
4685 case CCValAssign::AExt:
4686 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4688 case CCValAssign::ZExt:
4689 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4691 case CCValAssign::SExt:
4692 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4696 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4697 Flag = Chain.getValue(1);
4698 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4701 RetOps[0] = Chain; // Update chain.
4703 // Add the flag if we have it.
4705 RetOps.push_back(Flag);
4707 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4708 &RetOps[0], RetOps.size());
4711 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4712 const PPCSubtarget &Subtarget) const {
4713 // When we pop the dynamic allocation we need to restore the SP link.
4716 // Get the corect type for pointers.
4717 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4719 // Construct the stack pointer operand.
4720 bool isPPC64 = Subtarget.isPPC64();
4721 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4722 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4724 // Get the operands for the STACKRESTORE.
4725 SDValue Chain = Op.getOperand(0);
4726 SDValue SaveSP = Op.getOperand(1);
4728 // Load the old link SP.
4729 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4730 MachinePointerInfo(),
4731 false, false, false, 0);
4733 // Restore the stack pointer.
4734 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4736 // Store the old link SP.
4737 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4744 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4745 MachineFunction &MF = DAG.getMachineFunction();
4746 bool isPPC64 = PPCSubTarget.isPPC64();
4747 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4748 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4750 // Get current frame pointer save index. The users of this index will be
4751 // primarily DYNALLOC instructions.
4752 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4753 int RASI = FI->getReturnAddrSaveIndex();
4755 // If the frame pointer save index hasn't been defined yet.
4757 // Find out what the fix offset of the frame pointer save area.
4758 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4759 // Allocate the frame index for frame pointer save area.
4760 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4762 FI->setReturnAddrSaveIndex(RASI);
4764 return DAG.getFrameIndex(RASI, PtrVT);
4768 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4769 MachineFunction &MF = DAG.getMachineFunction();
4770 bool isPPC64 = PPCSubTarget.isPPC64();
4771 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4772 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4774 // Get current frame pointer save index. The users of this index will be
4775 // primarily DYNALLOC instructions.
4776 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4777 int FPSI = FI->getFramePointerSaveIndex();
4779 // If the frame pointer save index hasn't been defined yet.
4781 // Find out what the fix offset of the frame pointer save area.
4782 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4785 // Allocate the frame index for frame pointer save area.
4786 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4788 FI->setFramePointerSaveIndex(FPSI);
4790 return DAG.getFrameIndex(FPSI, PtrVT);
4793 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4795 const PPCSubtarget &Subtarget) const {
4797 SDValue Chain = Op.getOperand(0);
4798 SDValue Size = Op.getOperand(1);
4801 // Get the corect type for pointers.
4802 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4804 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4805 DAG.getConstant(0, PtrVT), Size);
4806 // Construct a node for the frame pointer save index.
4807 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4808 // Build a DYNALLOC node.
4809 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4810 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4811 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4814 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4815 SelectionDAG &DAG) const {
4817 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4818 DAG.getVTList(MVT::i32, MVT::Other),
4819 Op.getOperand(0), Op.getOperand(1));
4822 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4823 SelectionDAG &DAG) const {
4825 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4826 Op.getOperand(0), Op.getOperand(1));
4829 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4830 assert(Op.getValueType() == MVT::i1 &&
4831 "Custom lowering only for i1 loads");
4833 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4836 LoadSDNode *LD = cast<LoadSDNode>(Op);
4838 SDValue Chain = LD->getChain();
4839 SDValue BasePtr = LD->getBasePtr();
4840 MachineMemOperand *MMO = LD->getMemOperand();
4842 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4843 BasePtr, MVT::i8, MMO);
4844 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4846 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4847 return DAG.getMergeValues(Ops, 2, dl);
4850 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4851 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4852 "Custom lowering only for i1 stores");
4854 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4857 StoreSDNode *ST = cast<StoreSDNode>(Op);
4859 SDValue Chain = ST->getChain();
4860 SDValue BasePtr = ST->getBasePtr();
4861 SDValue Value = ST->getValue();
4862 MachineMemOperand *MMO = ST->getMemOperand();
4864 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4865 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4868 // FIXME: Remove this once the ANDI glue bug is fixed:
4869 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4870 assert(Op.getValueType() == MVT::i1 &&
4871 "Custom lowering only for i1 results");
4874 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4878 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4880 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4881 // Not FP? Not a fsel.
4882 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4883 !Op.getOperand(2).getValueType().isFloatingPoint())
4886 // We might be able to do better than this under some circumstances, but in
4887 // general, fsel-based lowering of select is a finite-math-only optimization.
4888 // For more information, see section F.3 of the 2.06 ISA specification.
4889 if (!DAG.getTarget().Options.NoInfsFPMath ||
4890 !DAG.getTarget().Options.NoNaNsFPMath)
4893 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4895 EVT ResVT = Op.getValueType();
4896 EVT CmpVT = Op.getOperand(0).getValueType();
4897 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4898 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4901 // If the RHS of the comparison is a 0.0, we don't need to do the
4902 // subtraction at all.
4904 if (isFloatingPointZero(RHS))
4906 default: break; // SETUO etc aren't handled by fsel.
4910 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4911 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4912 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4913 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4914 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4915 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4916 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4919 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4922 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4923 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4924 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4927 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4930 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4931 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4932 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4933 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4938 default: break; // SETUO etc aren't handled by fsel.
4942 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4943 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4944 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4945 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4946 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4947 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4948 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4949 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4952 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4953 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4954 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4955 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4958 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4959 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4960 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4961 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4964 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4965 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4966 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4967 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4970 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4971 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4972 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4973 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4978 // FIXME: Split this code up when LegalizeDAGTypes lands.
4979 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4981 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4982 SDValue Src = Op.getOperand(0);
4983 if (Src.getValueType() == MVT::f32)
4984 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4987 switch (Op.getSimpleValueType().SimpleTy) {
4988 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4990 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4991 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4996 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4997 "i64 FP_TO_UINT is supported only with FPCVT");
4998 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5004 // Convert the FP value to an int value through memory.
5005 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5006 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5007 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5008 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5009 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5011 // Emit a store to the stack slot.
5014 MachineFunction &MF = DAG.getMachineFunction();
5015 MachineMemOperand *MMO =
5016 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5017 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5018 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5019 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
5022 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5023 MPI, false, false, 0);
5025 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5027 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5028 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5029 DAG.getConstant(4, FIPtr.getValueType()));
5030 MPI = MachinePointerInfo();
5033 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5034 false, false, false, 0);
5037 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5038 SelectionDAG &DAG) const {
5040 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5041 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5044 if (Op.getOperand(0).getValueType() == MVT::i1)
5045 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5046 DAG.getConstantFP(1.0, Op.getValueType()),
5047 DAG.getConstantFP(0.0, Op.getValueType()));
5049 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5050 "UINT_TO_FP is supported only with FPCVT");
5052 // If we have FCFIDS, then use it when converting to single-precision.
5053 // Otherwise, convert to double-precision and then round.
5054 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5055 (Op.getOpcode() == ISD::UINT_TO_FP ?
5056 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5057 (Op.getOpcode() == ISD::UINT_TO_FP ?
5058 PPCISD::FCFIDU : PPCISD::FCFID);
5059 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5060 MVT::f32 : MVT::f64;
5062 if (Op.getOperand(0).getValueType() == MVT::i64) {
5063 SDValue SINT = Op.getOperand(0);
5064 // When converting to single-precision, we actually need to convert
5065 // to double-precision first and then round to single-precision.
5066 // To avoid double-rounding effects during that operation, we have
5067 // to prepare the input operand. Bits that might be truncated when
5068 // converting to double-precision are replaced by a bit that won't
5069 // be lost at this stage, but is below the single-precision rounding
5072 // However, if -enable-unsafe-fp-math is in effect, accept double
5073 // rounding to avoid the extra overhead.
5074 if (Op.getValueType() == MVT::f32 &&
5075 !PPCSubTarget.hasFPCVT() &&
5076 !DAG.getTarget().Options.UnsafeFPMath) {
5078 // Twiddle input to make sure the low 11 bits are zero. (If this
5079 // is the case, we are guaranteed the value will fit into the 53 bit
5080 // mantissa of an IEEE double-precision value without rounding.)
5081 // If any of those low 11 bits were not zero originally, make sure
5082 // bit 12 (value 2048) is set instead, so that the final rounding
5083 // to single-precision gets the correct result.
5084 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5085 SINT, DAG.getConstant(2047, MVT::i64));
5086 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5087 Round, DAG.getConstant(2047, MVT::i64));
5088 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5089 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5090 Round, DAG.getConstant(-2048, MVT::i64));
5092 // However, we cannot use that value unconditionally: if the magnitude
5093 // of the input value is small, the bit-twiddling we did above might
5094 // end up visibly changing the output. Fortunately, in that case, we
5095 // don't need to twiddle bits since the original input will convert
5096 // exactly to double-precision floating-point already. Therefore,
5097 // construct a conditional to use the original value if the top 11
5098 // bits are all sign-bit copies, and use the rounded value computed
5100 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5101 SINT, DAG.getConstant(53, MVT::i32));
5102 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5103 Cond, DAG.getConstant(1, MVT::i64));
5104 Cond = DAG.getSetCC(dl, MVT::i32,
5105 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5107 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5110 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5111 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5113 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5114 FP = DAG.getNode(ISD::FP_ROUND, dl,
5115 MVT::f32, FP, DAG.getIntPtrConstant(0));
5119 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5120 "Unhandled INT_TO_FP type in custom expander!");
5121 // Since we only generate this in 64-bit mode, we can take advantage of
5122 // 64-bit registers. In particular, sign extend the input value into the
5123 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5124 // then lfd it and fcfid it.
5125 MachineFunction &MF = DAG.getMachineFunction();
5126 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5127 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5130 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5131 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5132 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5134 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5135 MachinePointerInfo::getFixedStack(FrameIdx),
5138 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5139 "Expected an i32 store");
5140 MachineMemOperand *MMO =
5141 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5142 MachineMemOperand::MOLoad, 4, 4);
5143 SDValue Ops[] = { Store, FIdx };
5144 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5145 PPCISD::LFIWZX : PPCISD::LFIWAX,
5146 dl, DAG.getVTList(MVT::f64, MVT::Other),
5147 Ops, 2, MVT::i32, MMO);
5149 assert(PPCSubTarget.isPPC64() &&
5150 "i32->FP without LFIWAX supported only on PPC64");
5152 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5153 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5155 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5158 // STD the extended value into the stack slot.
5159 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5160 MachinePointerInfo::getFixedStack(FrameIdx),
5163 // Load the value as a double.
5164 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5165 MachinePointerInfo::getFixedStack(FrameIdx),
5166 false, false, false, 0);
5169 // FCFID it and return it.
5170 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5171 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5172 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5176 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5177 SelectionDAG &DAG) const {
5180 The rounding mode is in bits 30:31 of FPSR, and has the following
5187 FLT_ROUNDS, on the other hand, expects the following:
5194 To perform the conversion, we do:
5195 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5198 MachineFunction &MF = DAG.getMachineFunction();
5199 EVT VT = Op.getValueType();
5200 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5201 SDValue MFFSreg, InFlag;
5203 // Save FP Control Word to register
5205 MVT::f64, // return register
5206 MVT::Glue // unused in this context
5208 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5210 // Save FP register to stack slot
5211 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5212 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5213 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5214 StackSlot, MachinePointerInfo(), false, false,0);
5216 // Load FP Control Word from low 32 bits of stack slot.
5217 SDValue Four = DAG.getConstant(4, PtrVT);
5218 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5219 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5220 false, false, false, 0);
5222 // Transform as necessary
5224 DAG.getNode(ISD::AND, dl, MVT::i32,
5225 CWD, DAG.getConstant(3, MVT::i32));
5227 DAG.getNode(ISD::SRL, dl, MVT::i32,
5228 DAG.getNode(ISD::AND, dl, MVT::i32,
5229 DAG.getNode(ISD::XOR, dl, MVT::i32,
5230 CWD, DAG.getConstant(3, MVT::i32)),
5231 DAG.getConstant(3, MVT::i32)),
5232 DAG.getConstant(1, MVT::i32));
5235 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5237 return DAG.getNode((VT.getSizeInBits() < 16 ?
5238 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5241 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5242 EVT VT = Op.getValueType();
5243 unsigned BitWidth = VT.getSizeInBits();
5245 assert(Op.getNumOperands() == 3 &&
5246 VT == Op.getOperand(1).getValueType() &&
5249 // Expand into a bunch of logical ops. Note that these ops
5250 // depend on the PPC behavior for oversized shift amounts.
5251 SDValue Lo = Op.getOperand(0);
5252 SDValue Hi = Op.getOperand(1);
5253 SDValue Amt = Op.getOperand(2);
5254 EVT AmtVT = Amt.getValueType();
5256 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5257 DAG.getConstant(BitWidth, AmtVT), Amt);
5258 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5259 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5260 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5261 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5262 DAG.getConstant(-BitWidth, AmtVT));
5263 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5264 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5265 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5266 SDValue OutOps[] = { OutLo, OutHi };
5267 return DAG.getMergeValues(OutOps, 2, dl);
5270 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5271 EVT VT = Op.getValueType();
5273 unsigned BitWidth = VT.getSizeInBits();
5274 assert(Op.getNumOperands() == 3 &&
5275 VT == Op.getOperand(1).getValueType() &&
5278 // Expand into a bunch of logical ops. Note that these ops
5279 // depend on the PPC behavior for oversized shift amounts.
5280 SDValue Lo = Op.getOperand(0);
5281 SDValue Hi = Op.getOperand(1);
5282 SDValue Amt = Op.getOperand(2);
5283 EVT AmtVT = Amt.getValueType();
5285 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5286 DAG.getConstant(BitWidth, AmtVT), Amt);
5287 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5288 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5289 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5290 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5291 DAG.getConstant(-BitWidth, AmtVT));
5292 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5293 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5294 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5295 SDValue OutOps[] = { OutLo, OutHi };
5296 return DAG.getMergeValues(OutOps, 2, dl);
5299 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5301 EVT VT = Op.getValueType();
5302 unsigned BitWidth = VT.getSizeInBits();
5303 assert(Op.getNumOperands() == 3 &&
5304 VT == Op.getOperand(1).getValueType() &&
5307 // Expand into a bunch of logical ops, followed by a select_cc.
5308 SDValue Lo = Op.getOperand(0);
5309 SDValue Hi = Op.getOperand(1);
5310 SDValue Amt = Op.getOperand(2);
5311 EVT AmtVT = Amt.getValueType();
5313 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5314 DAG.getConstant(BitWidth, AmtVT), Amt);
5315 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5316 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5317 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5318 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5319 DAG.getConstant(-BitWidth, AmtVT));
5320 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5321 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5322 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5323 Tmp4, Tmp6, ISD::SETLE);
5324 SDValue OutOps[] = { OutLo, OutHi };
5325 return DAG.getMergeValues(OutOps, 2, dl);
5328 //===----------------------------------------------------------------------===//
5329 // Vector related lowering.
5332 /// BuildSplatI - Build a canonical splati of Val with an element size of
5333 /// SplatSize. Cast the result to VT.
5334 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5335 SelectionDAG &DAG, SDLoc dl) {
5336 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5338 static const EVT VTys[] = { // canonical VT to use for each size.
5339 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5342 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5344 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5348 EVT CanonicalVT = VTys[SplatSize-1];
5350 // Build a canonical splat for this value.
5351 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5352 SmallVector<SDValue, 8> Ops;
5353 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5354 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5355 &Ops[0], Ops.size());
5356 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5359 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5360 /// specified intrinsic ID.
5361 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5362 SelectionDAG &DAG, SDLoc dl,
5363 EVT DestVT = MVT::Other) {
5364 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5365 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5366 DAG.getConstant(IID, MVT::i32), Op);
5369 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5370 /// specified intrinsic ID.
5371 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5372 SelectionDAG &DAG, SDLoc dl,
5373 EVT DestVT = MVT::Other) {
5374 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5375 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5376 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5379 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5380 /// specified intrinsic ID.
5381 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5382 SDValue Op2, SelectionDAG &DAG,
5383 SDLoc dl, EVT DestVT = MVT::Other) {
5384 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5385 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5386 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5390 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5391 /// amount. The result has the specified value type.
5392 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5393 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5394 // Force LHS/RHS to be the right type.
5395 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5396 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5399 for (unsigned i = 0; i != 16; ++i)
5401 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5402 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5405 // If this is a case we can't handle, return null and let the default
5406 // expansion code take care of it. If we CAN select this case, and if it
5407 // selects to a single instruction, return Op. Otherwise, if we can codegen
5408 // this case more efficiently than a constant pool load, lower it to the
5409 // sequence of ops that should be used.
5410 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5411 SelectionDAG &DAG) const {
5413 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5414 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5416 // Check if this is a splat of a constant value.
5417 APInt APSplatBits, APSplatUndef;
5418 unsigned SplatBitSize;
5420 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5421 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5424 unsigned SplatBits = APSplatBits.getZExtValue();
5425 unsigned SplatUndef = APSplatUndef.getZExtValue();
5426 unsigned SplatSize = SplatBitSize / 8;
5428 // First, handle single instruction cases.
5431 if (SplatBits == 0) {
5432 // Canonicalize all zero vectors to be v4i32.
5433 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5434 SDValue Z = DAG.getConstant(0, MVT::i32);
5435 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5436 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5441 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5442 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5444 if (SextVal >= -16 && SextVal <= 15)
5445 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5448 // Two instruction sequences.
5450 // If this value is in the range [-32,30] and is even, use:
5451 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5452 // If this value is in the range [17,31] and is odd, use:
5453 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5454 // If this value is in the range [-31,-17] and is odd, use:
5455 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5456 // Note the last two are three-instruction sequences.
5457 if (SextVal >= -32 && SextVal <= 31) {
5458 // To avoid having these optimizations undone by constant folding,
5459 // we convert to a pseudo that will be expanded later into one of
5461 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5462 EVT VT = Op.getValueType();
5463 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5464 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5465 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5468 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5469 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5471 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5472 // Make -1 and vspltisw -1:
5473 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5475 // Make the VSLW intrinsic, computing 0x8000_0000.
5476 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5479 // xor by OnesV to invert it.
5480 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5481 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5484 // Check to see if this is a wide variety of vsplti*, binop self cases.
5485 static const signed char SplatCsts[] = {
5486 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5487 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5490 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5491 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5492 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5493 int i = SplatCsts[idx];
5495 // Figure out what shift amount will be used by altivec if shifted by i in
5497 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5499 // vsplti + shl self.
5500 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5501 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5502 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5503 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5504 Intrinsic::ppc_altivec_vslw
5506 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5507 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5510 // vsplti + srl self.
5511 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5512 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5513 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5514 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5515 Intrinsic::ppc_altivec_vsrw
5517 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5518 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5521 // vsplti + sra self.
5522 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5523 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5524 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5525 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5526 Intrinsic::ppc_altivec_vsraw
5528 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5529 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5532 // vsplti + rol self.
5533 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5534 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5535 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5536 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5537 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5538 Intrinsic::ppc_altivec_vrlw
5540 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5541 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5544 // t = vsplti c, result = vsldoi t, t, 1
5545 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5546 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5547 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5549 // t = vsplti c, result = vsldoi t, t, 2
5550 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5551 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5552 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5554 // t = vsplti c, result = vsldoi t, t, 3
5555 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5556 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5557 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5564 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5565 /// the specified operations to build the shuffle.
5566 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5567 SDValue RHS, SelectionDAG &DAG,
5569 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5570 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5571 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5574 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5586 if (OpNum == OP_COPY) {
5587 if (LHSID == (1*9+2)*9+3) return LHS;
5588 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5592 SDValue OpLHS, OpRHS;
5593 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5594 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5598 default: llvm_unreachable("Unknown i32 permute!");
5600 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5601 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5602 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5603 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5606 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5607 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5608 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5609 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5612 for (unsigned i = 0; i != 16; ++i)
5613 ShufIdxs[i] = (i&3)+0;
5616 for (unsigned i = 0; i != 16; ++i)
5617 ShufIdxs[i] = (i&3)+4;
5620 for (unsigned i = 0; i != 16; ++i)
5621 ShufIdxs[i] = (i&3)+8;
5624 for (unsigned i = 0; i != 16; ++i)
5625 ShufIdxs[i] = (i&3)+12;
5628 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5630 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5632 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5634 EVT VT = OpLHS.getValueType();
5635 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5636 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5637 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5638 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5641 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5642 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5643 /// return the code it can be lowered into. Worst case, it can always be
5644 /// lowered into a vperm.
5645 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5646 SelectionDAG &DAG) const {
5648 SDValue V1 = Op.getOperand(0);
5649 SDValue V2 = Op.getOperand(1);
5650 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5651 EVT VT = Op.getValueType();
5653 // Cases that are handled by instructions that take permute immediates
5654 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5655 // selected by the instruction selector.
5656 if (V2.getOpcode() == ISD::UNDEF) {
5657 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5658 PPC::isSplatShuffleMask(SVOp, 2) ||
5659 PPC::isSplatShuffleMask(SVOp, 4) ||
5660 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5661 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5662 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5663 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5664 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5665 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5666 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5667 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5668 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5673 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5674 // and produce a fixed permutation. If any of these match, do not lower to
5676 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5677 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5678 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5679 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5680 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5681 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5682 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5683 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5684 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5687 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5688 // perfect shuffle table to emit an optimal matching sequence.
5689 ArrayRef<int> PermMask = SVOp->getMask();
5691 unsigned PFIndexes[4];
5692 bool isFourElementShuffle = true;
5693 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5694 unsigned EltNo = 8; // Start out undef.
5695 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5696 if (PermMask[i*4+j] < 0)
5697 continue; // Undef, ignore it.
5699 unsigned ByteSource = PermMask[i*4+j];
5700 if ((ByteSource & 3) != j) {
5701 isFourElementShuffle = false;
5706 EltNo = ByteSource/4;
5707 } else if (EltNo != ByteSource/4) {
5708 isFourElementShuffle = false;
5712 PFIndexes[i] = EltNo;
5715 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5716 // perfect shuffle vector to determine if it is cost effective to do this as
5717 // discrete instructions, or whether we should use a vperm.
5718 if (isFourElementShuffle) {
5719 // Compute the index in the perfect shuffle table.
5720 unsigned PFTableIndex =
5721 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5723 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5724 unsigned Cost = (PFEntry >> 30);
5726 // Determining when to avoid vperm is tricky. Many things affect the cost
5727 // of vperm, particularly how many times the perm mask needs to be computed.
5728 // For example, if the perm mask can be hoisted out of a loop or is already
5729 // used (perhaps because there are multiple permutes with the same shuffle
5730 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5731 // the loop requires an extra register.
5733 // As a compromise, we only emit discrete instructions if the shuffle can be
5734 // generated in 3 or fewer operations. When we have loop information
5735 // available, if this block is within a loop, we should avoid using vperm
5736 // for 3-operation perms and use a constant pool load instead.
5738 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5741 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5742 // vector that will get spilled to the constant pool.
5743 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5745 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5746 // that it is in input element units, not in bytes. Convert now.
5747 EVT EltVT = V1.getValueType().getVectorElementType();
5748 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5750 SmallVector<SDValue, 16> ResultMask;
5751 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5752 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5754 for (unsigned j = 0; j != BytesPerElement; ++j)
5755 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5759 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5760 &ResultMask[0], ResultMask.size());
5761 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5764 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5765 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5766 /// information about the intrinsic.
5767 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5769 unsigned IntrinsicID =
5770 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5773 switch (IntrinsicID) {
5774 default: return false;
5775 // Comparison predicates.
5776 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5777 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5778 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5779 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5780 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5781 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5782 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5783 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5784 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5785 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5786 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5787 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5788 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5790 // Normal Comparisons.
5791 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5792 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5793 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5794 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5795 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5796 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5797 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5798 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5799 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5800 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5801 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5802 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5803 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5808 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5809 /// lower, do it, otherwise return null.
5810 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5811 SelectionDAG &DAG) const {
5812 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5813 // opcode number of the comparison.
5817 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5818 return SDValue(); // Don't custom lower most intrinsics.
5820 // If this is a non-dot comparison, make the VCMP node and we are done.
5822 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5823 Op.getOperand(1), Op.getOperand(2),
5824 DAG.getConstant(CompareOpc, MVT::i32));
5825 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5828 // Create the PPCISD altivec 'dot' comparison node.
5830 Op.getOperand(2), // LHS
5831 Op.getOperand(3), // RHS
5832 DAG.getConstant(CompareOpc, MVT::i32)
5834 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5835 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5837 // Now that we have the comparison, emit a copy from the CR to a GPR.
5838 // This is flagged to the above dot comparison.
5839 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5840 DAG.getRegister(PPC::CR6, MVT::i32),
5841 CompNode.getValue(1));
5843 // Unpack the result based on how the target uses it.
5844 unsigned BitNo; // Bit # of CR6.
5845 bool InvertBit; // Invert result?
5846 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5847 default: // Can't happen, don't crash on invalid number though.
5848 case 0: // Return the value of the EQ bit of CR6.
5849 BitNo = 0; InvertBit = false;
5851 case 1: // Return the inverted value of the EQ bit of CR6.
5852 BitNo = 0; InvertBit = true;
5854 case 2: // Return the value of the LT bit of CR6.
5855 BitNo = 2; InvertBit = false;
5857 case 3: // Return the inverted value of the LT bit of CR6.
5858 BitNo = 2; InvertBit = true;
5862 // Shift the bit into the low position.
5863 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5864 DAG.getConstant(8-(3-BitNo), MVT::i32));
5866 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5867 DAG.getConstant(1, MVT::i32));
5869 // If we are supposed to, toggle the bit.
5871 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5872 DAG.getConstant(1, MVT::i32));
5876 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5877 SelectionDAG &DAG) const {
5879 // Create a stack slot that is 16-byte aligned.
5880 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5881 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5882 EVT PtrVT = getPointerTy();
5883 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5885 // Store the input value into Value#0 of the stack slot.
5886 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5887 Op.getOperand(0), FIdx, MachinePointerInfo(),
5890 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5891 false, false, false, 0);
5894 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5896 if (Op.getValueType() == MVT::v4i32) {
5897 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5899 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5900 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5902 SDValue RHSSwap = // = vrlw RHS, 16
5903 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5905 // Shrinkify inputs to v8i16.
5906 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5907 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5908 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5910 // Low parts multiplied together, generating 32-bit results (we ignore the
5912 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5913 LHS, RHS, DAG, dl, MVT::v4i32);
5915 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5916 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5917 // Shift the high parts up 16 bits.
5918 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5920 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5921 } else if (Op.getValueType() == MVT::v8i16) {
5922 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5924 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5926 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5927 LHS, RHS, Zero, DAG, dl);
5928 } else if (Op.getValueType() == MVT::v16i8) {
5929 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5931 // Multiply the even 8-bit parts, producing 16-bit sums.
5932 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5933 LHS, RHS, DAG, dl, MVT::v8i16);
5934 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5936 // Multiply the odd 8-bit parts, producing 16-bit sums.
5937 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5938 LHS, RHS, DAG, dl, MVT::v8i16);
5939 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5941 // Merge the results together.
5943 for (unsigned i = 0; i != 8; ++i) {
5945 Ops[i*2+1] = 2*i+1+16;
5947 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5949 llvm_unreachable("Unknown mul to lower!");
5953 /// LowerOperation - Provide custom lowering hooks for some operations.
5955 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5956 switch (Op.getOpcode()) {
5957 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5958 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5959 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5960 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5961 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5962 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5963 case ISD::SETCC: return LowerSETCC(Op, DAG);
5964 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5965 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5967 return LowerVASTART(Op, DAG, PPCSubTarget);
5970 return LowerVAARG(Op, DAG, PPCSubTarget);
5973 return LowerVACOPY(Op, DAG, PPCSubTarget);
5975 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5976 case ISD::DYNAMIC_STACKALLOC:
5977 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5979 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5980 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5982 case ISD::LOAD: return LowerLOAD(Op, DAG);
5983 case ISD::STORE: return LowerSTORE(Op, DAG);
5984 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
5985 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5986 case ISD::FP_TO_UINT:
5987 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5989 case ISD::UINT_TO_FP:
5990 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5991 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5993 // Lower 64-bit shifts.
5994 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5995 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5996 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5998 // Vector-related lowering.
5999 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6000 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6001 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6002 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6003 case ISD::MUL: return LowerMUL(Op, DAG);
6005 // For counter-based loop handling.
6006 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6008 // Frame & Return address.
6009 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6010 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6014 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6015 SmallVectorImpl<SDValue>&Results,
6016 SelectionDAG &DAG) const {
6017 const TargetMachine &TM = getTargetMachine();
6019 switch (N->getOpcode()) {
6021 llvm_unreachable("Do not know how to custom type legalize this operation!");
6022 case ISD::INTRINSIC_W_CHAIN: {
6023 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6024 Intrinsic::ppc_is_decremented_ctr_nonzero)
6027 assert(N->getValueType(0) == MVT::i1 &&
6028 "Unexpected result type for CTR decrement intrinsic");
6029 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6030 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6031 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6034 Results.push_back(NewInt);
6035 Results.push_back(NewInt.getValue(1));
6039 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6040 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6043 EVT VT = N->getValueType(0);
6045 if (VT == MVT::i64) {
6046 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6048 Results.push_back(NewNode);
6049 Results.push_back(NewNode.getValue(1));
6053 case ISD::FP_ROUND_INREG: {
6054 assert(N->getValueType(0) == MVT::ppcf128);
6055 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6056 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6057 MVT::f64, N->getOperand(0),
6058 DAG.getIntPtrConstant(0));
6059 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6060 MVT::f64, N->getOperand(0),
6061 DAG.getIntPtrConstant(1));
6063 // Add the two halves of the long double in round-to-zero mode.
6064 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6066 // We know the low half is about to be thrown away, so just use something
6068 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6072 case ISD::FP_TO_SINT:
6073 // LowerFP_TO_INT() can only handle f32 and f64.
6074 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6076 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6082 //===----------------------------------------------------------------------===//
6083 // Other Lowering Code
6084 //===----------------------------------------------------------------------===//
6087 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6088 bool is64bit, unsigned BinOpcode) const {
6089 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6090 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6092 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6093 MachineFunction *F = BB->getParent();
6094 MachineFunction::iterator It = BB;
6097 unsigned dest = MI->getOperand(0).getReg();
6098 unsigned ptrA = MI->getOperand(1).getReg();
6099 unsigned ptrB = MI->getOperand(2).getReg();
6100 unsigned incr = MI->getOperand(3).getReg();
6101 DebugLoc dl = MI->getDebugLoc();
6103 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6104 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6105 F->insert(It, loopMBB);
6106 F->insert(It, exitMBB);
6107 exitMBB->splice(exitMBB->begin(), BB,
6108 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6109 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6111 MachineRegisterInfo &RegInfo = F->getRegInfo();
6112 unsigned TmpReg = (!BinOpcode) ? incr :
6113 RegInfo.createVirtualRegister(
6114 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6115 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6119 // fallthrough --> loopMBB
6120 BB->addSuccessor(loopMBB);
6123 // l[wd]arx dest, ptr
6124 // add r0, dest, incr
6125 // st[wd]cx. r0, ptr
6127 // fallthrough --> exitMBB
6129 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6130 .addReg(ptrA).addReg(ptrB);
6132 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6133 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6134 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6135 BuildMI(BB, dl, TII->get(PPC::BCC))
6136 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6137 BB->addSuccessor(loopMBB);
6138 BB->addSuccessor(exitMBB);
6147 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6148 MachineBasicBlock *BB,
6149 bool is8bit, // operation
6150 unsigned BinOpcode) const {
6151 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6152 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6153 // In 64 bit mode we have to use 64 bits for addresses, even though the
6154 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6155 // registers without caring whether they're 32 or 64, but here we're
6156 // doing actual arithmetic on the addresses.
6157 bool is64bit = PPCSubTarget.isPPC64();
6158 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6160 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6161 MachineFunction *F = BB->getParent();
6162 MachineFunction::iterator It = BB;
6165 unsigned dest = MI->getOperand(0).getReg();
6166 unsigned ptrA = MI->getOperand(1).getReg();
6167 unsigned ptrB = MI->getOperand(2).getReg();
6168 unsigned incr = MI->getOperand(3).getReg();
6169 DebugLoc dl = MI->getDebugLoc();
6171 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6172 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6173 F->insert(It, loopMBB);
6174 F->insert(It, exitMBB);
6175 exitMBB->splice(exitMBB->begin(), BB,
6176 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6177 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6179 MachineRegisterInfo &RegInfo = F->getRegInfo();
6180 const TargetRegisterClass *RC =
6181 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6182 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6183 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6184 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6185 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6186 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6187 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6188 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6189 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6190 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6191 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6192 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6193 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6195 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6199 // fallthrough --> loopMBB
6200 BB->addSuccessor(loopMBB);
6202 // The 4-byte load must be aligned, while a char or short may be
6203 // anywhere in the word. Hence all this nasty bookkeeping code.
6204 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6205 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6206 // xori shift, shift1, 24 [16]
6207 // rlwinm ptr, ptr1, 0, 0, 29
6208 // slw incr2, incr, shift
6209 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6210 // slw mask, mask2, shift
6212 // lwarx tmpDest, ptr
6213 // add tmp, tmpDest, incr2
6214 // andc tmp2, tmpDest, mask
6215 // and tmp3, tmp, mask
6216 // or tmp4, tmp3, tmp2
6219 // fallthrough --> exitMBB
6220 // srw dest, tmpDest, shift
6221 if (ptrA != ZeroReg) {
6222 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6223 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6224 .addReg(ptrA).addReg(ptrB);
6228 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6229 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6230 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6231 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6233 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6234 .addReg(Ptr1Reg).addImm(0).addImm(61);
6236 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6237 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6238 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6239 .addReg(incr).addReg(ShiftReg);
6241 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6243 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6244 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6246 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6247 .addReg(Mask2Reg).addReg(ShiftReg);
6250 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6251 .addReg(ZeroReg).addReg(PtrReg);
6253 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6254 .addReg(Incr2Reg).addReg(TmpDestReg);
6255 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6256 .addReg(TmpDestReg).addReg(MaskReg);
6257 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6258 .addReg(TmpReg).addReg(MaskReg);
6259 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6260 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6261 BuildMI(BB, dl, TII->get(PPC::STWCX))
6262 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6263 BuildMI(BB, dl, TII->get(PPC::BCC))
6264 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6265 BB->addSuccessor(loopMBB);
6266 BB->addSuccessor(exitMBB);
6271 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6276 llvm::MachineBasicBlock*
6277 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6278 MachineBasicBlock *MBB) const {
6279 DebugLoc DL = MI->getDebugLoc();
6280 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6282 MachineFunction *MF = MBB->getParent();
6283 MachineRegisterInfo &MRI = MF->getRegInfo();
6285 const BasicBlock *BB = MBB->getBasicBlock();
6286 MachineFunction::iterator I = MBB;
6290 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6291 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6293 unsigned DstReg = MI->getOperand(0).getReg();
6294 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6295 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6296 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6297 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6299 MVT PVT = getPointerTy();
6300 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6301 "Invalid Pointer Size!");
6302 // For v = setjmp(buf), we generate
6305 // SjLjSetup mainMBB
6311 // buf[LabelOffset] = LR
6315 // v = phi(main, restore)
6318 MachineBasicBlock *thisMBB = MBB;
6319 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6320 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6321 MF->insert(I, mainMBB);
6322 MF->insert(I, sinkMBB);
6324 MachineInstrBuilder MIB;
6326 // Transfer the remainder of BB and its successor edges to sinkMBB.
6327 sinkMBB->splice(sinkMBB->begin(), MBB,
6328 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6329 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6331 // Note that the structure of the jmp_buf used here is not compatible
6332 // with that used by libc, and is not designed to be. Specifically, it
6333 // stores only those 'reserved' registers that LLVM does not otherwise
6334 // understand how to spill. Also, by convention, by the time this
6335 // intrinsic is called, Clang has already stored the frame address in the
6336 // first slot of the buffer and stack address in the third. Following the
6337 // X86 target code, we'll store the jump address in the second slot. We also
6338 // need to save the TOC pointer (R2) to handle jumps between shared
6339 // libraries, and that will be stored in the fourth slot. The thread
6340 // identifier (R13) is not affected.
6343 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6344 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6345 const int64_t BPOffset = 4 * PVT.getStoreSize();
6347 // Prepare IP either in reg.
6348 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6349 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6350 unsigned BufReg = MI->getOperand(1).getReg();
6352 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6353 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6357 MIB.setMemRefs(MMOBegin, MMOEnd);
6360 // Naked functions never have a base pointer, and so we use r1. For all
6361 // other functions, this decision must be delayed until during PEI.
6363 if (MF->getFunction()->getAttributes().hasAttribute(
6364 AttributeSet::FunctionIndex, Attribute::Naked))
6365 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6367 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6369 MIB = BuildMI(*thisMBB, MI, DL,
6370 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6374 MIB.setMemRefs(MMOBegin, MMOEnd);
6377 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6378 const PPCRegisterInfo *TRI =
6379 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6380 MIB.addRegMask(TRI->getNoPreservedMask());
6382 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6384 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6386 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6388 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6389 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6393 MIB = BuildMI(mainMBB, DL,
6394 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6397 if (PPCSubTarget.isPPC64()) {
6398 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6400 .addImm(LabelOffset)
6403 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6405 .addImm(LabelOffset)
6409 MIB.setMemRefs(MMOBegin, MMOEnd);
6411 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6412 mainMBB->addSuccessor(sinkMBB);
6415 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6416 TII->get(PPC::PHI), DstReg)
6417 .addReg(mainDstReg).addMBB(mainMBB)
6418 .addReg(restoreDstReg).addMBB(thisMBB);
6420 MI->eraseFromParent();
6425 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6426 MachineBasicBlock *MBB) const {
6427 DebugLoc DL = MI->getDebugLoc();
6428 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6430 MachineFunction *MF = MBB->getParent();
6431 MachineRegisterInfo &MRI = MF->getRegInfo();
6434 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6435 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6437 MVT PVT = getPointerTy();
6438 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6439 "Invalid Pointer Size!");
6441 const TargetRegisterClass *RC =
6442 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6443 unsigned Tmp = MRI.createVirtualRegister(RC);
6444 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6445 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6446 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6447 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6449 MachineInstrBuilder MIB;
6451 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6452 const int64_t SPOffset = 2 * PVT.getStoreSize();
6453 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6454 const int64_t BPOffset = 4 * PVT.getStoreSize();
6456 unsigned BufReg = MI->getOperand(0).getReg();
6458 // Reload FP (the jumped-to function may not have had a
6459 // frame pointer, and if so, then its r31 will be restored
6461 if (PVT == MVT::i64) {
6462 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6466 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6470 MIB.setMemRefs(MMOBegin, MMOEnd);
6473 if (PVT == MVT::i64) {
6474 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6475 .addImm(LabelOffset)
6478 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6479 .addImm(LabelOffset)
6482 MIB.setMemRefs(MMOBegin, MMOEnd);
6485 if (PVT == MVT::i64) {
6486 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6490 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6494 MIB.setMemRefs(MMOBegin, MMOEnd);
6497 if (PVT == MVT::i64) {
6498 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6502 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6506 MIB.setMemRefs(MMOBegin, MMOEnd);
6509 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6510 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6514 MIB.setMemRefs(MMOBegin, MMOEnd);
6518 BuildMI(*MBB, MI, DL,
6519 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6520 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6522 MI->eraseFromParent();
6527 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6528 MachineBasicBlock *BB) const {
6529 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6530 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6531 return emitEHSjLjSetJmp(MI, BB);
6532 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6533 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6534 return emitEHSjLjLongJmp(MI, BB);
6537 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6539 // To "insert" these instructions we actually have to insert their
6540 // control-flow patterns.
6541 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6542 MachineFunction::iterator It = BB;
6545 MachineFunction *F = BB->getParent();
6547 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6548 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6549 MI->getOpcode() == PPC::SELECT_I4 ||
6550 MI->getOpcode() == PPC::SELECT_I8)) {
6551 SmallVector<MachineOperand, 2> Cond;
6552 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6553 MI->getOpcode() == PPC::SELECT_CC_I8)
6554 Cond.push_back(MI->getOperand(4));
6556 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6557 Cond.push_back(MI->getOperand(1));
6559 DebugLoc dl = MI->getDebugLoc();
6560 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6561 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6562 Cond, MI->getOperand(2).getReg(),
6563 MI->getOperand(3).getReg());
6564 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6565 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6566 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6567 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6568 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6569 MI->getOpcode() == PPC::SELECT_I4 ||
6570 MI->getOpcode() == PPC::SELECT_I8 ||
6571 MI->getOpcode() == PPC::SELECT_F4 ||
6572 MI->getOpcode() == PPC::SELECT_F8 ||
6573 MI->getOpcode() == PPC::SELECT_VRRC) {
6574 // The incoming instruction knows the destination vreg to set, the
6575 // condition code register to branch on, the true/false values to
6576 // select between, and a branch opcode to use.
6581 // cmpTY ccX, r1, r2
6583 // fallthrough --> copy0MBB
6584 MachineBasicBlock *thisMBB = BB;
6585 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6586 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6587 DebugLoc dl = MI->getDebugLoc();
6588 F->insert(It, copy0MBB);
6589 F->insert(It, sinkMBB);
6591 // Transfer the remainder of BB and its successor edges to sinkMBB.
6592 sinkMBB->splice(sinkMBB->begin(), BB,
6593 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6594 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6596 // Next, add the true and fallthrough blocks as its successors.
6597 BB->addSuccessor(copy0MBB);
6598 BB->addSuccessor(sinkMBB);
6600 if (MI->getOpcode() == PPC::SELECT_I4 ||
6601 MI->getOpcode() == PPC::SELECT_I8 ||
6602 MI->getOpcode() == PPC::SELECT_F4 ||
6603 MI->getOpcode() == PPC::SELECT_F8 ||
6604 MI->getOpcode() == PPC::SELECT_VRRC) {
6605 BuildMI(BB, dl, TII->get(PPC::BC))
6606 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6608 unsigned SelectPred = MI->getOperand(4).getImm();
6609 BuildMI(BB, dl, TII->get(PPC::BCC))
6610 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6614 // %FalseValue = ...
6615 // # fallthrough to sinkMBB
6618 // Update machine-CFG edges
6619 BB->addSuccessor(sinkMBB);
6622 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6625 BuildMI(*BB, BB->begin(), dl,
6626 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6627 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6628 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6630 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6631 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6632 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6633 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6634 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6635 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6636 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6637 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6639 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6640 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6641 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6642 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6643 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6644 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6645 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6646 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6648 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6649 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6650 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6651 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6652 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6653 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6654 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6655 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6657 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6658 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6659 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6660 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6661 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6662 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6663 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6664 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6666 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6667 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6668 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6669 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6670 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6671 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6672 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6673 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6675 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6676 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6677 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6678 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6679 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6680 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6681 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6682 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6684 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6685 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6686 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6687 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6688 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6689 BB = EmitAtomicBinary(MI, BB, false, 0);
6690 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6691 BB = EmitAtomicBinary(MI, BB, true, 0);
6693 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6694 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6695 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6697 unsigned dest = MI->getOperand(0).getReg();
6698 unsigned ptrA = MI->getOperand(1).getReg();
6699 unsigned ptrB = MI->getOperand(2).getReg();
6700 unsigned oldval = MI->getOperand(3).getReg();
6701 unsigned newval = MI->getOperand(4).getReg();
6702 DebugLoc dl = MI->getDebugLoc();
6704 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6705 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6706 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6707 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6708 F->insert(It, loop1MBB);
6709 F->insert(It, loop2MBB);
6710 F->insert(It, midMBB);
6711 F->insert(It, exitMBB);
6712 exitMBB->splice(exitMBB->begin(), BB,
6713 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6714 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6718 // fallthrough --> loopMBB
6719 BB->addSuccessor(loop1MBB);
6722 // l[wd]arx dest, ptr
6723 // cmp[wd] dest, oldval
6726 // st[wd]cx. newval, ptr
6730 // st[wd]cx. dest, ptr
6733 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6734 .addReg(ptrA).addReg(ptrB);
6735 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6736 .addReg(oldval).addReg(dest);
6737 BuildMI(BB, dl, TII->get(PPC::BCC))
6738 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6739 BB->addSuccessor(loop2MBB);
6740 BB->addSuccessor(midMBB);
6743 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6744 .addReg(newval).addReg(ptrA).addReg(ptrB);
6745 BuildMI(BB, dl, TII->get(PPC::BCC))
6746 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6747 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6748 BB->addSuccessor(loop1MBB);
6749 BB->addSuccessor(exitMBB);
6752 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6753 .addReg(dest).addReg(ptrA).addReg(ptrB);
6754 BB->addSuccessor(exitMBB);
6759 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6760 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6761 // We must use 64-bit registers for addresses when targeting 64-bit,
6762 // since we're actually doing arithmetic on them. Other registers
6764 bool is64bit = PPCSubTarget.isPPC64();
6765 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6767 unsigned dest = MI->getOperand(0).getReg();
6768 unsigned ptrA = MI->getOperand(1).getReg();
6769 unsigned ptrB = MI->getOperand(2).getReg();
6770 unsigned oldval = MI->getOperand(3).getReg();
6771 unsigned newval = MI->getOperand(4).getReg();
6772 DebugLoc dl = MI->getDebugLoc();
6774 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6775 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6776 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6777 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6778 F->insert(It, loop1MBB);
6779 F->insert(It, loop2MBB);
6780 F->insert(It, midMBB);
6781 F->insert(It, exitMBB);
6782 exitMBB->splice(exitMBB->begin(), BB,
6783 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6784 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6786 MachineRegisterInfo &RegInfo = F->getRegInfo();
6787 const TargetRegisterClass *RC =
6788 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6789 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6790 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6791 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6792 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6793 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6794 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6795 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6796 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6797 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6798 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6799 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6800 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6801 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6802 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6804 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6805 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6808 // fallthrough --> loopMBB
6809 BB->addSuccessor(loop1MBB);
6811 // The 4-byte load must be aligned, while a char or short may be
6812 // anywhere in the word. Hence all this nasty bookkeeping code.
6813 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6814 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6815 // xori shift, shift1, 24 [16]
6816 // rlwinm ptr, ptr1, 0, 0, 29
6817 // slw newval2, newval, shift
6818 // slw oldval2, oldval,shift
6819 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6820 // slw mask, mask2, shift
6821 // and newval3, newval2, mask
6822 // and oldval3, oldval2, mask
6824 // lwarx tmpDest, ptr
6825 // and tmp, tmpDest, mask
6826 // cmpw tmp, oldval3
6829 // andc tmp2, tmpDest, mask
6830 // or tmp4, tmp2, newval3
6835 // stwcx. tmpDest, ptr
6837 // srw dest, tmpDest, shift
6838 if (ptrA != ZeroReg) {
6839 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6840 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6841 .addReg(ptrA).addReg(ptrB);
6845 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6846 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6847 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6848 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6850 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6851 .addReg(Ptr1Reg).addImm(0).addImm(61);
6853 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6854 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6855 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6856 .addReg(newval).addReg(ShiftReg);
6857 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6858 .addReg(oldval).addReg(ShiftReg);
6860 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6862 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6863 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6864 .addReg(Mask3Reg).addImm(65535);
6866 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6867 .addReg(Mask2Reg).addReg(ShiftReg);
6868 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6869 .addReg(NewVal2Reg).addReg(MaskReg);
6870 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6871 .addReg(OldVal2Reg).addReg(MaskReg);
6874 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6875 .addReg(ZeroReg).addReg(PtrReg);
6876 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6877 .addReg(TmpDestReg).addReg(MaskReg);
6878 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6879 .addReg(TmpReg).addReg(OldVal3Reg);
6880 BuildMI(BB, dl, TII->get(PPC::BCC))
6881 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6882 BB->addSuccessor(loop2MBB);
6883 BB->addSuccessor(midMBB);
6886 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6887 .addReg(TmpDestReg).addReg(MaskReg);
6888 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6889 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6890 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6891 .addReg(ZeroReg).addReg(PtrReg);
6892 BuildMI(BB, dl, TII->get(PPC::BCC))
6893 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6894 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6895 BB->addSuccessor(loop1MBB);
6896 BB->addSuccessor(exitMBB);
6899 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6900 .addReg(ZeroReg).addReg(PtrReg);
6901 BB->addSuccessor(exitMBB);
6906 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6908 } else if (MI->getOpcode() == PPC::FADDrtz) {
6909 // This pseudo performs an FADD with rounding mode temporarily forced
6910 // to round-to-zero. We emit this via custom inserter since the FPSCR
6911 // is not modeled at the SelectionDAG level.
6912 unsigned Dest = MI->getOperand(0).getReg();
6913 unsigned Src1 = MI->getOperand(1).getReg();
6914 unsigned Src2 = MI->getOperand(2).getReg();
6915 DebugLoc dl = MI->getDebugLoc();
6917 MachineRegisterInfo &RegInfo = F->getRegInfo();
6918 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6920 // Save FPSCR value.
6921 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6923 // Set rounding mode to round-to-zero.
6924 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6925 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6927 // Perform addition.
6928 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6930 // Restore FPSCR value.
6931 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6932 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6933 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6934 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6935 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6936 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6937 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6938 PPC::ANDIo8 : PPC::ANDIo;
6939 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6940 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6942 MachineRegisterInfo &RegInfo = F->getRegInfo();
6943 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6944 &PPC::GPRCRegClass :
6945 &PPC::G8RCRegClass);
6947 DebugLoc dl = MI->getDebugLoc();
6948 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6949 .addReg(MI->getOperand(1).getReg()).addImm(1);
6950 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6951 MI->getOperand(0).getReg())
6952 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6954 llvm_unreachable("Unexpected instr type to insert");
6957 MI->eraseFromParent(); // The pseudo instruction is gone now.
6961 //===----------------------------------------------------------------------===//
6962 // Target Optimization Hooks
6963 //===----------------------------------------------------------------------===//
6965 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6966 DAGCombinerInfo &DCI) const {
6967 if (DCI.isAfterLegalizeVectorOps())
6970 EVT VT = Op.getValueType();
6972 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6973 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6974 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
6975 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
6977 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6978 // For the reciprocal, we need to find the zero of the function:
6979 // F(X) = A X - 1 [which has a zero at X = 1/A]
6981 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6982 // does not require additional intermediate precision]
6984 // Convergence is quadratic, so we essentially double the number of digits
6985 // correct after every iteration. The minimum architected relative
6986 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6987 // 23 digits and double has 52 digits.
6988 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6989 if (VT.getScalarType() == MVT::f64)
6992 SelectionDAG &DAG = DCI.DAG;
6996 DAG.getConstantFP(1.0, VT.getScalarType());
6997 if (VT.isVector()) {
6998 assert(VT.getVectorNumElements() == 4 &&
6999 "Unknown vector type");
7000 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7001 FPOne, FPOne, FPOne, FPOne);
7004 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7005 DCI.AddToWorklist(Est.getNode());
7007 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7008 for (int i = 0; i < Iterations; ++i) {
7009 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7010 DCI.AddToWorklist(NewEst.getNode());
7012 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7013 DCI.AddToWorklist(NewEst.getNode());
7015 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7016 DCI.AddToWorklist(NewEst.getNode());
7018 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7019 DCI.AddToWorklist(Est.getNode());
7028 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7029 DAGCombinerInfo &DCI) const {
7030 if (DCI.isAfterLegalizeVectorOps())
7033 EVT VT = Op.getValueType();
7035 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7036 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7037 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7038 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7040 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7041 // For the reciprocal sqrt, we need to find the zero of the function:
7042 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7044 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7045 // As a result, we precompute A/2 prior to the iteration loop.
7047 // Convergence is quadratic, so we essentially double the number of digits
7048 // correct after every iteration. The minimum architected relative
7049 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7050 // 23 digits and double has 52 digits.
7051 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7052 if (VT.getScalarType() == MVT::f64)
7055 SelectionDAG &DAG = DCI.DAG;
7058 SDValue FPThreeHalves =
7059 DAG.getConstantFP(1.5, VT.getScalarType());
7060 if (VT.isVector()) {
7061 assert(VT.getVectorNumElements() == 4 &&
7062 "Unknown vector type");
7063 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7064 FPThreeHalves, FPThreeHalves,
7065 FPThreeHalves, FPThreeHalves);
7068 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7069 DCI.AddToWorklist(Est.getNode());
7071 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7072 // this entire sequence requires only one FP constant.
7073 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7074 DCI.AddToWorklist(HalfArg.getNode());
7076 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7077 DCI.AddToWorklist(HalfArg.getNode());
7079 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7080 for (int i = 0; i < Iterations; ++i) {
7081 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7082 DCI.AddToWorklist(NewEst.getNode());
7084 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7085 DCI.AddToWorklist(NewEst.getNode());
7087 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7088 DCI.AddToWorklist(NewEst.getNode());
7090 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7091 DCI.AddToWorklist(Est.getNode());
7100 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7101 // not enforce equality of the chain operands.
7102 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7103 unsigned Bytes, int Dist,
7104 SelectionDAG &DAG) {
7105 EVT VT = LS->getMemoryVT();
7106 if (VT.getSizeInBits() / 8 != Bytes)
7109 SDValue Loc = LS->getBasePtr();
7110 SDValue BaseLoc = Base->getBasePtr();
7111 if (Loc.getOpcode() == ISD::FrameIndex) {
7112 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7114 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7115 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7116 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7117 int FS = MFI->getObjectSize(FI);
7118 int BFS = MFI->getObjectSize(BFI);
7119 if (FS != BFS || FS != (int)Bytes) return false;
7120 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7124 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7125 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7129 const GlobalValue *GV1 = NULL;
7130 const GlobalValue *GV2 = NULL;
7131 int64_t Offset1 = 0;
7132 int64_t Offset2 = 0;
7133 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7134 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7135 if (isGA1 && isGA2 && GV1 == GV2)
7136 return Offset1 == (Offset2 + Dist*Bytes);
7140 // Return true is there is a nearyby consecutive load to the one provided
7141 // (regardless of alignment). We search up and down the chain, looking though
7142 // token factors and other loads (but nothing else). As a result, a true
7143 // results indicates that it is safe to create a new consecutive load adjacent
7144 // to the load provided.
7145 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7146 SDValue Chain = LD->getChain();
7147 EVT VT = LD->getMemoryVT();
7149 SmallSet<SDNode *, 16> LoadRoots;
7150 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7151 SmallSet<SDNode *, 16> Visited;
7153 // First, search up the chain, branching to follow all token-factor operands.
7154 // If we find a consecutive load, then we're done, otherwise, record all
7155 // nodes just above the top-level loads and token factors.
7156 while (!Queue.empty()) {
7157 SDNode *ChainNext = Queue.pop_back_val();
7158 if (!Visited.insert(ChainNext))
7161 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7162 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7165 if (!Visited.count(ChainLD->getChain().getNode()))
7166 Queue.push_back(ChainLD->getChain().getNode());
7167 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7168 for (SDNode::op_iterator O = ChainNext->op_begin(),
7169 OE = ChainNext->op_end(); O != OE; ++O)
7170 if (!Visited.count(O->getNode()))
7171 Queue.push_back(O->getNode());
7173 LoadRoots.insert(ChainNext);
7176 // Second, search down the chain, starting from the top-level nodes recorded
7177 // in the first phase. These top-level nodes are the nodes just above all
7178 // loads and token factors. Starting with their uses, recursively look though
7179 // all loads (just the chain uses) and token factors to find a consecutive
7184 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7185 IE = LoadRoots.end(); I != IE; ++I) {
7186 Queue.push_back(*I);
7188 while (!Queue.empty()) {
7189 SDNode *LoadRoot = Queue.pop_back_val();
7190 if (!Visited.insert(LoadRoot))
7193 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7194 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7197 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7198 UE = LoadRoot->use_end(); UI != UE; ++UI)
7199 if (((isa<LoadSDNode>(*UI) &&
7200 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7201 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7202 Queue.push_back(*UI);
7209 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7210 DAGCombinerInfo &DCI) const {
7211 SelectionDAG &DAG = DCI.DAG;
7214 assert(PPCSubTarget.useCRBits() &&
7215 "Expecting to be tracking CR bits");
7216 // If we're tracking CR bits, we need to be careful that we don't have:
7217 // trunc(binary-ops(zext(x), zext(y)))
7219 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7220 // such that we're unnecessarily moving things into GPRs when it would be
7221 // better to keep them in CR bits.
7223 // Note that trunc here can be an actual i1 trunc, or can be the effective
7224 // truncation that comes from a setcc or select_cc.
7225 if (N->getOpcode() == ISD::TRUNCATE &&
7226 N->getValueType(0) != MVT::i1)
7229 if (N->getOperand(0).getValueType() != MVT::i32 &&
7230 N->getOperand(0).getValueType() != MVT::i64)
7233 if (N->getOpcode() == ISD::SETCC ||
7234 N->getOpcode() == ISD::SELECT_CC) {
7235 // If we're looking at a comparison, then we need to make sure that the
7236 // high bits (all except for the first) don't matter the result.
7238 cast<CondCodeSDNode>(N->getOperand(
7239 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7240 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7242 if (ISD::isSignedIntSetCC(CC)) {
7243 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7244 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7246 } else if (ISD::isUnsignedIntSetCC(CC)) {
7247 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7248 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7249 !DAG.MaskedValueIsZero(N->getOperand(1),
7250 APInt::getHighBitsSet(OpBits, OpBits-1)))
7253 // This is neither a signed nor an unsigned comparison, just make sure
7254 // that the high bits are equal.
7255 APInt Op1Zero, Op1One;
7256 APInt Op2Zero, Op2One;
7257 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7258 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7260 // We don't really care about what is known about the first bit (if
7261 // anything), so clear it in all masks prior to comparing them.
7262 Op1Zero.clearBit(0); Op1One.clearBit(0);
7263 Op2Zero.clearBit(0); Op2One.clearBit(0);
7265 if (Op1Zero != Op2Zero || Op1One != Op2One)
7270 // We now know that the higher-order bits are irrelevant, we just need to
7271 // make sure that all of the intermediate operations are bit operations, and
7272 // all inputs are extensions.
7273 if (N->getOperand(0).getOpcode() != ISD::AND &&
7274 N->getOperand(0).getOpcode() != ISD::OR &&
7275 N->getOperand(0).getOpcode() != ISD::XOR &&
7276 N->getOperand(0).getOpcode() != ISD::SELECT &&
7277 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7278 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7279 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7280 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7281 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7284 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7285 N->getOperand(1).getOpcode() != ISD::AND &&
7286 N->getOperand(1).getOpcode() != ISD::OR &&
7287 N->getOperand(1).getOpcode() != ISD::XOR &&
7288 N->getOperand(1).getOpcode() != ISD::SELECT &&
7289 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7290 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7291 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7292 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7293 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7296 SmallVector<SDValue, 4> Inputs;
7297 SmallVector<SDValue, 8> BinOps, PromOps;
7298 SmallPtrSet<SDNode *, 16> Visited;
7300 for (unsigned i = 0; i < 2; ++i) {
7301 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7302 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7303 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7304 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7305 isa<ConstantSDNode>(N->getOperand(i)))
7306 Inputs.push_back(N->getOperand(i));
7308 BinOps.push_back(N->getOperand(i));
7310 if (N->getOpcode() == ISD::TRUNCATE)
7314 // Visit all inputs, collect all binary operations (and, or, xor and
7315 // select) that are all fed by extensions.
7316 while (!BinOps.empty()) {
7317 SDValue BinOp = BinOps.back();
7320 if (!Visited.insert(BinOp.getNode()))
7323 PromOps.push_back(BinOp);
7325 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7326 // The condition of the select is not promoted.
7327 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7329 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7332 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7333 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7334 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7335 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7336 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7337 Inputs.push_back(BinOp.getOperand(i));
7338 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7339 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7340 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7341 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7342 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7343 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7344 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7345 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7346 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7347 BinOps.push_back(BinOp.getOperand(i));
7349 // We have an input that is not an extension or another binary
7350 // operation; we'll abort this transformation.
7356 // Make sure that this is a self-contained cluster of operations (which
7357 // is not quite the same thing as saying that everything has only one
7359 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7360 if (isa<ConstantSDNode>(Inputs[i]))
7363 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7364 UE = Inputs[i].getNode()->use_end();
7367 if (User != N && !Visited.count(User))
7370 // Make sure that we're not going to promote the non-output-value
7371 // operand(s) or SELECT or SELECT_CC.
7372 // FIXME: Although we could sometimes handle this, and it does occur in
7373 // practice that one of the condition inputs to the select is also one of
7374 // the outputs, we currently can't deal with this.
7375 if (User->getOpcode() == ISD::SELECT) {
7376 if (User->getOperand(0) == Inputs[i])
7378 } else if (User->getOpcode() == ISD::SELECT_CC) {
7379 if (User->getOperand(0) == Inputs[i] ||
7380 User->getOperand(1) == Inputs[i])
7386 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7387 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7388 UE = PromOps[i].getNode()->use_end();
7391 if (User != N && !Visited.count(User))
7394 // Make sure that we're not going to promote the non-output-value
7395 // operand(s) or SELECT or SELECT_CC.
7396 // FIXME: Although we could sometimes handle this, and it does occur in
7397 // practice that one of the condition inputs to the select is also one of
7398 // the outputs, we currently can't deal with this.
7399 if (User->getOpcode() == ISD::SELECT) {
7400 if (User->getOperand(0) == PromOps[i])
7402 } else if (User->getOpcode() == ISD::SELECT_CC) {
7403 if (User->getOperand(0) == PromOps[i] ||
7404 User->getOperand(1) == PromOps[i])
7410 // Replace all inputs with the extension operand.
7411 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7412 // Constants may have users outside the cluster of to-be-promoted nodes,
7413 // and so we need to replace those as we do the promotions.
7414 if (isa<ConstantSDNode>(Inputs[i]))
7417 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7420 // Replace all operations (these are all the same, but have a different
7421 // (i1) return type). DAG.getNode will validate that the types of
7422 // a binary operator match, so go through the list in reverse so that
7423 // we've likely promoted both operands first. Any intermediate truncations or
7424 // extensions disappear.
7425 while (!PromOps.empty()) {
7426 SDValue PromOp = PromOps.back();
7429 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7430 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7431 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7432 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7433 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7434 PromOp.getOperand(0).getValueType() != MVT::i1) {
7435 // The operand is not yet ready (see comment below).
7436 PromOps.insert(PromOps.begin(), PromOp);
7440 SDValue RepValue = PromOp.getOperand(0);
7441 if (isa<ConstantSDNode>(RepValue))
7442 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7444 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7449 switch (PromOp.getOpcode()) {
7450 default: C = 0; break;
7451 case ISD::SELECT: C = 1; break;
7452 case ISD::SELECT_CC: C = 2; break;
7455 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7456 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7457 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7458 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7459 // The to-be-promoted operands of this node have not yet been
7460 // promoted (this should be rare because we're going through the
7461 // list backward, but if one of the operands has several users in
7462 // this cluster of to-be-promoted nodes, it is possible).
7463 PromOps.insert(PromOps.begin(), PromOp);
7467 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7468 PromOp.getNode()->op_end());
7470 // If there are any constant inputs, make sure they're replaced now.
7471 for (unsigned i = 0; i < 2; ++i)
7472 if (isa<ConstantSDNode>(Ops[C+i]))
7473 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7475 DAG.ReplaceAllUsesOfValueWith(PromOp,
7476 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7477 Ops.data(), Ops.size()));
7480 // Now we're left with the initial truncation itself.
7481 if (N->getOpcode() == ISD::TRUNCATE)
7482 return N->getOperand(0);
7484 // Otherwise, this is a comparison. The operands to be compared have just
7485 // changed type (to i1), but everything else is the same.
7486 return SDValue(N, 0);
7489 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7490 DAGCombinerInfo &DCI) const {
7491 SelectionDAG &DAG = DCI.DAG;
7494 // If we're tracking CR bits, we need to be careful that we don't have:
7495 // zext(binary-ops(trunc(x), trunc(y)))
7497 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7498 // such that we're unnecessarily moving things into CR bits that can more
7499 // efficiently stay in GPRs. Note that if we're not certain that the high
7500 // bits are set as required by the final extension, we still may need to do
7501 // some masking to get the proper behavior.
7503 // This same functionality is important on PPC64 when dealing with
7504 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7505 // the return values of functions. Because it is so similar, it is handled
7508 if (N->getValueType(0) != MVT::i32 &&
7509 N->getValueType(0) != MVT::i64)
7512 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7513 PPCSubTarget.useCRBits()) ||
7514 (N->getOperand(0).getValueType() == MVT::i32 &&
7515 PPCSubTarget.isPPC64())))
7518 if (N->getOperand(0).getOpcode() != ISD::AND &&
7519 N->getOperand(0).getOpcode() != ISD::OR &&
7520 N->getOperand(0).getOpcode() != ISD::XOR &&
7521 N->getOperand(0).getOpcode() != ISD::SELECT &&
7522 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7525 SmallVector<SDValue, 4> Inputs;
7526 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7527 SmallPtrSet<SDNode *, 16> Visited;
7529 // Visit all inputs, collect all binary operations (and, or, xor and
7530 // select) that are all fed by truncations.
7531 while (!BinOps.empty()) {
7532 SDValue BinOp = BinOps.back();
7535 if (!Visited.insert(BinOp.getNode()))
7538 PromOps.push_back(BinOp);
7540 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7541 // The condition of the select is not promoted.
7542 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7544 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7547 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7548 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7549 Inputs.push_back(BinOp.getOperand(i));
7550 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7551 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7552 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7553 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7554 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7555 BinOps.push_back(BinOp.getOperand(i));
7557 // We have an input that is not a truncation or another binary
7558 // operation; we'll abort this transformation.
7564 // Make sure that this is a self-contained cluster of operations (which
7565 // is not quite the same thing as saying that everything has only one
7567 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7568 if (isa<ConstantSDNode>(Inputs[i]))
7571 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7572 UE = Inputs[i].getNode()->use_end();
7575 if (User != N && !Visited.count(User))
7578 // Make sure that we're not going to promote the non-output-value
7579 // operand(s) or SELECT or SELECT_CC.
7580 // FIXME: Although we could sometimes handle this, and it does occur in
7581 // practice that one of the condition inputs to the select is also one of
7582 // the outputs, we currently can't deal with this.
7583 if (User->getOpcode() == ISD::SELECT) {
7584 if (User->getOperand(0) == Inputs[i])
7586 } else if (User->getOpcode() == ISD::SELECT_CC) {
7587 if (User->getOperand(0) == Inputs[i] ||
7588 User->getOperand(1) == Inputs[i])
7594 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7595 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7596 UE = PromOps[i].getNode()->use_end();
7599 if (User != N && !Visited.count(User))
7602 // Make sure that we're not going to promote the non-output-value
7603 // operand(s) or SELECT or SELECT_CC.
7604 // FIXME: Although we could sometimes handle this, and it does occur in
7605 // practice that one of the condition inputs to the select is also one of
7606 // the outputs, we currently can't deal with this.
7607 if (User->getOpcode() == ISD::SELECT) {
7608 if (User->getOperand(0) == PromOps[i])
7610 } else if (User->getOpcode() == ISD::SELECT_CC) {
7611 if (User->getOperand(0) == PromOps[i] ||
7612 User->getOperand(1) == PromOps[i])
7618 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7619 bool ReallyNeedsExt = false;
7620 if (N->getOpcode() != ISD::ANY_EXTEND) {
7621 // If all of the inputs are not already sign/zero extended, then
7622 // we'll still need to do that at the end.
7623 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7624 if (isa<ConstantSDNode>(Inputs[i]))
7628 Inputs[i].getOperand(0).getValueSizeInBits();
7629 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7631 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7632 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7633 APInt::getHighBitsSet(OpBits,
7634 OpBits-PromBits))) ||
7635 (N->getOpcode() == ISD::SIGN_EXTEND &&
7636 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7637 (OpBits-(PromBits-1)))) {
7638 ReallyNeedsExt = true;
7644 // Replace all inputs, either with the truncation operand, or a
7645 // truncation or extension to the final output type.
7646 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7647 // Constant inputs need to be replaced with the to-be-promoted nodes that
7648 // use them because they might have users outside of the cluster of
7650 if (isa<ConstantSDNode>(Inputs[i]))
7653 SDValue InSrc = Inputs[i].getOperand(0);
7654 if (Inputs[i].getValueType() == N->getValueType(0))
7655 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7656 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7657 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7658 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7659 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7660 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7661 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7663 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7664 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7667 // Replace all operations (these are all the same, but have a different
7668 // (promoted) return type). DAG.getNode will validate that the types of
7669 // a binary operator match, so go through the list in reverse so that
7670 // we've likely promoted both operands first.
7671 while (!PromOps.empty()) {
7672 SDValue PromOp = PromOps.back();
7676 switch (PromOp.getOpcode()) {
7677 default: C = 0; break;
7678 case ISD::SELECT: C = 1; break;
7679 case ISD::SELECT_CC: C = 2; break;
7682 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7683 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7684 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7685 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7686 // The to-be-promoted operands of this node have not yet been
7687 // promoted (this should be rare because we're going through the
7688 // list backward, but if one of the operands has several users in
7689 // this cluster of to-be-promoted nodes, it is possible).
7690 PromOps.insert(PromOps.begin(), PromOp);
7694 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7695 PromOp.getNode()->op_end());
7697 // If this node has constant inputs, then they'll need to be promoted here.
7698 for (unsigned i = 0; i < 2; ++i) {
7699 if (!isa<ConstantSDNode>(Ops[C+i]))
7701 if (Ops[C+i].getValueType() == N->getValueType(0))
7704 if (N->getOpcode() == ISD::SIGN_EXTEND)
7705 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7706 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7707 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7709 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7712 DAG.ReplaceAllUsesOfValueWith(PromOp,
7713 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7714 Ops.data(), Ops.size()));
7717 // Now we're left with the initial extension itself.
7718 if (!ReallyNeedsExt)
7719 return N->getOperand(0);
7721 // To zero extend, just mask off everything except for the first bit (in the
7723 if (N->getOpcode() == ISD::ZERO_EXTEND)
7724 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7725 DAG.getConstant(APInt::getLowBitsSet(
7726 N->getValueSizeInBits(0), PromBits),
7727 N->getValueType(0)));
7729 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7730 "Invalid extension type");
7731 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7733 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7734 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7735 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7736 N->getOperand(0), ShiftCst), ShiftCst);
7739 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7740 DAGCombinerInfo &DCI) const {
7741 const TargetMachine &TM = getTargetMachine();
7742 SelectionDAG &DAG = DCI.DAG;
7744 switch (N->getOpcode()) {
7747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7748 if (C->isNullValue()) // 0 << V -> 0.
7749 return N->getOperand(0);
7753 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7754 if (C->isNullValue()) // 0 >>u V -> 0.
7755 return N->getOperand(0);
7759 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7760 if (C->isNullValue() || // 0 >>s V -> 0.
7761 C->isAllOnesValue()) // -1 >>s V -> -1.
7762 return N->getOperand(0);
7765 case ISD::SIGN_EXTEND:
7766 case ISD::ZERO_EXTEND:
7767 case ISD::ANY_EXTEND:
7768 return DAGCombineExtBoolTrunc(N, DCI);
7771 case ISD::SELECT_CC:
7772 return DAGCombineTruncBoolExt(N, DCI);
7774 assert(TM.Options.UnsafeFPMath &&
7775 "Reciprocal estimates require UnsafeFPMath");
7777 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7779 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7780 if (RV.getNode() != 0) {
7781 DCI.AddToWorklist(RV.getNode());
7782 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7783 N->getOperand(0), RV);
7785 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7786 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7788 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7790 if (RV.getNode() != 0) {
7791 DCI.AddToWorklist(RV.getNode());
7792 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7793 N->getValueType(0), RV);
7794 DCI.AddToWorklist(RV.getNode());
7795 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7796 N->getOperand(0), RV);
7798 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7799 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7801 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7803 if (RV.getNode() != 0) {
7804 DCI.AddToWorklist(RV.getNode());
7805 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7806 N->getValueType(0), RV,
7807 N->getOperand(1).getOperand(1));
7808 DCI.AddToWorklist(RV.getNode());
7809 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7810 N->getOperand(0), RV);
7814 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7815 if (RV.getNode() != 0) {
7816 DCI.AddToWorklist(RV.getNode());
7817 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7818 N->getOperand(0), RV);
7824 assert(TM.Options.UnsafeFPMath &&
7825 "Reciprocal estimates require UnsafeFPMath");
7827 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7829 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7830 if (RV.getNode() != 0) {
7831 DCI.AddToWorklist(RV.getNode());
7832 RV = DAGCombineFastRecip(RV, DCI);
7833 if (RV.getNode() != 0) {
7834 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7835 // this case and force the answer to 0.
7837 EVT VT = RV.getValueType();
7839 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7840 if (VT.isVector()) {
7841 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7842 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7846 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7847 N->getOperand(0), Zero, ISD::SETEQ);
7848 DCI.AddToWorklist(ZeroCmp.getNode());
7849 DCI.AddToWorklist(RV.getNode());
7851 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7859 case ISD::SINT_TO_FP:
7860 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7861 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7862 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7863 // We allow the src/dst to be either f32/f64, but the intermediate
7864 // type must be i64.
7865 if (N->getOperand(0).getValueType() == MVT::i64 &&
7866 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7867 SDValue Val = N->getOperand(0).getOperand(0);
7868 if (Val.getValueType() == MVT::f32) {
7869 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7870 DCI.AddToWorklist(Val.getNode());
7873 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7874 DCI.AddToWorklist(Val.getNode());
7875 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7876 DCI.AddToWorklist(Val.getNode());
7877 if (N->getValueType(0) == MVT::f32) {
7878 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7879 DAG.getIntPtrConstant(0));
7880 DCI.AddToWorklist(Val.getNode());
7883 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7884 // If the intermediate type is i32, we can avoid the load/store here
7891 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7892 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7893 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7894 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7895 N->getOperand(1).getValueType() == MVT::i32 &&
7896 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7897 SDValue Val = N->getOperand(1).getOperand(0);
7898 if (Val.getValueType() == MVT::f32) {
7899 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7900 DCI.AddToWorklist(Val.getNode());
7902 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7903 DCI.AddToWorklist(Val.getNode());
7906 N->getOperand(0), Val, N->getOperand(2),
7907 DAG.getValueType(N->getOperand(1).getValueType())
7910 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7911 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7912 cast<StoreSDNode>(N)->getMemoryVT(),
7913 cast<StoreSDNode>(N)->getMemOperand());
7914 DCI.AddToWorklist(Val.getNode());
7918 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7919 if (cast<StoreSDNode>(N)->isUnindexed() &&
7920 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7921 N->getOperand(1).getNode()->hasOneUse() &&
7922 (N->getOperand(1).getValueType() == MVT::i32 ||
7923 N->getOperand(1).getValueType() == MVT::i16 ||
7924 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7925 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7926 N->getOperand(1).getValueType() == MVT::i64))) {
7927 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7928 // Do an any-extend to 32-bits if this is a half-word input.
7929 if (BSwapOp.getValueType() == MVT::i16)
7930 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7933 N->getOperand(0), BSwapOp, N->getOperand(2),
7934 DAG.getValueType(N->getOperand(1).getValueType())
7937 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7938 Ops, array_lengthof(Ops),
7939 cast<StoreSDNode>(N)->getMemoryVT(),
7940 cast<StoreSDNode>(N)->getMemOperand());
7944 LoadSDNode *LD = cast<LoadSDNode>(N);
7945 EVT VT = LD->getValueType(0);
7946 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7947 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7948 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7949 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7950 // FIXME: Update this for VSX!
7951 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7952 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7953 LD->getAlignment() < ABIAlignment) {
7954 // This is a type-legal unaligned Altivec load.
7955 SDValue Chain = LD->getChain();
7956 SDValue Ptr = LD->getBasePtr();
7958 // This implements the loading of unaligned vectors as described in
7959 // the venerable Apple Velocity Engine overview. Specifically:
7960 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7961 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7963 // The general idea is to expand a sequence of one or more unaligned
7964 // loads into a alignment-based permutation-control instruction (lvsl),
7965 // a series of regular vector loads (which always truncate their
7966 // input address to an aligned address), and a series of permutations.
7967 // The results of these permutations are the requested loaded values.
7968 // The trick is that the last "extra" load is not taken from the address
7969 // you might suspect (sizeof(vector) bytes after the last requested
7970 // load), but rather sizeof(vector) - 1 bytes after the last
7971 // requested vector. The point of this is to avoid a page fault if the
7972 // base address happened to be aligned. This works because if the base
7973 // address is aligned, then adding less than a full vector length will
7974 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7975 // the next vector will be fetched as you might suspect was necessary.
7977 // We might be able to reuse the permutation generation from
7978 // a different base address offset from this one by an aligned amount.
7979 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
7980 // optimization later.
7981 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
7982 DAG, dl, MVT::v16i8);
7984 // Refine the alignment of the original load (a "new" load created here
7985 // which was identical to the first except for the alignment would be
7986 // merged with the existing node regardless).
7987 MachineFunction &MF = DAG.getMachineFunction();
7988 MachineMemOperand *MMO =
7989 MF.getMachineMemOperand(LD->getPointerInfo(),
7990 LD->getMemOperand()->getFlags(),
7991 LD->getMemoryVT().getStoreSize(),
7993 LD->refineAlignment(MMO);
7994 SDValue BaseLoad = SDValue(LD, 0);
7996 // Note that the value of IncOffset (which is provided to the next
7997 // load's pointer info offset value, and thus used to calculate the
7998 // alignment), and the value of IncValue (which is actually used to
7999 // increment the pointer value) are different! This is because we
8000 // require the next load to appear to be aligned, even though it
8001 // is actually offset from the base pointer by a lesser amount.
8002 int IncOffset = VT.getSizeInBits() / 8;
8003 int IncValue = IncOffset;
8005 // Walk (both up and down) the chain looking for another load at the real
8006 // (aligned) offset (the alignment of the other load does not matter in
8007 // this case). If found, then do not use the offset reduction trick, as
8008 // that will prevent the loads from being later combined (as they would
8009 // otherwise be duplicates).
8010 if (!findConsecutiveLoad(LD, DAG))
8013 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8014 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8017 DAG.getLoad(VT, dl, Chain, Ptr,
8018 LD->getPointerInfo().getWithOffset(IncOffset),
8019 LD->isVolatile(), LD->isNonTemporal(),
8020 LD->isInvariant(), ABIAlignment);
8022 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8023 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8025 if (BaseLoad.getValueType() != MVT::v4i32)
8026 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8028 if (ExtraLoad.getValueType() != MVT::v4i32)
8029 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8031 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8032 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8034 if (VT != MVT::v4i32)
8035 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8037 // Now we need to be really careful about how we update the users of the
8038 // original load. We cannot just call DCI.CombineTo (or
8039 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8040 // uses created here (the permutation for example) that need to stay.
8041 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8043 SDUse &Use = UI.getUse();
8045 // Note: BaseLoad is checked here because it might not be N, but a
8047 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8048 User == TF.getNode() || Use.getResNo() > 1) {
8053 SDValue To = Use.getResNo() ? TF : Perm;
8056 SmallVector<SDValue, 8> Ops;
8057 for (SDNode::op_iterator O = User->op_begin(),
8058 OE = User->op_end(); O != OE; ++O) {
8065 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
8068 return SDValue(N, 0);
8072 case ISD::INTRINSIC_WO_CHAIN:
8073 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8074 Intrinsic::ppc_altivec_lvsl &&
8075 N->getOperand(1)->getOpcode() == ISD::ADD) {
8076 SDValue Add = N->getOperand(1);
8078 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8079 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8080 Add.getValueType().getScalarType().getSizeInBits()))) {
8081 SDNode *BasePtr = Add->getOperand(0).getNode();
8082 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8083 UE = BasePtr->use_end(); UI != UE; ++UI) {
8084 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8085 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8086 Intrinsic::ppc_altivec_lvsl) {
8087 // We've found another LVSL, and this address if an aligned
8088 // multiple of that one. The results will be the same, so use the
8089 // one we've just found instead.
8091 return SDValue(*UI, 0);
8099 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8100 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8101 N->getOperand(0).hasOneUse() &&
8102 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8103 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8104 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8105 N->getValueType(0) == MVT::i64))) {
8106 SDValue Load = N->getOperand(0);
8107 LoadSDNode *LD = cast<LoadSDNode>(Load);
8108 // Create the byte-swapping load.
8110 LD->getChain(), // Chain
8111 LD->getBasePtr(), // Ptr
8112 DAG.getValueType(N->getValueType(0)) // VT
8115 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8116 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8117 MVT::i64 : MVT::i32, MVT::Other),
8118 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8120 // If this is an i16 load, insert the truncate.
8121 SDValue ResVal = BSLoad;
8122 if (N->getValueType(0) == MVT::i16)
8123 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8125 // First, combine the bswap away. This makes the value produced by the
8127 DCI.CombineTo(N, ResVal);
8129 // Next, combine the load away, we give it a bogus result value but a real
8130 // chain result. The result value is dead because the bswap is dead.
8131 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8133 // Return N so it doesn't get rechecked!
8134 return SDValue(N, 0);
8138 case PPCISD::VCMP: {
8139 // If a VCMPo node already exists with exactly the same operands as this
8140 // node, use its result instead of this node (VCMPo computes both a CR6 and
8141 // a normal output).
8143 if (!N->getOperand(0).hasOneUse() &&
8144 !N->getOperand(1).hasOneUse() &&
8145 !N->getOperand(2).hasOneUse()) {
8147 // Scan all of the users of the LHS, looking for VCMPo's that match.
8148 SDNode *VCMPoNode = 0;
8150 SDNode *LHSN = N->getOperand(0).getNode();
8151 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8153 if (UI->getOpcode() == PPCISD::VCMPo &&
8154 UI->getOperand(1) == N->getOperand(1) &&
8155 UI->getOperand(2) == N->getOperand(2) &&
8156 UI->getOperand(0) == N->getOperand(0)) {
8161 // If there is no VCMPo node, or if the flag value has a single use, don't
8163 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8166 // Look at the (necessarily single) use of the flag value. If it has a
8167 // chain, this transformation is more complex. Note that multiple things
8168 // could use the value result, which we should ignore.
8169 SDNode *FlagUser = 0;
8170 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8171 FlagUser == 0; ++UI) {
8172 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8174 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8175 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8182 // If the user is a MFOCRF instruction, we know this is safe.
8183 // Otherwise we give up for right now.
8184 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8185 return SDValue(VCMPoNode, 0);
8190 SDValue Cond = N->getOperand(1);
8191 SDValue Target = N->getOperand(2);
8193 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8194 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8195 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8197 // We now need to make the intrinsic dead (it cannot be instruction
8199 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8200 assert(Cond.getNode()->hasOneUse() &&
8201 "Counter decrement has more than one use");
8203 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8204 N->getOperand(0), Target);
8209 // If this is a branch on an altivec predicate comparison, lower this so
8210 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8211 // lowering is done pre-legalize, because the legalizer lowers the predicate
8212 // compare down to code that is difficult to reassemble.
8213 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8214 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8216 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8217 // value. If so, pass-through the AND to get to the intrinsic.
8218 if (LHS.getOpcode() == ISD::AND &&
8219 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8220 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8221 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8222 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8223 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8225 LHS = LHS.getOperand(0);
8227 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8228 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8229 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8230 isa<ConstantSDNode>(RHS)) {
8231 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8232 "Counter decrement comparison is not EQ or NE");
8234 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8235 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8236 (CC == ISD::SETNE && !Val);
8238 // We now need to make the intrinsic dead (it cannot be instruction
8240 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8241 assert(LHS.getNode()->hasOneUse() &&
8242 "Counter decrement has more than one use");
8244 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8245 N->getOperand(0), N->getOperand(4));
8251 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8252 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8253 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8254 assert(isDot && "Can't compare against a vector result!");
8256 // If this is a comparison against something other than 0/1, then we know
8257 // that the condition is never/always true.
8258 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8259 if (Val != 0 && Val != 1) {
8260 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8261 return N->getOperand(0);
8262 // Always !=, turn it into an unconditional branch.
8263 return DAG.getNode(ISD::BR, dl, MVT::Other,
8264 N->getOperand(0), N->getOperand(4));
8267 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8269 // Create the PPCISD altivec 'dot' comparison node.
8271 LHS.getOperand(2), // LHS of compare
8272 LHS.getOperand(3), // RHS of compare
8273 DAG.getConstant(CompareOpc, MVT::i32)
8275 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8276 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8278 // Unpack the result based on how the target uses it.
8279 PPC::Predicate CompOpc;
8280 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8281 default: // Can't happen, don't crash on invalid number though.
8282 case 0: // Branch on the value of the EQ bit of CR6.
8283 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8285 case 1: // Branch on the inverted value of the EQ bit of CR6.
8286 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8288 case 2: // Branch on the value of the LT bit of CR6.
8289 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8291 case 3: // Branch on the inverted value of the LT bit of CR6.
8292 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8296 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8297 DAG.getConstant(CompOpc, MVT::i32),
8298 DAG.getRegister(PPC::CR6, MVT::i32),
8299 N->getOperand(4), CompNode.getValue(1));
8308 //===----------------------------------------------------------------------===//
8309 // Inline Assembly Support
8310 //===----------------------------------------------------------------------===//
8312 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8315 const SelectionDAG &DAG,
8316 unsigned Depth) const {
8317 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8318 switch (Op.getOpcode()) {
8320 case PPCISD::LBRX: {
8321 // lhbrx is known to have the top bits cleared out.
8322 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8323 KnownZero = 0xFFFF0000;
8326 case ISD::INTRINSIC_WO_CHAIN: {
8327 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8329 case Intrinsic::ppc_altivec_vcmpbfp_p:
8330 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8331 case Intrinsic::ppc_altivec_vcmpequb_p:
8332 case Intrinsic::ppc_altivec_vcmpequh_p:
8333 case Intrinsic::ppc_altivec_vcmpequw_p:
8334 case Intrinsic::ppc_altivec_vcmpgefp_p:
8335 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8336 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8337 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8338 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8339 case Intrinsic::ppc_altivec_vcmpgtub_p:
8340 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8341 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8342 KnownZero = ~1U; // All bits but the low one are known to be zero.
8350 /// getConstraintType - Given a constraint, return the type of
8351 /// constraint it is for this target.
8352 PPCTargetLowering::ConstraintType
8353 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8354 if (Constraint.size() == 1) {
8355 switch (Constraint[0]) {
8362 return C_RegisterClass;
8364 // FIXME: While Z does indicate a memory constraint, it specifically
8365 // indicates an r+r address (used in conjunction with the 'y' modifier
8366 // in the replacement string). Currently, we're forcing the base
8367 // register to be r0 in the asm printer (which is interpreted as zero)
8368 // and forming the complete address in the second register. This is
8372 } else if (Constraint == "wc") { // individual CR bits.
8373 return C_RegisterClass;
8374 } else if (Constraint == "wa" || Constraint == "wd" ||
8375 Constraint == "wf" || Constraint == "ws") {
8376 return C_RegisterClass; // VSX registers.
8378 return TargetLowering::getConstraintType(Constraint);
8381 /// Examine constraint type and operand type and determine a weight value.
8382 /// This object must already have been set up with the operand type
8383 /// and the current alternative constraint selected.
8384 TargetLowering::ConstraintWeight
8385 PPCTargetLowering::getSingleConstraintMatchWeight(
8386 AsmOperandInfo &info, const char *constraint) const {
8387 ConstraintWeight weight = CW_Invalid;
8388 Value *CallOperandVal = info.CallOperandVal;
8389 // If we don't have a value, we can't do a match,
8390 // but allow it at the lowest weight.
8391 if (CallOperandVal == NULL)
8393 Type *type = CallOperandVal->getType();
8395 // Look at the constraint type.
8396 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8397 return CW_Register; // an individual CR bit.
8398 else if ((StringRef(constraint) == "wa" ||
8399 StringRef(constraint) == "wd" ||
8400 StringRef(constraint) == "wf") &&
8403 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8406 switch (*constraint) {
8408 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8411 if (type->isIntegerTy())
8412 weight = CW_Register;
8415 if (type->isFloatTy())
8416 weight = CW_Register;
8419 if (type->isDoubleTy())
8420 weight = CW_Register;
8423 if (type->isVectorTy())
8424 weight = CW_Register;
8427 weight = CW_Register;
8436 std::pair<unsigned, const TargetRegisterClass*>
8437 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8439 if (Constraint.size() == 1) {
8440 // GCC RS6000 Constraint Letters
8441 switch (Constraint[0]) {
8443 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8444 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8445 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8447 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8448 return std::make_pair(0U, &PPC::G8RCRegClass);
8449 return std::make_pair(0U, &PPC::GPRCRegClass);
8451 if (VT == MVT::f32 || VT == MVT::i32)
8452 return std::make_pair(0U, &PPC::F4RCRegClass);
8453 if (VT == MVT::f64 || VT == MVT::i64)
8454 return std::make_pair(0U, &PPC::F8RCRegClass);
8457 return std::make_pair(0U, &PPC::VRRCRegClass);
8459 return std::make_pair(0U, &PPC::CRRCRegClass);
8461 } else if (Constraint == "wc") { // an individual CR bit.
8462 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8463 } else if (Constraint == "wa" || Constraint == "wd" ||
8464 Constraint == "wf" || Constraint == "ws") {
8465 return std::make_pair(0U, &PPC::VSRCRegClass);
8468 std::pair<unsigned, const TargetRegisterClass*> R =
8469 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8471 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8472 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8473 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8475 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8476 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8477 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8478 PPC::GPRCRegClass.contains(R.first)) {
8479 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8480 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8481 PPC::sub_32, &PPC::G8RCRegClass),
8482 &PPC::G8RCRegClass);
8489 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8490 /// vector. If it is invalid, don't add anything to Ops.
8491 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8492 std::string &Constraint,
8493 std::vector<SDValue>&Ops,
8494 SelectionDAG &DAG) const {
8495 SDValue Result(0,0);
8497 // Only support length 1 constraints.
8498 if (Constraint.length() > 1) return;
8500 char Letter = Constraint[0];
8511 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8512 if (!CST) return; // Must be an immediate to match.
8513 unsigned Value = CST->getZExtValue();
8515 default: llvm_unreachable("Unknown constraint letter!");
8516 case 'I': // "I" is a signed 16-bit constant.
8517 if ((short)Value == (int)Value)
8518 Result = DAG.getTargetConstant(Value, Op.getValueType());
8520 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8521 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8522 if ((short)Value == 0)
8523 Result = DAG.getTargetConstant(Value, Op.getValueType());
8525 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8526 if ((Value >> 16) == 0)
8527 Result = DAG.getTargetConstant(Value, Op.getValueType());
8529 case 'M': // "M" is a constant that is greater than 31.
8531 Result = DAG.getTargetConstant(Value, Op.getValueType());
8533 case 'N': // "N" is a positive constant that is an exact power of two.
8534 if ((int)Value > 0 && isPowerOf2_32(Value))
8535 Result = DAG.getTargetConstant(Value, Op.getValueType());
8537 case 'O': // "O" is the constant zero.
8539 Result = DAG.getTargetConstant(Value, Op.getValueType());
8541 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8542 if ((short)-Value == (int)-Value)
8543 Result = DAG.getTargetConstant(Value, Op.getValueType());
8550 if (Result.getNode()) {
8551 Ops.push_back(Result);
8555 // Handle standard constraint letters.
8556 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8559 // isLegalAddressingMode - Return true if the addressing mode represented
8560 // by AM is legal for this target, for a load/store of the specified type.
8561 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8563 // FIXME: PPC does not allow r+i addressing modes for vectors!
8565 // PPC allows a sign-extended 16-bit immediate field.
8566 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8569 // No global is ever allowed as a base.
8573 // PPC only support r+r,
8575 case 0: // "r+i" or just "i", depending on HasBaseReg.
8578 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8580 // Otherwise we have r+r or r+i.
8583 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8585 // Allow 2*r as r+r.
8588 // No other scales are supported.
8595 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8596 SelectionDAG &DAG) const {
8597 MachineFunction &MF = DAG.getMachineFunction();
8598 MachineFrameInfo *MFI = MF.getFrameInfo();
8599 MFI->setReturnAddressIsTaken(true);
8601 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8605 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8607 // Make sure the function does not optimize away the store of the RA to
8609 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8610 FuncInfo->setLRStoreRequired();
8611 bool isPPC64 = PPCSubTarget.isPPC64();
8612 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8615 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8618 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8619 isPPC64? MVT::i64 : MVT::i32);
8620 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8621 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8623 MachinePointerInfo(), false, false, false, 0);
8626 // Just load the return address off the stack.
8627 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8628 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8629 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8632 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8633 SelectionDAG &DAG) const {
8635 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8637 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8638 bool isPPC64 = PtrVT == MVT::i64;
8640 MachineFunction &MF = DAG.getMachineFunction();
8641 MachineFrameInfo *MFI = MF.getFrameInfo();
8642 MFI->setFrameAddressIsTaken(true);
8644 // Naked functions never have a frame pointer, and so we use r1. For all
8645 // other functions, this decision must be delayed until during PEI.
8647 if (MF.getFunction()->getAttributes().hasAttribute(
8648 AttributeSet::FunctionIndex, Attribute::Naked))
8649 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8651 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8653 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8656 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8657 FrameAddr, MachinePointerInfo(), false, false,
8663 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8664 // The PowerPC target isn't yet aware of offsets.
8668 /// getOptimalMemOpType - Returns the target specific optimal type for load
8669 /// and store operations as a result of memset, memcpy, and memmove
8670 /// lowering. If DstAlign is zero that means it's safe to destination
8671 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8672 /// means there isn't a need to check it against alignment requirement,
8673 /// probably because the source does not need to be loaded. If 'IsMemset' is
8674 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8675 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8676 /// source is constant so it does not need to be loaded.
8677 /// It returns EVT::Other if the type should be determined using generic
8678 /// target-independent logic.
8679 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8680 unsigned DstAlign, unsigned SrcAlign,
8681 bool IsMemset, bool ZeroMemset,
8683 MachineFunction &MF) const {
8684 if (this->PPCSubTarget.isPPC64()) {
8691 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8694 if (DisablePPCUnaligned)
8697 // PowerPC supports unaligned memory access for simple non-vector types.
8698 // Although accessing unaligned addresses is not as efficient as accessing
8699 // aligned addresses, it is generally more efficient than manual expansion,
8700 // and generally only traps for software emulation when crossing page
8706 if (VT.getSimpleVT().isVector())
8709 if (VT == MVT::ppcf128)
8718 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8719 VT = VT.getScalarType();
8724 switch (VT.getSimpleVT().SimpleTy) {
8735 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8736 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8737 return TargetLowering::getSchedulingPreference(N);
8742 // Create a fast isel object.
8744 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8745 const TargetLibraryInfo *LibInfo) const {
8746 return PPC::createFastISel(FuncInfo, LibInfo);